Files
geMoldInsight/tests/test_route_load_status.py
T

78 lines
3.0 KiB
Python
Raw Normal View History

"""批次 3 回归:路由装载失败显式化(_safe_include 不再静默跳过)。
- 非 DEBUG:失败记录进 route_registry,/api/health 呈现 degraded
- DEBUG:装载失败直接抛错(fail fast,开发期当场暴露)
- 注册表状态在测试间隔离(真实 app 在导入期已登记 loaded 列表)
"""
import pytest
from fastapi import FastAPI
from httpx import AsyncClient, ASGITransport
from shared.config.settings import settings
from moldinsight.api import _safe_include
from moldinsight.api.route_registry import route_load_status
from moldinsight.api.health_router import router as health_router
@pytest.fixture(autouse=True)
def clean_registry():
"""清空注册表并在测试后还原真实 app 导入期登记的状态。"""
snapshot = {k: list(v) for k, v in route_load_status.items()}
for items in route_load_status.values():
items.clear()
yield
for items in route_load_status.values():
items.clear()
for key, items in snapshot.items():
route_load_status[key].extend(items)
def test_failed_route_recorded_not_silent(monkeypatch):
"""非 DEBUG:装载失败必须留下显式记录(此前仅 WARNING 日志后静默跳过)。"""
monkeypatch.setattr(settings, "DEBUG", False)
_safe_include("不存在", "moldinsight.api.definitely_missing_module")
failed = route_load_status["failed"]
assert len(failed) == 1
assert failed[0]["label"] == "不存在"
assert failed[0]["module"] == "moldinsight.api.definitely_missing_module"
assert "error" in failed[0]
def test_failed_route_raises_in_debug(monkeypatch):
"""DEBUG:装载失败直接抛错,禁止带病启动。"""
monkeypatch.setattr(settings, "DEBUG", True)
with pytest.raises(ModuleNotFoundError):
_safe_include("不存在", "moldinsight.api.definitely_missing_module")
def test_debug_only_route_disabled_when_debug_off(monkeypatch):
monkeypatch.setattr(settings, "DEBUG", False)
_safe_include("调试", "moldinsight.api.debug_router", debug_only=True)
assert route_load_status["disabled"][0]["module"] == "moldinsight.api.debug_router"
assert route_load_status["failed"] == []
@pytest.mark.asyncio
async def test_health_reports_degraded_and_failed_routes(monkeypatch):
"""health 必须暴露失败路由清单并将 status 置为 degraded。"""
monkeypatch.setattr(settings, "DEBUG", False)
_safe_include("不存在", "moldinsight.api.definitely_missing_module")
test_app = FastAPI()
test_app.include_router(health_router, prefix="/api")
transport = ASGITransport(app=test_app)
async with AsyncClient(transport=transport, base_url="http://test") as ac:
resp = await ac.get("/api/health")
assert resp.status_code == 200
body = resp.json()
assert body["status"] == "degraded"
assert body["routes"]["failed"][0]["module"] == "moldinsight.api.definitely_missing_module"
# 真实探测而非硬编码(布尔类型即可,具体值取决于环境是否安装 OCC)
assert isinstance(body["pythonocc"], bool)