139 lines
6.1 KiB
Python
139 lines
6.1 KiB
Python
"""CSV клиентов/платежей/журнала: Excel-совместимость, суммы, защита от формул."""
|
|
import csv
|
|
import importlib
|
|
import io
|
|
import os
|
|
import sys
|
|
import time
|
|
from urllib.parse import quote
|
|
|
|
import pytest
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
if ROOT not in sys.path:
|
|
sys.path.insert(0, ROOT)
|
|
ADMIN_HTML = os.path.join(ROOT, "static", "admin.html")
|
|
|
|
|
|
def _read(text: str):
|
|
assert text.startswith("\ufeff"), "нет BOM — Excel сломает кириллицу"
|
|
return list(csv.reader(io.StringIO(text[1:]), delimiter=";"))
|
|
|
|
|
|
@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")
|
|
db.create_user("joe@x", auth.hash_password("Passw0rd!ok"))
|
|
db.admin_verify_user("joe@x")
|
|
db.add_account_entry("joe@x", 1000.0, "взнос", "boss@x")
|
|
db.create_user("ex@x", auth.hash_password("Passw0rd!ok"))
|
|
db.admin_verify_user("ex@x")
|
|
db.add_account_entry("ex@x", 1000.0, "взнос", "boss@x")
|
|
db.record_llm_usage("ex@x", "t1", "agent", "deepseek", "m", 1, 0, 1, 0,
|
|
cost_rub=0, price_rub=1500)
|
|
db.create_user("old@x", auth.hash_password("Passw0rd!ok"))
|
|
db.admin_verify_user("old@x")
|
|
db.soft_delete_user("old@x")
|
|
with db._conn() as conn:
|
|
conn.execute("INSERT INTO payments (ts, username, product, amount_rub, "
|
|
"yk_payment_id, status, updated_at) VALUES (?,?,?,?,?,?,?)",
|
|
(1700000000, "joe@x", "agent-month", "990.00", "yk-1", "succeeded", 1700000000))
|
|
db.log_action("joe@x", "chat", "POST", "/api/chat", "=HYPERLINK(\"x\")", "1.2.3.4", 200)
|
|
from fastapi.testclient import TestClient
|
|
client = TestClient(main.app)
|
|
h = {"Authorization": "Bearer " + auth._make_token("boss@x", "admin")}
|
|
return db, client, h, auth
|
|
|
|
|
|
def test_users_csv_has_sum_and_headers(env):
|
|
db, client, h, auth = env
|
|
r = client.get("/api/admin/export/users.csv", headers=h)
|
|
assert r.status_code == 200
|
|
assert r.headers["content-type"].startswith("text/csv")
|
|
rows = _read(r.text)
|
|
assert rows[0][:3] == ["Email", "Роль", "Статус"]
|
|
joe = next(row for row in rows[1:] if row[0] == "joe@x")
|
|
assert joe[2] == "active"
|
|
assert joe[-1] == "1000,00"
|
|
|
|
|
|
def test_users_csv_respects_search_and_status(env):
|
|
db, client, h, auth = env
|
|
rows = _read(client.get("/api/admin/export/users.csv?q=joe", headers=h).text)
|
|
assert [r[0] for r in rows[1:]] == ["joe@x"]
|
|
rows = _read(client.get("/api/admin/export/users.csv?status=blocked", headers=h).text)
|
|
assert rows[1:] == []
|
|
|
|
|
|
def test_users_csv_finds_deleted_and_marks_exhausted(env):
|
|
db, client, h, auth = env
|
|
deleted = _read(client.get("/api/admin/export/users.csv?q=old@x&deleted=1", headers=h).text)
|
|
assert any(r[0] == "old@x" and r[2] == "deleted" for r in deleted[1:])
|
|
with db._conn() as conn:
|
|
archived = conn.execute("SELECT email FROM users WHERE deleted_email='old@x'").fetchone()[0]
|
|
raw = _read(client.get("/api/admin/export/users.csv?q=" + quote(archived) + "&deleted=1",
|
|
headers=h).text)
|
|
assert any(r[0] == "old@x" for r in raw[1:]), "поиск по архивному raw_email не работает"
|
|
exhausted = _read(client.get("/api/admin/export/users.csv?status=exhausted", headers=h).text)
|
|
row = next(r for r in exhausted[1:] if r[0] == "ex@x")
|
|
assert row[-1] == "-500,00"
|
|
|
|
|
|
def test_payments_and_audit_csv(env):
|
|
db, client, h, auth = env
|
|
pay = _read(client.get("/api/admin/export/payments.csv?days=3650", headers=h).text)
|
|
assert pay[0][:3] == ["Время (UTC+10)", "Пользователь", "Тариф"]
|
|
assert any(row[2] == "agent-month" and row[3] == "990,00" for row in pay[1:])
|
|
assert pay[1][0] == time.strftime("%Y-%m-%d %H:%M", time.gmtime(1700000000 + 10 * 3600))
|
|
|
|
audit = _read(client.get("/api/admin/export/audit.csv?limit=1000", headers=h).text)
|
|
assert audit[0][:3] == ["Время (UTC+10)", "Пользователь", "Действие"]
|
|
cell = next(row for row in audit[1:] if row[2] == "chat")
|
|
assert cell[5].startswith("'="), "формула не обезврежена"
|
|
assert cell[7] == "200", "код ответа потерян"
|
|
|
|
|
|
def test_audit_limit_marks_truncation(env):
|
|
db, client, h, auth = env
|
|
db.log_action("joe@x", "login", "POST", "/api/login", "", "1.2.3.4", 200)
|
|
rows = _read(client.get("/api/admin/export/audit.csv?limit=1", headers=h).text)
|
|
assert rows[-1][0] == "выгружены не все — сузьте фильтр"
|
|
|
|
|
|
def test_users_csv_survives_accounts_failure(env, monkeypatch):
|
|
db, client, h, auth = env
|
|
monkeypatch.setattr(db, "account_balances_all",
|
|
lambda: (_ for _ in ()).throw(RuntimeError("down")))
|
|
r = client.get("/api/admin/export/users.csv", headers=h)
|
|
assert r.status_code == 200
|
|
assert "балансы не прочитаны" in r.text
|
|
assert client.get("/api/admin/export/users.csv?status=exhausted",
|
|
headers=h).status_code == 503
|
|
|
|
|
|
def test_export_is_admin_only(env):
|
|
db, client, h, auth = env
|
|
stranger = {"Authorization": "Bearer " + auth._make_token("joe@x", "user")}
|
|
for path in ("/api/admin/export/users.csv", "/api/admin/export/payments.csv",
|
|
"/api/admin/export/audit.csv"):
|
|
assert client.get(path, headers=stranger).status_code == 403
|
|
|
|
|
|
def test_ui_has_csv_buttons():
|
|
html = open(ADMIN_HTML, encoding="utf-8").read()
|
|
for path in ("/api/admin/export/users.csv", "/api/admin/export/payments.csv",
|
|
"/api/admin/export/audit.csv"):
|
|
assert path in html
|
|
assert "downloadCsv" in html and "downloadUsersCsv" in html and "downloadAuditCsv" in html
|