Files
mtusi2026lab2/student-tests/common.py
T
Чиняева df31f4a9fb Реализовать лабораторную 2 на оценку 4
PostgreSQL как источник истины, непрозрачные сессии в Redis с TTL и AOF, миграции под advisory lock, пул и таймауты, проверки гонки/отката/отказов и отчёт с evidence.
2026-11-06 22:37:31 +03:00

77 lines
2.7 KiB
Python

#!/usr/bin/env python3
"""Small standard-library HTTP helpers for the student checks."""
from __future__ import annotations
import base64
import json
import os
import uuid
import urllib.error
import urllib.request
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
class HttpClient:
def __init__(self, base_url: str | None = None):
self.base = (base_url or BASE_URL).rstrip("/")
def call(self, method: str, path: str, body=None, token: str | None = None, headers=None):
h = {"Accept": "application/json"}
data = None
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
h["Content-Type"] = "application/json"
if token:
h["Authorization"] = "Bearer " + token
h.update(headers or {})
request = urllib.request.Request(self.base + path, data=data, headers=h, method=method)
try:
response = urllib.request.urlopen(request, timeout=10)
except urllib.error.HTTPError as error:
response = error
with response:
raw = response.read()
payload = None
if raw:
try:
payload = json.loads(raw)
except ValueError:
payload = None
return response.code, response.headers, payload, raw
def register(self) -> tuple[dict, dict]:
suffix = uuid.uuid4().hex[:12]
registration = {
"username": "st_" + suffix,
"display_name": "Студент " + suffix,
"password": "T3st-" + uuid.uuid4().hex,
}
status, _headers, user, _raw = self.call("POST", "/api/v1/users", registration)
if status != 201:
raise AssertionError(f"registration failed: HTTP {status}")
return user, registration
def login(self, registration: dict) -> dict:
credential = base64.b64encode(
(registration["username"] + ":" + registration["password"]).encode("utf-8")
).decode("ascii")
status, _headers, session, _raw = self.call(
"POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + credential}
)
if status != 201:
raise AssertionError(f"login failed: HTTP {status}")
return session
def assert_status(actual: int, expected: int, label: str) -> None:
if actual != expected:
raise AssertionError(f"{label}: expected HTTP {expected}, received {actual}")
def error_code(payload) -> str | None:
if not isinstance(payload, dict):
return None
error = payload.get("error")
return error.get("code") if isinstance(error, dict) else None