api / tests /conftest.py
hanbinsite's picture
feat: complete core feature improvements
bf34e9d
Raw History Blame Contribute Delete
3.37 kB
import pytest
import pytest_asyncio
from httpx import AsyncClient, ASGITransport
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from app.database import Base, get_db
from app.utils.auth import hash_password
TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"
test_engine = create_async_engine(
TEST_DATABASE_URL,
connect_args={"check_same_thread": False},
)
TestSessionLocal = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
# 当前测试用的 session(每个 test 独立)
_current_session: AsyncSession | None = None
async def override_get_db():
"""
优先复用测试 session(保证 db_session 写入的数据对 HTTP 请求可见),
没有共享 session 时自己创建一个(用于不需要预置数据的测试)
"""
if _current_session is not None:
yield _current_session
else:
async with TestSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
@pytest_asyncio.fixture(autouse=True)
async def setup_db():
async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
@pytest_asyncio.fixture
async def db_session(setup_db):
global _current_session
async with TestSessionLocal() as session:
_current_session = session
try:
yield session
finally:
_current_session = None
await session.rollback()
@pytest_asyncio.fixture
async def client(setup_db):
from app.main import app
from app.limiter import limiter
app.dependency_overrides[get_db] = override_get_db
limiter.enabled = False
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
yield ac
app.dependency_overrides.clear()
limiter.enabled = True
@pytest_asyncio.fixture
async def superadmin_token(client, db_session):
"""创建超级管理员并返回 token"""
from app.models.admin import Admin
from app.models.role import Role, AdminRole
admin = Admin(
username="test_superadmin",
password_hash=hash_password("Test@123456"),
nickname="Test SuperAdmin",
is_active=True,
)
db_session.add(admin)
await db_session.flush()
role = Role(name="超级管理员", code="super_admin", is_builtin=True, status=1)
db_session.add(role)
await db_session.flush()
db_session.add(AdminRole(admin_id=admin.id, role_id=role.id))
await db_session.commit()
resp = await client.post("/admin/auth/login", json={
"username": "test_superadmin",
"password": "Test@123456",
})
return resp.json()["data"]["accessToken"]
@pytest_asyncio.fixture
async def user_token(client, db_session):
"""通过 HTTP 注册普通用户并返回 token(数据写入共享 session,对后续请求可见)"""
resp = await client.post("/user/auth/register", json={
"username": "testuser",
"password": "Test@123456",
})
assert resp.json()["code"] == 0, f"register failed: {resp.json()}"
return resp.json()["data"]["accessToken"]