我想通过 pytest 中的 alembic 连接到 postgresql 数据库。我可以使用我设置的密码通过 pg admin 连接到数据库,但我总是收到错误:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "testuser"
代码位于 VisualStudio 代码中并在 WSL 中打开。
docker postgresql 数据库
docker run -d --rm --name postgres-container -e POSTGRES_USER=testuser-e POSTGRES_PASSWORD=examplepass -p 5432:5432 postgres:latest
pytest.ini
[pytest]
verbosity_assertions = 1
env =
DB_PASS=examplepass
DB_USER=testuser
DB_HOST=localhost
DB_NAME=testdb
DB_PORT=5432
conftest.py设置
@pytest.fixture(scope='module')
def connection_string():
return f'postgresql://{os.getenv("DB_USER")}:{os.getenv("DB_PASS")}@{os.getenv("DB_HOST")}/{os.getenv("DB_NAME")}'
@pytest.fixture(scope='module')
def engine(connection_string):
logging.info(connection_string)
engine = create_engine(connection_string)
logging.info(engine.url)
return engine
@pytest.fixture(scope='module')
def tables(engine):
alembic_cfg = AlembicConfig("alembic.ini")
alembic_cfg.set_main_option('sqlalchemy.url', str(engine.url))
command.upgrade(alembic_cfg, "head")
yield
command.downgrade(alembic_cfg, "base")
@pytest.fixture(scope='module')
def session(engine, tables, context):
"""Returns an sqlalchemy session, and after the test tears down everything properly."""
connection = engine.connect()
Session = sessionmaker(bind=connection)
session = Session()
# inserts example tables
insert_into_tables(session, context)
yield session
测试文件.py
sys.path.append(".")
from sqlalchemy import text
def test_db_setup(session):
# Try to execute a simple query to check if a table exists
result_table_exists = session.execute(text("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'task')"))
日志输出显示正确的 URL
INFO root:conftest.py:47 postgresql://testuser:examplepass@localhost/testdb
INFO root:conftest.py:49 postgresql://testuser:***@localhost/testdb
“testuser”和“-e”之间缺少一个空格。 使用以下命令
docker run -d --rm --name postgres-container -e POSTGRES_USER=testuser -e POSTGRES_PASSWORD=examplepass -p 5432:5432 postgres:latest