File size: 3,370 Bytes
bf34e9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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"]