我正在尝试使用 pytest 对postgresql数据库运行一些简单的集成测试。我必须使用 python 2.7 ,所以不能选择 testcontainers 。
我的 conftest.py 如下:
import pytest
import docker # his is a official system docker package
@pytest.fixture(scope="session")
def finalizer_function(container_id):
container_id.stop()
@pytest.fixture(scope="session", autouse=True)
def db_init():
"""
This db_init() method will start up docker container
which will be used throughout all the tests and once
all the tests are completed, containers will be
automatically removed.
:return:
"""
client = docker.from_env()
con_id = client.containers.run(
image="postgres:9.6",
name="postgres",
detach=True,
environment={
'POSTGRES_DB': 'postgres',
'POSTGRES_PASSWORD': 'test',
'POSTGRES_USER': 'postgres',
},
remove=True,
ports={"5432/tcp": 5432}
)
# yield con_id.stop()
这是一个非常基本的测试,我无法运行 test_postgres.py :
import docker
import socket
import psycopg2
from postgres import Postgres
def test_connection_to_db(db_init):
"""
:param db_init:
:return:
"""
print(socket.gethostname())
dbo = Postgres(
default_dbuser='postgres',
default_db='postgres',
host='127.0.0.1',
password='test',
port='5432'
)
_superuser = 'userx'
dbo.create_user(user=_superuser, password='start123', superuser=True)
认为from postgres import Postgres
是我的自定义 postgres
没问题的模块。
PYTHONPATH=lib pytest -s -vv tests/test_postgres.py
...
E OperationalError: server closed the connection unexpectedly
E This probably means the server terminated abnormally
E before or while processing the request.
但是,当我使用 fixture 启动docker容器时, db_init 并且我尝试使用 psql 连接到该容器,我可以毫无问题地连接到数据库:
psql -h 127.0.0.1 -p 5432 -U postgres -d postgres
Password for user postgres:
psql (10.6, server 9.6.12)
Type "help" for help.
postgres=#
请告知,我肯定只是一个愚蠢的错误。
Thx