Lab2 grade 4: PostgreSQL, Redis sessions, Compose, student tests and evidence.
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
"""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"
|
||||
h.update(headers or {})
|
||||
req = urllib.request.Request(BASE_URL + path, data=raw, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=30)
|
||||
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"
|
||||
return {"status": status, "headers": resp.headers, "json": payload, "bytes": data}
|
||||
|
||||
|
||||
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,
|
||||
}
|
||||
Reference in New Issue
Block a user