Files
life-echo/api/tests/evaluation/test_internal_router_auth.py

66 lines
2.1 KiB
Python

"""内部路由在未配密钥时应 503。"""
import pytest
from httpx import ASGITransport, AsyncClient
from app.features.evaluation.internal_auth import get_internal_eval_principal
from app.features.evaluation.router import router
@pytest.mark.asyncio
async def test_internal_eval_list_sets_requires_config(monkeypatch: pytest.MonkeyPatch):
from fastapi import FastAPI
monkeypatch.setattr(
"app.core.config.settings.internal_eval_api_key",
"",
raising=False,
)
app = FastAPI()
app.include_router(router, prefix="/internal/api/evaluation")
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://t") as client:
r = await client.get("/internal/api/evaluation/regression-sets")
assert r.status_code == 503
@pytest.mark.asyncio
async def test_internal_eval_with_override_lists_empty(monkeypatch: pytest.MonkeyPatch):
from fastapi import FastAPI
monkeypatch.setattr(
"app.core.config.settings.internal_eval_api_key",
"secret",
raising=False,
)
app = FastAPI()
app.include_router(router, prefix="/internal/api/evaluation")
async def _override_auth():
from app.features.evaluation.internal_auth import InternalEvalPrincipal
return InternalEvalPrincipal()
app.dependency_overrides[get_internal_eval_principal] = _override_auth
from app.core.db import get_async_db
from unittest.mock import AsyncMock, MagicMock
mock_session = AsyncMock()
mock_result = MagicMock()
mock_result.scalars.return_value.unique.return_value.all.return_value = []
mock_session.execute = AsyncMock(return_value=mock_result)
async def _db():
yield mock_session
app.dependency_overrides[get_async_db] = _db
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://t") as client:
r = await client.get(
"/internal/api/evaluation/regression-sets",
headers={"X-Internal-Eval-Key": "secret"},
)
assert r.status_code == 200
assert r.json() == []