forked from mtusi2026/mtusi2026lab3
34 lines
1.7 KiB
Python
34 lines
1.7 KiB
Python
import base64
|
|
import json
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
|
|
|
|
def call(base, method, path, body=None, headers=None, timeout=3.0):
|
|
"""Возвращает (status, headers с ключами в нижнем регистре, bytes). Сетевые ошибки поднимаются наружу."""
|
|
data = json.dumps(body).encode() if body is not None else None
|
|
h = {"Content-Type": "application/json"} if data else {}
|
|
h.update(headers or {})
|
|
req = urllib.request.Request(base + path, data=data, method=method, headers=h)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
return r.status, {k.lower(): v for k, v in r.headers.items()}, r.read()
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, {k.lower(): v for k, v in e.headers.items()}, e.read()
|
|
|
|
|
|
def setup(base):
|
|
"""Синтетический пользователь, сессия и чат из одного участника. Возвращает (auth_headers, chat_id)."""
|
|
name = "load_" + uuid.uuid4().hex[:12]
|
|
password = "load-password-" + uuid.uuid4().hex[:8]
|
|
s, _, b = call(base, "POST", "/api/v1/users", {"username": name, "display_name": "Load", "password": password})
|
|
assert s == 201, f"register failed: {s}"
|
|
uid = json.loads(b)["id"]
|
|
cred = base64.b64encode(f"{name}:{password}".encode()).decode()
|
|
s, _, b = call(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
|
|
assert s == 201, f"login failed: {s}"
|
|
auth = {"Authorization": "Bearer " + json.loads(b)["token"]}
|
|
s, _, b = call(base, "POST", "/api/v1/chats", {"title": "load", "member_ids": [uid]}, auth)
|
|
assert s == 201, f"chat failed: {s}"
|
|
return auth, json.loads(b)["id"] |