147 lines
6.4 KiB
Python
147 lines
6.4 KiB
Python
"""P3.2: экран денег — период, карточки, SVG, пустое состояние."""
|
|
import http.server
|
|
import json
|
|
import socketserver
|
|
import sys
|
|
import threading
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
sys.path.insert(0, str(ROOT)); sys.path.insert(0, str(ROOT / "tests"))
|
|
pytest.importorskip("playwright.sync_api", reason="playwright не установлен")
|
|
from test_admin_design_ui import browser # noqa: E402,F401
|
|
|
|
MONEY = {"period_days": 30, "revenue_rub": 1000, "refunded_rub": 0, "cost_rub": 250,
|
|
"flow_rub": 750, "charged_rub": 800, "accounts_total_rub": 2000,
|
|
"accounts_count": 2, "unpriced": 0, "topups_rub": 0}
|
|
MONTHS = [{"month": "2026-09", "revenue_rub": 500, "cost_rub": 100},
|
|
{"month": "2026-10", "revenue_rub": 500, "cost_rub": 150}]
|
|
PAYMENTS = [
|
|
{"id": 1, "ts": 1793000000, "username": "anna@x", "product": "tariff1",
|
|
"amount_rub": "100.50", "yk_payment_id": "yk1", "status": "succeeded"},
|
|
{"id": 2, "ts": 1793000001, "username": "bob@x", "product": "tariff2",
|
|
"amount_rub": "200.00", "yk_payment_id": "yk2", "status": "pending"},
|
|
]
|
|
|
|
|
|
class Handler(http.server.SimpleHTTPRequestHandler):
|
|
calls = []
|
|
|
|
def __init__(self, *a, **kw):
|
|
super().__init__(*a, directory=str(ROOT), **kw)
|
|
|
|
def do_GET(self):
|
|
from urllib.parse import urlparse, parse_qs
|
|
u = urlparse(self.path)
|
|
if u.path == "/api/admin/v2/money":
|
|
Handler.calls.append(u.query)
|
|
return self._json({**MONEY, "period_days": int(parse_qs(u.query).get("days", ["30"])[0])})
|
|
if u.path == "/api/admin/v2/accounts":
|
|
return self._json({"items": [
|
|
{"email": "anna@x", "balance_rub": 100.0, "deposited_rub": 200.0,
|
|
"charged_rub": 100.0, "status": "ok"},
|
|
{"email": "bob@x", "balance_rub": 0.0, "deposited_rub": 100.0,
|
|
"charged_rub": 100.0, "status": "exhausted"}],
|
|
"total": 2, "total_kop": 10000, "total_rub": 100.0})
|
|
if u.path == "/api/admin/v2/accounts.csv":
|
|
body = "email;balance_rub\nanna@x;100.00\n".encode()
|
|
self.send_response(200); self.send_header("Content-Type", "text/csv")
|
|
self.send_header("Content-Length", str(len(body))); self.end_headers()
|
|
self.wfile.write(body); return
|
|
if u.path == "/api/admin/v2/payments":
|
|
q = parse_qs(u.query)
|
|
items = PAYMENTS
|
|
if q.get("q"):
|
|
items = [r for r in items if q["q"][0] in r["username"] or q["q"][0] in r["yk_payment_id"]]
|
|
if q.get("status"):
|
|
items = [r for r in items if r["status"] == q["status"][0]]
|
|
return self._json({"items": items, "total": len(items), "page": 1, "per_page": 50})
|
|
if u.path == "/api/admin/v2/finance":
|
|
return self._json({"months": MONTHS, "days": int(parse_qs(u.query).get("days", ["30"])[0])})
|
|
if self.path == "/admin/v2" or self.path.startswith("/admin/v2/"):
|
|
data = (ROOT / "static/admin2/index.html").read_bytes()
|
|
self.send_response(200); self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
self.send_header("Content-Length", str(len(data))); self.end_headers()
|
|
self.wfile.write(data); return
|
|
return super().do_GET()
|
|
|
|
def _json(self, obj):
|
|
data = json.dumps(obj).encode()
|
|
self.send_response(200); self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(data))); self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
def log_message(self, *a):
|
|
return
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def site():
|
|
Handler.calls = []
|
|
class Quiet(socketserver.ThreadingTCPServer):
|
|
allow_reuse_address = True
|
|
daemon_threads = True
|
|
srv = Quiet(("127.0.0.1", 0), Handler)
|
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
|
yield f"http://127.0.0.1:{srv.server_address[1]}"
|
|
srv.shutdown()
|
|
|
|
|
|
def test_money_cards_charts_and_period(browser, site):
|
|
Handler.calls = []
|
|
page = browser.new_page()
|
|
errors = []
|
|
page.on("pageerror", lambda e: errors.append(str(e)))
|
|
page.add_init_script("localStorage.setItem('token','t')")
|
|
page.goto(site + "/admin/v2/money")
|
|
page.wait_for_selector(".grid .card")
|
|
assert page.locator(".grid .card").count() == 4
|
|
assert page.locator(".chart").count() == 2
|
|
assert "1\u00a0000" in page.locator(".grid").inner_text()
|
|
page.locator(".toolbar button", has_text="90 дней").click()
|
|
page.wait_for_timeout(500)
|
|
assert any("days=90" in c for c in Handler.calls)
|
|
assert errors == []
|
|
page.close()
|
|
|
|
|
|
def test_money_empty_months(browser, site):
|
|
# страница с пустым рядом месяцев не должна падать и не рисовать пустые SVG
|
|
page = browser.new_page()
|
|
page.add_init_script("localStorage.setItem('token','t')")
|
|
page.route("**/api/admin/v2/finance*",
|
|
lambda route: route.fulfill(status=200, body=json.dumps({"months": []}),
|
|
headers={"Content-Type": "application/json"}))
|
|
page.goto(site + "/admin/v2/money")
|
|
page.wait_for_selector(".note")
|
|
assert page.locator(".chart").count() == 0
|
|
page.close()
|
|
|
|
|
|
def test_payments_table_and_filter(browser, site):
|
|
page = browser.new_page()
|
|
page.add_init_script("localStorage.setItem('token','t')")
|
|
page.goto(site + "/admin/v2/money")
|
|
page.wait_for_selector(".payments table tbody tr")
|
|
assert page.locator(".payments table tbody tr").count() == 2
|
|
assert "yk1" in page.locator(".payments table").inner_text()
|
|
page.fill(".payments input[type=search]", "bob")
|
|
page.wait_for_function("document.querySelectorAll('.payments table tbody tr').length === 1")
|
|
assert page.locator(".payments table tbody tr").count() == 1
|
|
assert "bob@x" in page.locator(".payments table").inner_text()
|
|
page.close()
|
|
|
|
|
|
def test_accounts_table_and_csv(browser, site):
|
|
page = browser.new_page()
|
|
page.add_init_script("localStorage.setItem('token','t')")
|
|
page.goto(site + "/admin/v2/money")
|
|
page.wait_for_selector(".accounts table")
|
|
assert "anna@x" in page.locator(".accounts table").inner_text()
|
|
with page.expect_download() as dl:
|
|
page.locator("button", has_text="CSV").click()
|
|
assert dl.value.suggested_filename == "accounts.csv"
|
|
page.close()
|