"""P3.5: счета v2 — итог, статусы, CSV сходится.""" 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 for m in (db, auth, main): importlib.reload(m) db.init_db() db.create_user("boss@x", auth.hash_password("Passw0rd!ok"), role="admin") db.admin_verify_user("boss@x") for email, price in (("ok@x", 1), ("low@x", 9.5), ("zero@x", 1500)): db.create_user(email, auth.hash_password("Passw0rd!ok")) db.admin_verify_user(email) db.add_account_entry(email, 10.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,?,'t','agent','deepseek','m',1,0,1,0,0,?)", (email, price)) from fastapi.testclient import TestClient client = TestClient(main.app) h = {"Authorization": "Bearer " + auth._make_token("boss@x", "admin")} return client, h, auth def test_accounts_total_status_and_csv(env): client, h, auth = env d = client.get("/api/admin/v2/accounts", headers=h).json() assert d["total"] == 3 assert d["total_kop"] == (900 + 50 + -149000) assert client.get("/api/admin/v2/accounts?status=zero", headers=h).json()["total"] == 0 assert client.get("/api/admin/v2/accounts?status=exhausted", headers=h).json()["total"] == 1 assert client.get("/api/admin/v2/accounts?status=low", headers=h).json()["total"] == 1 csv = client.get("/api/admin/v2/accounts.csv", headers=h) assert csv.status_code == 200 lines = [x for x in csv.text.splitlines() if x] assert len(lines) == 4 # header + 3 assert "zero@x" in csv.text and "-1490.00" in csv.text def test_accounts_admin_only(env): client, h, auth = env user = {"Authorization": "Bearer " + auth._make_token("ok@x", "user")} assert client.get("/api/admin/v2/accounts", headers=user).status_code == 403 assert client.get("/api/admin/v2/accounts.csv", headers=user).status_code == 403