2026-08-23 22:35:59 +08:00
|
|
|
|
# -*- coding: utf-8 -*-
|
2026-08-24 00:34:28 +08:00
|
|
|
|
"""共享夹具:临时 SQLite 数据库 + TestClient(auth 与 rbac 测试共用)。
|
2026-08-23 22:35:59 +08:00
|
|
|
|
|
2026-08-24 00:34:28 +08:00
|
|
|
|
方案:monkeypatch config.DATABASE_URL 为临时异步 SQLite,让应用 lifespan 在
|
|
|
|
|
|
TestClient 自身的事件循环内建库/种子,避免异步引擎跨事件循环问题。测试函数
|
|
|
|
|
|
保持同步(TestClient 内部驱动 async 应用)。
|
|
|
|
|
|
"""
|
|
|
|
|
|
from __future__ import annotations
|
2026-08-23 23:59:34 +08:00
|
|
|
|
|
2026-08-23 22:35:59 +08:00
|
|
|
|
import pytest
|
|
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
|
|
|
2026-08-24 00:34:28 +08:00
|
|
|
|
from app import config as app_config
|
2026-08-23 22:35:59 +08:00
|
|
|
|
from app.main import app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture()
|
2026-08-24 00:34:28 +08:00
|
|
|
|
def client(tmp_path, monkeypatch):
|
|
|
|
|
|
"""把数据库指向临时 SQLite,保证测试隔离。"""
|
|
|
|
|
|
monkeypatch.setattr(
|
|
|
|
|
|
app_config, "DATABASE_URL", f"sqlite+aiosqlite:///{tmp_path}/test.db",
|
|
|
|
|
|
)
|
|
|
|
|
|
# 清掉上一测试残留的 app.state.db,强制 lifespan 用当前 tmp URL 新建库
|
|
|
|
|
|
if hasattr(app.state, "db"):
|
|
|
|
|
|
app.state.db = None
|
2026-08-23 22:35:59 +08:00
|
|
|
|
with TestClient(app) as c:
|
|
|
|
|
|
yield c
|