Files
smeta-web/tests/test_alerts_costs.py
T
anorandClaude Opus 4.8 1142770c94 feat(launch-Ф3): TG-алерты (alerts.py) + дашборд «Расходы LLM» в админке
- alerts.send_tg: ALERT_TG_* (те же ключи, что канарейка), no-op без ключей,
  никогда не raise; quotas подхватывает автоматически (гейт ImportError снят)
- GET /api/admin/costs: день×юзер×путь×провайдер + agent_24h/капы; секция в админке
  (textContent для username — XSS-дисциплина)
- 4 red-green теста (tests/test_alerts_costs.py)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 23:45:19 +10:00

99 lines
3.6 KiB
Python
Raw 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.
"""Ф3 публичного запуска: TG-алерты (alerts.py) + дашборд расходов (/api/admin/costs).
Дизайн: docs/PUBLIC_LAUNCH_PLAN.md Ф3. Red-green: написано ДО реализации.
"""
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)
# --- A. alerts.send_tg ---
def test_send_tg_no_keys_noop(monkeypatch):
"""Без ALERT_TG_* — False и НОЛЬ сетевых вызовов (не пытаемся слать в пустоту).
Mutation: убрать guard на пустые ключи → упадёт (httpx дёрнется)."""
monkeypatch.delenv("ALERT_TG_BOT_TOKEN", raising=False)
monkeypatch.delenv("ALERT_TG_CHAT_ID", raising=False)
import alerts
importlib.reload(alerts)
calls = []
monkeypatch.setattr(alerts, "_post", lambda *a, **kw: calls.append(a) or 200)
assert alerts.send_tg("тест") is False
assert calls == []
def test_send_tg_with_keys_posts(monkeypatch):
"""С ключами — POST на api.telegram.org с chat_id и текстом; 200 → True."""
monkeypatch.setenv("ALERT_TG_BOT_TOKEN", "123:abc")
monkeypatch.setenv("ALERT_TG_CHAT_ID", "42")
import alerts
importlib.reload(alerts)
seen = {}
def fake_post(url, data):
seen["url"], seen["data"] = url, data
return 200
monkeypatch.setattr(alerts, "_post", fake_post)
assert alerts.send_tg("бюджет исчерпан") is True
assert "api.telegram.org" in seen["url"] and "123:abc" in seen["url"]
assert seen["data"]["chat_id"] == "42"
assert "бюджет" in seen["data"]["text"]
def test_send_tg_never_raises(monkeypatch):
"""Сеть упала → False, не исключение (алерт не роняет запрос)."""
monkeypatch.setenv("ALERT_TG_BOT_TOKEN", "123:abc")
monkeypatch.setenv("ALERT_TG_CHAT_ID", "42")
import alerts
importlib.reload(alerts)
def boom(url, data):
raise RuntimeError("net down")
monkeypatch.setattr(alerts, "_post", boom)
assert alerts.send_tg("x") is False
# --- B. /api/admin/costs ---
@pytest.fixture()
def client_env(tmp_path, monkeypatch):
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
monkeypatch.setenv("AI_BACKEND", "claude")
monkeypatch.setenv("SESSION_SECRET", "test-secret")
monkeypatch.chdir(ROOT)
import db, auth, claude_bridge, main
importlib.reload(db)
importlib.reload(auth)
importlib.reload(claude_bridge)
importlib.reload(main)
db.init_db()
db.create_user("admin@x", "h", role="admin")
from fastapi.testclient import TestClient
return db, auth, TestClient(main.app)
def test_costs_endpoint_rbac_and_data(client_env):
db, auth, client = client_env
r = client.get("/api/admin/costs",
headers={"Authorization": "Bearer " + auth._make_token("u@x", "user")})
assert r.status_code == 403
db.record_llm_usage("u@x", "t", "agent", "deepseek", "deepseek-v4-flash", 100, 0, 10, 0.5)
db.record_llm_usage("u@x", "t", "agent", "deepseek", "deepseek-v4-flash", 100, 0, 10, 0.25)
r = client.get("/api/admin/costs",
headers={"Authorization": "Bearer " + auth._make_token("admin@x", "admin")})
assert r.status_code == 200
body = r.json()
mine = [x for x in body["daily"] if x["username"] == "u@x"]
assert mine and mine[0]["cost_usd"] == pytest.approx(0.75) and mine[0]["requests"] == 2
assert body["totals"]["agent_24h"] == pytest.approx(0.75)