forked from mtusi2026/mtusi2026lab2
ЛР 2: PostgreSQL, сессии в Valkey, трек 2
This commit is contained in:
@@ -0,0 +1,111 @@
|
||||
"""Shared HTTP helpers for the student checks; stdlib only, Python 3.9+."""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
DEFAULT_BASE = os.environ.get("BASE_URL", "http://localhost:8080")
|
||||
|
||||
|
||||
class Failed(AssertionError):
|
||||
pass
|
||||
|
||||
|
||||
def expect(condition, message):
|
||||
if not condition:
|
||||
raise Failed(message)
|
||||
|
||||
|
||||
def call(base, method, path, body=None, token=None, headers=None, timeout=10, raw=None, content_type=None):
|
||||
sent = {"Accept": "application/json"}
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
sent["Content-Type"] = "application/json"
|
||||
if content_type is not None:
|
||||
sent["Content-Type"] = content_type
|
||||
if token:
|
||||
sent["Authorization"] = "Bearer " + token
|
||||
sent.update(headers or {})
|
||||
request = urllib.request.Request(base + path, data=data, headers=sent, method=method)
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=timeout)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
||||
raise Failed("%s %s: нет соединения (%s)" % (method, path, type(exc).__name__)) from None
|
||||
with response:
|
||||
raw = response.read()
|
||||
payload = None
|
||||
if raw:
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except ValueError:
|
||||
payload = None
|
||||
return {"status": response.code, "headers": response.headers, "json": payload}
|
||||
|
||||
|
||||
def credentials(label="check"):
|
||||
return {
|
||||
"username": "u_%s_%s" % (label, uuid.uuid4().hex[:10]),
|
||||
"display_name": "Проверка " + label,
|
||||
"password": "T3st-" + uuid.uuid4().hex,
|
||||
}
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
return "Basic " + base64.b64encode(("%s:%s" % (username, password)).encode("utf-8")).decode()
|
||||
|
||||
|
||||
def register(base, label="check"):
|
||||
body = credentials(label)
|
||||
result = call(base, "POST", "/api/v1/users", body=body)
|
||||
expect(result["status"] == 201, "регистрация вернула %s" % result["status"])
|
||||
return {"registration": body, "user": result["json"], "id": result["json"]["id"]}
|
||||
|
||||
|
||||
def login(base, actor):
|
||||
result = call(
|
||||
base,
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
headers={"Authorization": basic(actor["registration"]["username"], actor["registration"]["password"])},
|
||||
)
|
||||
expect(result["status"] == 201, "вход вернул %s" % result["status"])
|
||||
actor["token"] = result["json"]["token"]
|
||||
actor["session"] = result["json"]
|
||||
return actor
|
||||
|
||||
|
||||
def member(base, label="check"):
|
||||
return login(base, register(base, label))
|
||||
|
||||
|
||||
def chat_with(base, owner, *others):
|
||||
members = [owner["id"]] + [other["id"] for other in others]
|
||||
result = call(base, "POST", "/api/v1/chats", body={"title": "Проверка " + uuid.uuid4().hex[:8], "member_ids": members}, token=owner["token"])
|
||||
expect(result["status"] == 201, "создание чата вернуло %s" % result["status"])
|
||||
return result["json"]
|
||||
|
||||
|
||||
def arguments(description):
|
||||
parser = argparse.ArgumentParser(description=description)
|
||||
parser.add_argument("--base-url", default=DEFAULT_BASE)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def run(tests, base):
|
||||
failures = []
|
||||
for test in tests:
|
||||
try:
|
||||
test(base)
|
||||
print("PASS %s" % test.__name__)
|
||||
except AssertionError as exc:
|
||||
failures.append(test.__name__)
|
||||
print("FAIL %s: %s" % (test.__name__, exc))
|
||||
print("%d/%d checks passed" % (len(tests) - len(failures), len(tests)))
|
||||
sys.exit(1 if failures else 0)
|
||||
Reference in New Issue
Block a user