搭好异步测试基础设施(续)
# tests/conftest.py
import pytest
import pytest_asyncio
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from app.database import Base, get_db
from app.main import app
TEST_DATABASE_URL = "postgresql+asyncpg://user:pass@localhost/test_db"
engine = create_async_engine(TEST_DATABASE_URL)
@pytest_asyncio.fixture(scope="session", autouse=True)
async def create_tables():
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
@pytest_asyncio.fixture
async def db_session():
async with engine.connect() as conn:
await conn.begin() # 外层事务
async with AsyncSession(
conn,
join_transaction_mode="create_savepoint", # 关键配置
) as session:
yield session
await session.rollback() # 回滚到 savepoint