a869b2934a
- conftest 改为 monkeypatch DATABASE_URL + lifespan 建库(解决异步引擎跨事件循环) - 修复 seed_data 辅助函数 await、_to_dict 链式 await、get_current_user await - 修复 Database.initialize 建表于本实例引擎 - 平台 19 路由全部经异步接口回归通过
28 lines
959 B
Python
28 lines
959 B
Python
# -*- coding: utf-8 -*-
|
||
"""共享夹具:临时 SQLite 数据库 + TestClient(auth 与 rbac 测试共用)。
|
||
|
||
方案: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
|
||
|
||
|
||
@pytest.fixture()
|
||
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
|