Files
smeta-web/tests/test_admin_dashboard_api.py

113 lines
4.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""P2.3: dashboard одним ответом, визит, кэш 15 с, admin-only."""
import importlib
import os
import sys
import pytest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
@pytest.fixture()
def env(tmp_path, monkeypatch):
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
monkeypatch.setenv("SESSION_SECRET", "test-secret")
monkeypatch.setenv("AI_BACKEND", "claude")
monkeypatch.chdir(ROOT)
import auth
import db
import main
import admin_api
for m in (db, auth, main, admin_api):
importlib.reload(m)
db.init_db()
db.create_user("boss@x", auth.hash_password("Passw0rd!ok"), role="admin")
db.admin_verify_user("boss@x")
db.create_user("joe@x", auth.hash_password("Passw0rd!ok"))
db.admin_verify_user("joe@x")
from fastapi.testclient import TestClient
client = TestClient(main.app)
admin_api._CACHE["ts"] = 0.0
admin_api._CACHE["data"] = None
h = {"Authorization": "Bearer " + auth._make_token("boss@x", "admin")}
return db, client, h
def test_dashboard_returns_one_snapshot(env):
db, client, h = env
r = client.get("/api/admin/v2/dashboard", headers=h)
assert r.status_code == 200, r.text
d = r.json()
assert d["user"] == "boss@x"
assert {"work_24h", "money", "attention", "last_visit"} <= set(d)
assert "revenue_rub" in d["money"] and "accounts_total_rub" in d["money"]
def test_visit_returns_previous(env):
db, client, h = env
assert client.post("/api/admin/v2/visit", headers=h).json()["previous"] is None
second = client.post("/api/admin/v2/visit", headers=h).json()
assert second["previous"] is not None
def test_dashboard_is_cached_for_15_seconds(env, monkeypatch):
db, client, h = env
import admin_api
calls = {"n": 0}
real = admin_api._build
def counted(user):
calls["n"] += 1
return real(user)
monkeypatch.setattr(admin_api, "_build", counted)
assert client.get("/api/admin/v2/dashboard", headers=h).status_code == 200
assert client.get("/api/admin/v2/dashboard", headers=h).status_code == 200
assert calls["n"] == 1
client.post("/api/admin/v2/visit", headers=h)
assert client.get("/api/admin/v2/dashboard", headers=h).status_code == 200
# визит больше не сбрасывает кэш: personal-поля дописываются поверх
assert calls["n"] == 1
def test_dashboard_is_admin_only(env):
db, client, h = env
import auth
user = {"Authorization": "Bearer " + auth._make_token("joe@x", "user")}
assert client.get("/api/admin/v2/dashboard", headers=user).status_code == 403
assert client.get("/api/admin/v2/dashboard").status_code in (401, 403)
def test_cache_is_common_and_personal_fields_are_not_cached(env):
db, client, h = env
import auth
db.create_user("boss2@x", auth.hash_password("Passw0rd!ok"), role="admin")
db.admin_verify_user("boss2@x")
h2 = {"Authorization": "Bearer " + auth._make_token("boss2@x", "admin")}
first = client.get("/api/admin/v2/dashboard", headers=h).json()
second = client.get("/api/admin/v2/dashboard", headers=h2).json()
assert first["user"] == "boss@x"
assert second["user"] == "boss2@x"
assert second["last_visit"] is None # чужой визит не протёк
# Второй запрос в пределах TTL не видит изменений базы — это кэш, а не пересчёт.
db.add_account_entry("joe@x", 500.0, "взнос", "boss@x")
third = client.get("/api/admin/v2/dashboard", headers=h).json()
assert third["money"]["accounts_total_rub"] == first["money"]["accounts_total_rub"]
def test_attention_has_real_unpriced_and_p95(env):
db, client, h = env
db.add_account_entry("joe@x", 1000.0, "взнос", "boss@x", ts=0)
with db._conn() as c:
c.execute("INSERT INTO llm_usage (ts, username, tab_id, path, provider, model, "
"input_tokens, cache_tokens, output_tokens, cost_usd, cost_rub, "
"price_rub) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
(1, "joe@x", "t", "agent", "deepseek", "m", 1, 0, 1, 0, 0, None))
d = client.get("/api/admin/v2/dashboard", headers=h).json()
assert d["attention"]["unpriced"] == 1
assert "latency_qa_p95_ms" in d["work_24h"]
assert "latency_agent_p95_ms" in d["work_24h"]