conftest.py 2 KB
"""pytest 测试配置"""
import asyncio
from typing import AsyncGenerator
import pytest
import pytest_asyncio
from httpx import AsyncClient, ASGITransport
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker

from app.core.database import Base, get_db
from app.core.config import settings
from app.main import app


# 使用 SQLite 内存数据库进行测试
TEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"

# 如果 aiosqlite 不可用,使用同步方式
try:
    import aiosqlite
    HAS_AIOSQLITE = True
except ImportError:
    HAS_AIOSQLITE = False

# 为测试覆盖 db_url
_test_engine = None
_test_session_factory = None


def _get_test_engine():
    global _test_engine
    if _test_engine is None:
        if HAS_AIOSQLITE:
            _test_engine = create_async_engine(TEST_DATABASE_URL, echo=True)
        else:
            # 使用 SQLAlchemy 的 NullPool 模式,回退到同步 SQLite
            pytest.skip("aiosqlite 未安装,跳过异步数据库测试")
    return _test_engine


@pytest_asyncio.fixture
async def db_session() -> AsyncGenerator[AsyncSession, None]:
    """创建测试数据库会话,每次测试后回滚"""
    engine = _get_test_engine()
    session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    async with session_factory() as session:
        yield session
        await session.rollback()

    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)


@pytest_asyncio.fixture
async def client(db_session: AsyncSession) -> AsyncGenerator[AsyncClient, None]:
    """创建测试 HTTP 客户端"""

    async def _override_get_db():
        yield db_session

    app.dependency_overrides[get_db] = _override_get_db

    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as ac:
        yield ac

    app.dependency_overrides.clear()