"""Общие HTTP-помощники собственных тестов (только стандартная библиотека).""" import base64 import json import os import uuid from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") class Resp: def __init__(self, status, data, headers, elapsed=0.0): self.status = status self.json = data self.headers = headers self.elapsed = elapsed def request(method, path, token=None, payload=None, raw=None, headers=None, base_url=None, timeout=10): import time h = {"Accept": "application/json"} if token is not None: h["Authorization"] = "Bearer " + token body = None if payload is not None: body = json.dumps(payload, ensure_ascii=False).encode("utf-8") h["Content-Type"] = "application/json" elif raw is not None: body = raw h["Content-Type"] = "application/json" h.update(headers or {}) # Переход 2 -> 3: POST сообщения требует Idempotency-Key. Старые тесты lab2 # его не передают — добавляем уникальный ключ, если тест не задал свой. # Явное значение None в headers означает «не отправлять заголовок вовсе». if method == "POST" and path.split("?")[0].endswith("/messages") \ and not any(k.lower() == "idempotency-key" for k in h): h["Idempotency-Key"] = uuid.uuid4().hex h = {k: v for k, v in h.items() if v is not None} req = Request((base_url or BASE_URL) + path, data=body, headers=h, method=method) started = time.monotonic() try: response = urlopen(req, timeout=timeout) except HTTPError as error: response = error with response: content = response.read() status = response.status if hasattr(response, "status") else response.code rh = response.headers try: data = json.loads(content.decode("utf-8")) if content else None except (UnicodeDecodeError, json.JSONDecodeError): data = None return Resp(status, data, rh, time.monotonic() - started) def basic(username, password): raw = (username + ":" + password).encode("utf-8") return "Basic " + base64.b64encode(raw).decode("ascii") def new_password(): return "Pw-" + uuid.uuid4().hex def register(prefix="t", password=None, base_url=None): username = (prefix + "_" + uuid.uuid4().hex[:16])[:32] password = password or new_password() r = request("POST", "/api/v1/users", base_url=base_url, payload={ "username": username, "display_name": "Test " + prefix, "password": password, }) assert r.status == 201, (r.status, r.json) user = r.json user["_password"] = password return user def login(user, base_url=None): r = request("POST", "/api/v1/auth/sessions", base_url=base_url, headers={"Authorization": basic(user["username"], user["_password"])}) assert r.status == 201, (r.status, r.json) return r.json["token"] def actor(prefix="t", base_url=None): user = register(prefix, base_url=base_url) user["_token"] = login(user, base_url=base_url) return user def create_chat(owner, *members, base_url=None): r = request("POST", "/api/v1/chats", token=owner["_token"], base_url=base_url, payload={ "title": "Test chat " + uuid.uuid4().hex[:8], "member_ids": [owner["id"]] + [m["id"] for m in members], }) assert r.status == 201, (r.status, r.json) return r.json def reachable(base_url): try: urlopen(base_url.rstrip("/") + "/health/live", timeout=2).read() return True except (URLError, OSError, HTTPError): return False def wait_ready(token, attachment_id, timeout=60.0, allow_failed=False): """lab5: опрашивать метаданные до конечного состояния (ready/failed).""" import time deadline = time.monotonic() + timeout last = None while time.monotonic() < deadline: r = request("GET", "/api/v1/attachments/" + attachment_id, token=token) last = r if r.status == 200 and r.json["status"] == "ready": return r.json if r.status == 200 and r.json["status"] == "failed": if allow_failed: return r.json raise AssertionError("attachment failed: %s" % r.json.get("error_code")) time.sleep(0.2) raise AssertionError("attachment %s not ready in %.0fs (last: %s)" % ( attachment_id, timeout, last.json if last else None))