From 841523bc0098ac311d85ea6e4f3a5231cd2eb333 Mon Sep 17 00:00:00 2001 From: anor Date: Wed, 28 Oct 2026 14:50:36 +1000 Subject: [PATCH] =?UTF-8?q?test(=D0=BF=D0=BE=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5):=20=D0=BA=D1=80=D0=B0=D1=81=D0=BD=D1=8B?= =?UTF-8?q?=D0=B5=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20?= =?UTF-8?q?=D1=80=D1=83=D1=87=D0=B5=D0=BA,=20=D1=81=D1=82=D1=80=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D1=86=D1=8B=20=D1=80=D0=B5=D0=B7=D1=83=D0=BB=D1=8C?= =?UTF-8?q?=D1=82=D0=B0=D1=82=D0=B0,=20=D1=84=D0=B8=D0=BD=D0=B0=D0=BD?= =?UTF-8?q?=D1=81=D0=BE=D0=B2=20=D0=B8=20=D0=B4=D0=BE=D0=BF=D1=83=D1=81?= =?UTF-8?q?=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- tests/test_topup_api.py | 369 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 369 insertions(+) create mode 100644 tests/test_topup_api.py diff --git a/tests/test_topup_api.py b/tests/test_topup_api.py new file mode 100644 index 0000000..b2bd765 --- /dev/null +++ b/tests/test_topup_api.py @@ -0,0 +1,369 @@ +"""Пополнение счёта онлайн — ручки и страница результата (план, шаг 4). + +Сквозь настоящий переходник pay_robokassa в тестовом режиме (OpStateExt там не работает — +зачисление по подписанному уведомлению) и настоящую SQLite. Подделка только на рубеже +платёжки: httpx.get для OpStateExt, ответ — структура из документации. Каждая проверка +статуса — ровно один код. Red-green: написано ДО кода. +""" + +import calendar +import hashlib +import importlib +import json +import os +import sys +import time + +import pytest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) + +USER = "buyer@x.ru" +OTHER = "other@x.ru" +ADMIN = "adm@x.ru" +OWNER = "boss@x.ru" +P2 = "test-pass-two" +ROBO = ("185.59.216.65", 4444) +NOON = calendar.timegm((2026, 10, 27, 3, 0, 0, 0, 0, 0)) +KITCHEN = ("robokassa", "комисси", "pass", "signature", "provider", "fee") + + +@pytest.fixture() +def 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.setenv("AGENT_OWNER_EMAILS", OWNER) + monkeypatch.setenv("TOPUP_ENABLED", "1") + monkeypatch.setenv("PAYMENT_PROVIDER", "robokassa") + monkeypatch.setenv("ROBOKASSA_LOGIN", "shop") + monkeypatch.setenv("ROBOKASSA_PASS1", "test-pass-one") + monkeypatch.setenv("ROBOKASSA_PASS2", P2) + monkeypatch.setenv("ROBOKASSA_TEST", "1") + monkeypatch.setenv("ROBOKASSA_HASH", "sha256") + for k in ("ALERT_TG_BOT_TOKEN", "ALERT_TG_CHAT_ID", "TOPUP_ORDER_OFFSET", + "CHAT_DAILY_RUB", "CHAT_DAILY_TOKENS", "AGENT_PROVIDER"): + monkeypatch.delenv(k, raising=False) + monkeypatch.chdir(ROOT) + import auth + import billing + import claude_bridge + import db + import main + import pricing + import quotas + for m in (pricing, db, billing, quotas, auth, claude_bridge, main): + importlib.reload(m) + import balance + import pay_robokassa + import topup + for m in (balance, pay_robokassa, topup): + importlib.reload(m) + db.init_db() + for u, role in ((USER, "user"), (OTHER, "user"), (ADMIN, "admin"), (OWNER, "user"), + ("svc@local", "user"), ("new@x.ru", "user")): + db.create_user(u, "h", role=role) + if u != "new@x.ru": + db.admin_verify_user(u) + from fastapi.testclient import TestClient + return db, auth, main, TestClient(main.app), TestClient(main.app, client=ROBO) + + +def _h(auth, user=USER, role="user"): + return {"Authorization": "Bearer " + auth._make_token(user, role)} + + +def _create(client, auth, user=USER, amount="1000"): + return client.post("/api/topups", headers=_h(auth, user), json={"amount": amount}) + + +def _notify_body(inv, out_sum="1000.00", password=P2): + sig = hashlib.sha256(f"{out_sum}:{inv}:{password}".encode()).hexdigest() + return {"OutSum": out_sum, "InvId": str(inv), "Fee": "0.00", "EMail": USER, + "PaymentMethod": "BankCard", "IncCurrLabel": "BankCardPSR", "SignatureValue": sig} + + +def _paid(env_, amount="1000"): + db, auth, main, client, robo = env_ + tid = _create(client, auth, amount=amount).json()["topup_id"] + inv = db.get_topup(tid)["provider_id"] + r = robo.post("/api/topups/notify", data=_notify_body(inv, f"{float(amount):.2f}")) + assert r.status_code == 200 and r.text == f"OK{inv}" + return tid, inv + + +# --- создание ------------------------------------------------------------------------------ + +def test_create_requires_login(env): + db, auth, main, client, robo = env + assert client.post("/api/topups", json={"amount": "1000"}).status_code == 401 + + +@pytest.mark.parametrize("who,code", [(OWNER, 400), ("svc@local", 400), ("new@x.ru", 403)]) +def test_create_refusals(env, who, code): + """Владелец/@local — 400, неподтверждённый — 403. Порча: не звать refuse_reason.""" + db, auth, main, client, robo = env + assert _create(client, auth, who).status_code == code + + +def test_create_blocked_is_401(env): + """Заблокированного не пускает уже вход (_get_user) — 401, до проверок пополнения.""" + db, auth, main, client, robo = env + db.block_user(USER, True) + assert _create(client, auth).status_code == 401 + + +def test_create_manual_read_only_402_mail(env): + db, auth, main, client, robo = env + db.set_read_only(USER, True) + r = _create(client, auth) + assert r.status_code == 402 and "info@infosmeta.ru" in r.json()["detail"] + + +def test_create_flag_off_503(env, monkeypatch): + """Флаг выключен — 503 «Пополнение временно недоступно». Порча: не проверять флаг.""" + db, auth, main, client, robo = env + monkeypatch.setenv("TOPUP_ENABLED", "0") + r = _create(client, auth) + assert r.status_code == 503 and r.json()["detail"] == "Пополнение временно недоступно" + + +def test_create_bad_amount_400_and_fourth_409(env): + db, auth, main, client, robo = env + r = _create(client, auth, amount="299,99") + assert r.status_code == 400 and "300" in r.json()["detail"] + for _ in range(3): + assert _create(client, auth).status_code == 200 + assert _create(client, auth).status_code == 409 + + +def test_create_success_and_audit(env): + """Успех — topup_id и адрес Robokassa; в журнале topup_create с IP. Порча: не писать + журнал.""" + db, auth, main, client, robo = env + r = _create(client, auth) + assert r.status_code == 200 + d = r.json() + assert set(d) == {"topup_id", "pay_url"} + assert d["pay_url"].startswith("https://auth.robokassa.ru/Merchant/Index.aspx?") + with db._conn() as c: + rows = c.execute("SELECT detail, ip FROM audit_log WHERE action='topup_create'").fetchall() + assert len(rows) == 1 and rows[0]["ip"] and "1 000" in rows[0]["detail"] + + +# --- уведомление --------------------------------------------------------------------------- + +def test_notify_forged_and_foreign_ip_change_nothing(env): + """С чужого IP и с битой подписью — 200 пусто, ничего не изменилось. + Порча: зачислять без проверки подписи.""" + db, auth, main, client, robo = env + tid = _create(client, auth).json()["topup_id"] + inv = db.get_topup(tid)["provider_id"] + r = client.post("/api/topups/notify", data=_notify_body(inv)) + assert r.status_code == 200 and r.text == "" + r = robo.post("/api/topups/notify", data=_notify_body(inv, password="wrong")) + assert r.status_code == 200 and r.text == "" + assert db.get_topup(tid)["status"] == "pending" + assert db.account_entries(USER) == [] + + +def test_notify_genuine_credits_once(env): + """Подлинное — зачислено, ответ OK текстом; повтор — без второй записи. + Порча: ответить JSON.""" + db, auth, main, client, robo = env + tid, inv = _paid(env) + r = robo.post("/api/topups/notify", data=_notify_body(inv)) + assert r.status_code == 200 and r.text == f"OK{inv}" + assert r.headers["content-type"].startswith("text/plain") + assert db.get_topup(tid)["status"] == "succeeded" + assert [e["amount_rub"] for e in db.account_entries(USER)] == [1000.0] + + +def test_notify_unknown_and_internal_error_200(env, monkeypatch): + """Неизвестный номер — 200 пусто; исключение внутри — 200 и запись в журнал. + Порча: пустить исключение наружу (500).""" + db, auth, main, client, robo = env + r = robo.post("/api/topups/notify", data=_notify_body(999999)) + assert r.status_code == 200 and r.text == "" + tid = _create(client, auth).json()["topup_id"] + inv = db.get_topup(tid)["provider_id"] + import topup + def boom(*a, **k): + raise RuntimeError("база легла") + monkeypatch.setattr(topup, "provider", boom) + r = robo.post("/api/topups/notify", data=_notify_body(inv)) + assert r.status_code == 200 + + +# --- состояние своего платежа -------------------------------------------------------------- + +def test_status_own_foreign_missing(env): + """Свой — состояние и остаток; чужой и несуществующий — одинаковый 404; без входа 401. + Порча: не сверять владельца.""" + db, auth, main, client, robo = env + tid, _ = _paid(env) + r = client.get(f"/api/topups/{tid}", headers=_h(auth)) + assert r.status_code == 200 + assert r.json() == {"status": "succeeded", "amount_rub": 1000.0, "balance_rub": 1000.0} + a = client.get(f"/api/topups/{tid}", headers=_h(auth, OTHER)) + b = client.get("/api/topups/987654", headers=_h(auth, OTHER)) + assert a.status_code == 404 and b.status_code == 404 and a.json() == b.json() + assert client.get(f"/api/topups/{tid}").status_code == 401 + + +# --- возврат кнопкой ----------------------------------------------------------------------- + +def test_admin_refund_only_admin(env): + db, auth, main, client, robo = env + tid, _ = _paid(env) + r = client.post(f"/api/admin/topups/{tid}/refund", headers=_h(auth), json={"amount": "300"}) + assert r.status_code == 403 + + +def test_admin_refund_partial_full_over(env): + """Частичный — запись −300 и refunded_kop; сверх остатка платежа — 400 с текстом; полный + — refunded; журнал topup_refund. Порча: не проверять остаток платежа.""" + db, auth, main, client, robo = env + tid, _ = _paid(env) + ah = _h(auth, ADMIN, "admin") + r = client.post(f"/api/admin/topups/{tid}/refund", headers=ah, json={"amount": "300"}) + assert r.status_code == 200 + assert db.get_topup(tid)["refunded_kop"] == 30_000 + r = client.post(f"/api/admin/topups/{tid}/refund", headers=ah, json={"amount": "700,01"}) + assert r.status_code == 400 and "700" in r.json()["detail"] + r = client.post(f"/api/admin/topups/{tid}/refund", headers=ah, json={"amount": "700"}) + assert r.status_code == 200 + assert db.get_topup(tid)["status"] == "refunded" + assert [e["amount_rub"] for e in db.account_entries(USER)] == [-700.0, -300.0, 1000.0] + with db._conn() as c: + assert c.execute("SELECT COUNT(*) FROM audit_log WHERE action='topup_refund'").fetchone()[0] == 2 + + +def test_admin_storno_of_topup_refused(env): + """Кнопка «Сторно» на записи онлайн-пополнения — 400 с текстом про кабинет платёжки.""" + db, auth, main, client, robo = env + _paid(env) + eid = db.account_entries(USER)[0]["id"] + r = client.post("/api/admin/users/deposit", headers=_h(auth, ADMIN, "admin"), + json={"email": USER, "amount": -1000, "reverses": eid}) + assert r.status_code == 400 and "кабинета платёжки" in r.json()["detail"] + + +# --- что видит человек --------------------------------------------------------------------- + +def test_limits_topup_block_only_with_flag_and_no_kitchen(env, monkeypatch): + """В /api/limits блок topup — при флаге и допуске; кухни нет. Порча: блок без флага.""" + db, auth, main, client, robo = env + lim = client.get("/api/limits", headers=_h(auth)).json() + assert lim["topup"] == {"enabled": True, "presets": [500, 1000, 3000, 5000], + "min": 300, "max": 20000} + text = json.dumps(lim, ensure_ascii=False).lower() + for word in KITCHEN: + assert word not in text, word + assert "topup" not in client.get("/api/limits", headers=_h(auth, OWNER)).json() + monkeypatch.setenv("TOPUP_ENABLED", "0") + assert "topup" not in client.get("/api/limits", headers=_h(auth)).json() + + +def _spend(db, rub, user=USER): + db.record_llm_usage(user, "t", "agent", "glm", "m", 100, 0, 100, None, cost_rub=rub / 4, + price_rub=rub, markup=4.0, ts=time.time() + 5) + + +def test_exhausted_402_offers_topup_when_enabled(env, monkeypatch): + """Счёт исчерпан: при включённом флаге текст отказа зовёт «Пополнить счёт», а не на + почту; при выключенном — прежний текст с почтой. Порча: оставить почту при флаге.""" + db, auth, main, client, robo = env + _paid(env) + _spend(db, 1500.0) + r = client.post("/api/chat", headers=_h(auth), json={"message": "вопрос", "tab_id": "t"}) + assert r.status_code == 402 + assert "Пополнить счёт" in r.json()["detail"] and "info@" not in r.json()["detail"] + monkeypatch.setenv("TOPUP_ENABLED", "0") + r = client.post("/api/chat", headers=_h(auth), json={"message": "вопрос", "tab_id": "t"}) + assert r.status_code == 402 and "info@infosmeta.ru" in r.json()["detail"] + + +# --- админка, финансы ---------------------------------------------------------------------- + +def test_admin_payments_union_only_admin(env): + """«Платежи» — только админу; в списке и старая строка payments, и новая topups. + Порча: отдавать только одну таблицу.""" + db, auth, main, client, robo = env + db.insert_payment(OTHER, "agent-month", "990.00", "yk_1", "idem", None) + tid, inv = _paid(env) + assert client.get("/api/admin/payments", headers=_h(auth)).status_code == 403 + r = client.get("/api/admin/payments", headers=_h(auth, ADMIN, "admin")) + assert r.status_code == 200 + rows = r.json()["payments"] + kinds = {(x["kind"], x["username"]) for x in rows} + assert ("topup", USER) in kinds and ("yookassa", OTHER) in kinds + t = next(x for x in rows if x["kind"] == "topup") + assert (t["id"], t["amount_rub"], t["status"], t["provider_id"]) == (tid, 1000.0, "succeeded", inv) + assert t["refunded_rub"] == 0 and t["refundable_rub"] == 1000.0 + + +def test_finance_sums_both_sources_refund_once(env): + """Финансы: поступления — успешные пополнения минус возвращённое плюс старые платежи; + возврат показан отдельно и не вычтен дважды. Порча: читать только payments.""" + db, auth, main, client, robo = env + db.insert_payment(OTHER, "agent-month", "990.00", "yk_1", "idem", None) + db.finalize_payment_status("yk_1", "succeeded") + tid, _ = _paid(env) + db.refund_topup(tid, 30_000, "admin") + fin = db.finance_by_month(time.time() - 86400)["months"] + assert len(fin) == 1 + assert fin[0]["revenue_rub"] == pytest.approx(990.0 + 700.0) + assert fin[0]["refunded_rub"] == pytest.approx(300.0) + assert fin[0]["payers"] == 2 + + +def test_billing_settings_topup_limits(env): + """Пределы и пресеты правятся в настройках учёта; мусор — 400. Порча: не проверять.""" + db, auth, main, client, robo = env + ah = _h(auth, ADMIN, "admin") + r = client.post("/api/admin/billing-settings", headers=ah, + json={"topup_min_rub": "100", "topup_max_rub": "30000", + "topup_presets": "200, 1000"}) + assert r.status_code == 200 + g = client.get("/api/admin/billing-settings", headers=ah).json() + assert g["topup"] == {"presets": [200, 1000], "min": 100, "max": 30000} + r = client.post("/api/admin/billing-settings", headers=ah, json={"topup_min_rub": "много"}) + assert r.status_code == 400 + r = client.post("/api/admin/billing-settings", headers=ah, json={"topup_presets": "50"}) + assert r.status_code == 400 + + +# --- допуск к агенту ----------------------------------------------------------------------- + +def test_agent_allowed_by_positive_account(env): + """Счёт в плюсе — третье основание допуска к агенту, и при стопе по бюджету такой + человек щадится; исчерпанный — нет. Порча: не смотреть на счёт.""" + db, auth, main, client, robo = env + import agent_provider + db.set_user_agent_access(USER, False) + assert not agent_provider.agent_allowed(USER) + _paid(env) + assert agent_provider.agent_allowed(USER) + db.set_killswitch("on", "budget") + assert agent_provider.agent_allowed(USER) + db.set_killswitch("off") + _spend(db, 1500.0) + assert not agent_provider.agent_allowed(USER) + + +# --- страница результата ------------------------------------------------------------------- + +def test_payment_result_page_has_all_states(env): + db, auth, main, client, robo = env + r = client.get("/payment/result?t=5") + assert r.status_code == 200 + for text in ("Зачислено", "На счёте", "Банк ещё подтверждает платёж", + "Оплата не прошла, деньги не списаны", "Не удалось проверить платёж", + "/api/topups/", "last_topup_id"): + assert text in r.text, text + for word in ("robokassa", "webhook"): + assert word not in r.text.lower()