conftest.py
2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""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()