Files

70 lines
2.7 KiB
Python

"""Leaderboard reads must not expose the removed per-user analytics queries."""
from types import SimpleNamespace
import pytest
from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient
from app.gateway.routers import admin_users
def _app() -> FastAPI:
app = FastAPI()
app.include_router(admin_users.router)
return app
@pytest.mark.asyncio
async def test_removed_analytics_url_never_opens_a_database_session(monkeypatch):
def unexpected_session():
pytest.fail("The retired analytics endpoint must not touch the database")
monkeypatch.setattr(admin_users, "get_session_factory", unexpected_session)
app = _app()
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
response = await client.get("/api/admin/users/sample-user/analytics?days=7")
assert response.status_code == 404
assert not any(path.endswith("/analytics") for path in app.openapi()["paths"])
@pytest.mark.asyncio
async def test_leaderboard_still_returns_aggregate_snapshot(monkeypatch):
async def current_admin(_request):
return SimpleNamespace(system_role="admin")
async def snapshot(_factory, _settings, since, until, **_kwargs):
return admin_users.AdminLeaderboardResponse(
range_days=7,
since=since.isoformat(),
until=until.isoformat(),
overview=admin_users.AdminLeaderboardOverview(total_users=2, total_runs=12),
)
monkeypatch.setattr(admin_users, "get_current_user_from_request", current_admin)
monkeypatch.setattr(admin_users, "get_session_factory", lambda: object())
monkeypatch.setattr(admin_users, "load_system_settings", lambda: SimpleNamespace(leaderboard=object()))
monkeypatch.setattr(admin_users, "_load_or_schedule_daily_leaderboard", snapshot)
async with AsyncClient(transport=ASGITransport(app=_app()), base_url="http://test") as client:
response = await client.get("/api/admin/users/leaderboard?days=7")
assert response.status_code == 200
assert response.json()["overview"]["total_runs"] == 12
@pytest.mark.asyncio
async def test_leaderboard_keeps_admin_authorization(monkeypatch):
async def ordinary_user(_request):
return SimpleNamespace(system_role="user")
def unexpected_session():
pytest.fail("Authorization must precede database access")
monkeypatch.setattr(admin_users, "get_current_user_from_request", ordinary_user)
monkeypatch.setattr(admin_users, "get_session_factory", unexpected_session)
async with AsyncClient(transport=ASGITransport(app=_app()), base_url="http://test") as client:
response = await client.get("/api/admin/users/leaderboard?days=7")
assert response.status_code == 403