"""Minimal HTTP helpers for student tests (stdlib only).""" from __future__ import annotations import base64 import json import os import urllib.error import urllib.request import uuid BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") def call(method, path, expected=None, body=None, token=None, headers=None, raw=None): h = {"Accept": "application/json"} if token: h["Authorization"] = "Bearer " + token if body is not None: raw = json.dumps(body, ensure_ascii=False).encode("utf-8") h["Content-Type"] = "application/json" # Lab3+: POST messages require Idempotency-Key unless caller supplies headers. if ( method == "POST" and path.rstrip("/").endswith("/messages") and (headers is None or "Idempotency-Key" not in headers) ): h["Idempotency-Key"] = uuid.uuid4().hex h.update(headers or {}) req = urllib.request.Request(BASE_URL + path, data=raw, headers=h, method=method) try: resp = urllib.request.urlopen(req, timeout=60) except urllib.error.HTTPError as err: resp = err data = resp.read() status = resp.code if expected is not None: assert status == expected, ( f"{method} {path}: expected {expected}, got {status}: {data[:200]!r}" ) payload = None ctype = resp.headers.get_content_type() if ctype == "application/json" and data: payload = json.loads(data.decode("utf-8")) assert resp.headers.get("X-Request-Id"), "missing X-Request-Id" assert resp.headers.get("X-Instance-Id"), "missing X-Instance-Id" return {"status": status, "headers": resp.headers, "json": payload, "bytes": data} def upload(token, chat_id, data, filename="photo.png", content_type="image/png", expected=None, headers=None): from urllib.parse import quote h = {} if content_type is None else {"Content-Type": content_type} h.update(headers or {}) query = "" if filename is None else "?filename=" + quote(filename, safe="") resp = call("POST", f"/api/v1/chats/{chat_id}/attachments{query}", expected, token=token, raw=data, headers=h) if expected is None or expected < 500: assert resp["status"] < 500, f"user error became {resp['status']}: {resp['json']}" return resp def chat_for(*actors, title="attachments"): return call( "POST", "/api/v1/chats", 201, token=actors[0]["token"], body={"title": title, "member_ids": [a["id"] for a in actors]}, )["json"] def register(label: str): username = f"st_{label}_{uuid.uuid4().hex[:10]}" password = "T3st-" + uuid.uuid4().hex body = { "username": username, "display_name": f"Student {label}", "password": password, } user = call("POST", "/api/v1/users", 201, body=body)["json"] credential = base64.b64encode(f"{username}:{password}".encode()).decode() session = call( "POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + credential}, )["json"] return { "id": user["id"], "user": user, "token": session["token"], "registration": body, }