Files

28 lines
959 B
Python
Raw Permalink Normal View History

# -*- coding: utf-8 -*-
"""共享夹具:临时 SQLite 数据库 + TestClientauth 与 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