test: 平台测试套件适配异步四层,66 全绿
- conftest 改为 monkeypatch DATABASE_URL + lifespan 建库(解决异步引擎跨事件循环) - 修复 seed_data 辅助函数 await、_to_dict 链式 await、get_current_user await - 修复 Database.initialize 建表于本实例引擎 - 平台 19 路由全部经异步接口回归通过
This commit is contained in:
+15
-10
@@ -1,22 +1,27 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""共享夹具:临时 SQLite 数据库 + TestClient(auth 与 rbac 测试共用)。"""
|
||||
from __future__ import annotations
|
||||
"""共享夹具:临时 SQLite 数据库 + TestClient(auth 与 rbac 测试共用)。
|
||||
|
||||
import asyncio
|
||||
方案:monkeypatch config.DATABASE_URL 为临时异步 SQLite,让应用 lifespan 在
|
||||
TestClient 自身的事件循环内建库/种子,避免异步引擎跨事件循环问题。测试函数
|
||||
保持同步(TestClient 内部驱动 async 应用)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import config as app_config
|
||||
from app.main import app
|
||||
from app.infrastructure.repositories import Database
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(tmp_path):
|
||||
"""把 app.state.db 换成指向临时 SQLite 的 Database,保证测试隔离。"""
|
||||
db = Database(db_url=f"sqlite+aiosqlite:///{tmp_path}/test.db")
|
||||
asyncio.run(db.initialize())
|
||||
app.state.db = db
|
||||
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
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
asyncio.run(db.close())
|
||||
|
||||
Reference in New Issue
Block a user