"""pytest 夹具:统一连接 PostgreSQL 测试库(ADR-024,不用 SQLite 替代)。""" import os import pytest from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from app import models # noqa: F401 注册模型 from app.db.base import Base TEST_DATABASE_URL = os.environ.get( "TEST_DATABASE_URL", "postgresql+asyncpg://hunjing:hunjing_dev_password@127.0.0.1:5432/hunjing_test", ) @pytest.fixture async def db() -> async_sessionmaker[AsyncSession]: """每个测试重建 schema:隔离且可重复。""" engine = create_async_engine(TEST_DATABASE_URL) async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await conn.run_sync(Base.metadata.create_all) factory = async_sessionmaker(engine, expire_on_commit=False) yield factory await engine.dispose() @pytest.fixture async def client(db): """连接测试库的应用客户端(覆盖 get_db)。""" from httpx import ASGITransport, AsyncClient from app.db import session as db_session from app.main import create_app app = create_app() async def override(): async with db() as session: try: yield session await session.commit() except Exception: await session.rollback() raise app.dependency_overrides[db_session.get_db] = override transport = ASGITransport(app=app, raise_app_exceptions=False) async with AsyncClient(transport=transport, base_url="https://test") as c: yield c async def login(client, email: str) -> dict[str, str]: """开发档登录:返回需附加的请求头(Cookie 由客户端自动携带)。""" resp = await client.post("/v1/auth/sessions", json={"email": email}) assert resp.status_code == 201, resp.text return {"Hunjing-CSRF-Token": resp.json()["csrf_token"]}