"""Общие помощники для собственных тестов (только стандартная библиотека).""" import base64 import json import os import subprocess import sys import time import urllib.error import urllib.request import uuid from pathlib import Path ROOT = Path(__file__).resolve().parent.parent BASE = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/") PASSWORD = "synthetic-pass-123" class Failure(Exception): pass def check(cond, msg): if not cond: raise Failure(msg) def call(method, path, body=None, headers=None, timeout=15): h = dict(headers or {}) data = None if body is not None: data = json.dumps(body).encode() h["Content-Type"] = "application/json" req = urllib.request.Request(BASE + path, data=data, method=method, headers=h) started = time.monotonic() try: with urllib.request.urlopen(req, timeout=timeout) as r: status, raw, rh = r.status, r.read(), r.headers except urllib.error.HTTPError as e: status, raw, rh = e.code, e.read(), e.headers elapsed = time.monotonic() - started payload = json.loads(raw) if raw else None return status, payload, rh, elapsed def basic(username, password): return {"Authorization": "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()} def bearer(token): return {"Authorization": "Bearer " + token} def new_user(prefix="t"): name = prefix + uuid.uuid4().hex[:12] st, body, _, _ = call("POST", "/api/v1/users", {"username": name, "display_name": "Synthetic", "password": PASSWORD}) check(st == 201, f"register expected 201, got {st}") return {"username": name, "id": body["id"]} def login(user): st, body, _, _ = call("POST", "/api/v1/auth/sessions", headers=basic(user["username"], PASSWORD)) check(st == 201, f"login expected 201, got {st}") return body def compose(*args, env=None, check_rc=True): cmd = ["docker", "compose", "--env-file", str(ROOT / ".env"), *args] full_env = dict(os.environ, **(env or {})) r = subprocess.run(cmd, cwd=ROOT, env=full_env, capture_output=True, text=True, encoding="utf-8", errors="replace") if check_rc and r.returncode != 0: raise Failure("docker compose " + " ".join(args) + " failed: " + r.stderr[-300:]) return r.stdout def wait_ready(timeout=90): deadline = time.monotonic() + timeout while time.monotonic() < deadline: try: if call("GET", "/health/ready", timeout=3)[0] == 200: return except Exception: pass time.sleep(0.5) raise Failure("API did not become ready") def run(main): try: main() except Failure as e: print("FAIL:", e) sys.exit(1)