"""Minimal standard-library HTTP client for the student's own tests. Run with the API already up: python -m unittest discover -s student-tests -p "test_*.py" -v BASE_URL selects the stand (default http://127.0.0.1:8080). No third-party dependency is needed, so `make test-student` works on a clean clone. """ from __future__ import annotations import base64 import json import os import urllib.error import urllib.parse import urllib.request import uuid import json from pathlib import Path ROOT = Path(__file__).resolve().parents[1] LAB = json.loads((ROOT / "lab.json").read_text(encoding="utf-8"))["number"] # 127.0.0.1 rather than "localhost": on a dual-stack host "localhost" resolves # to ::1 first, a published Docker port may answer on IPv4 only, and every IPv6 # attempt then costs ~2 s of SYN retry before urllib falls back to IPv4. The IPv4 # literal keeps the client fast and never reaches the application. BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") TIMEOUT = float(os.environ.get("STUDENT_TEST_TIMEOUT", "20")) class NoRedirect(urllib.request.HTTPRedirectHandler): """The contract never requires redirects; fail loudly instead of following.""" def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001 return None # The lab stand is always loopback; urllib ignores the Windows proxy bypass # list, so a corporate/system proxy would otherwise be used for localhost too. _OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) class Response: def __init__(self, status: int, headers: dict[str, str], data: bytes) -> None: self.status = status self.headers = headers self.data = data try: self.json = json.loads(data.decode("utf-8")) if data else None except (ValueError, UnicodeDecodeError): self.json = None def header(self, name: str) -> str: for key, value in self.headers.items(): if key.lower() == name.lower(): return value return "" def __repr__(self) -> str: # pragma: no cover - diagnostics only return "Response(status=%s, json=%r)" % (self.status, self.json) def request( method: str, path: str, *, body=None, raw: bytes | None = None, token: str | None = None, headers: dict[str, str] | None = None, content_type: str | None = None, timeout: float | None = None, base_url: str | None = None, ) -> Response: url = (base_url or BASE_URL) + path data = raw request_headers = {"Accept": "application/json"} if body is not None: data = json.dumps(body, ensure_ascii=False).encode("utf-8") request_headers["Content-Type"] = "application/json" if content_type is not None: request_headers["Content-Type"] = content_type if token is not None: request_headers["Authorization"] = "Bearer " + token request_headers.update(headers or {}) prepared = urllib.request.Request(url, data=data, headers=request_headers, method=method) try: response = _OPENER.open(prepared, timeout=timeout or TIMEOUT) except urllib.error.HTTPError as error: response = error with response: payload = response.read() return Response(response.code, dict(response.headers.items()), payload) def basic(username: str, password: str) -> dict[str, str]: encoded = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii") return {"Authorization": "Basic " + encoded} def new_registration(prefix: str = "st", password: str | None = None) -> dict[str, str]: suffix = uuid.uuid4().hex[:12] return { "username": prefix + "_" + suffix, "display_name": "Тест " + suffix, "password": password or ("St-" + uuid.uuid4().hex), } def register(registration: dict[str, str] | None = None) -> Response: return request("POST", "/api/v1/users", body=registration or new_registration()) def login(username: str, password: str) -> Response: return request("POST", "/api/v1/auth/sessions", headers=basic(username, password)) class Actor: """A registered user with a live session, as a client would hold it.""" def __init__(self, registration: dict[str, str]) -> None: self.registration = registration response = register(registration) if response.status != 201: raise AssertionError( "registration failed: %s %r" % (response.status, response.json) ) self.user = response.json self.username = registration["username"] self.password = registration["password"] @property def id(self) -> str: return self.user["id"] def sign_in(self) -> "Actor": response = login(self.username, self.password) if response.status != 201: raise AssertionError("login failed: %s %r" % (response.status, response.json)) self.session = response.json self.token = response.json["token"] return self def actor(prefix: str = "st", password: str | None = None) -> Actor: return Actor(new_registration(prefix, password)).sign_in() def create_chat(token: str, member_ids: list[str], title: str = "Тестовый чат") -> dict: response = request( "POST", "/api/v1/chats", body={"title": title, "member_ids": member_ids}, token=token, ) if response.status != 201: raise AssertionError("chat creation failed: %s %r" % (response.status, response.json)) return response.json def send(token: str, chat_id: str, text: str) -> dict: headers = {} if LAB >= 3: headers["Idempotency-Key"] = uuid.uuid4().hex response = request( "POST", "/api/v1/chats/" + chat_id + "/messages", body={"text": text}, token=token, headers=headers ) if response.status != 201: raise AssertionError("message failed: %s %r" % (response.status, response.json)) return response.json def history(token: str, chat_id: str, limit: int = 100) -> list[dict]: """Walk every page of a chat, guarding against cursor loops.""" items: list[dict] = [] seen: set[str] = set() cursor: str | None = None while True: path = "/api/v1/chats/" + chat_id + "/messages?limit=" + str(limit) if cursor is not None: path += "&cursor=" + urllib.parse.quote(cursor, safe="") response = request("GET", path, token=token) if response.status != 200: raise AssertionError("history failed: %s %r" % (response.status, response.json)) items.extend(response.json["items"]) cursor = response.json["next_cursor"] if cursor is None: return items if cursor in seen: raise AssertionError("cursor loop detected") seen.add(cursor) def expect_error(test, response: Response, status: int, code: str) -> dict: """Assert the public error envelope, request id echo and the status.""" test.assertEqual(response.status, status, response.json) test.assertIsInstance(response.json, dict) error = response.json.get("error") test.assertIsNotNone(error, "missing error envelope") test.assertEqual(error["code"], code) test.assertTrue(error["message"]) request_id = response.header("X-Request-Id") test.assertTrue(request_id, "missing X-Request-Id header") test.assertEqual(error["request_id"], request_id) return error