Files
mtusi2026lab4-fork/student-tests/run-test.py
T
2026-10-26 18:16:58 +03:00

125 lines
5.0 KiB
Python

#!/usr/bin/env python3
"""Student tests lab2. Запуск: python3 student-tests/run-test.py [--base-url URL]"""
import argparse
import base64
import json
import sys
import urllib.error
import urllib.request
import uuid
BASE = "http://localhost:8080"
FAILURES = []
def req(method, path, body=None, raw=None, token=None, ctype="application/json"):
headers, data = {}, None
if raw is not None:
data, headers["Content-Type"] = raw.encode("utf-8"), ctype
elif body is not None:
data, headers["Content-Type"] = json.dumps(body, ensure_ascii=False).encode("utf-8"), ctype
if token:
if token.startswith("Basic "):
headers["Authorization"] = token
else:
headers["Authorization"] = f"Bearer {token}"
r = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(r, timeout=30) as resp:
payload = resp.read().decode("utf-8")
return resp.status, dict(resp.headers), (json.loads(payload) if payload else None)
except urllib.error.HTTPError as e:
payload = e.read().decode("utf-8")
try:
return e.code, dict(e.headers), json.loads(payload)
except ValueError:
return e.code, dict(e.headers), None
def check(name, cond, detail=""):
if not cond:
FAILURES.append(name)
print(f"[{'PASS' if cond else 'FAIL'}] {name}" + (f" -- {detail}" if not cond and detail else ""))
def register_user(username, display_name, password):
st, _, body = req("POST", "/api/v1/users", {"username": username, "display_name": display_name, "password": password})
assert st == 201, f"cannot create user: {st} {body}"
return body
def login(username, password):
creds = base64.b64encode(f"{username}:{password}".encode()).decode()
st, _, body = req("POST", "/api/v1/auth/sessions", token=f"Basic {creds}")
assert st == 201, f"cannot login: {st} {body}"
return body # Возвращаем весь словарь ответа
def main():
global BASE
ap = argparse.ArgumentParser()
ap.add_argument("--base-url", default="http://localhost:8080")
BASE = ap.parse_args().base_url.rstrip("/")
# Health checks
st, hdr, body = req("GET", "/health/live")
check("health live 200", st == 200 and body == {"status": "ok"})
check("X-Request-Id present", bool(hdr.get("X-Request-Id")))
# Validation tests
st, _, body = req("POST", "/api/v1/users", raw='{"username": "abc",')
check("malformed JSON -> 400", st == 400 and body["error"]["code"] == "invalid_request")
st, _, _ = req("POST", "/api/v1/users", {"username": "BadName", "display_name": "x", "password": "validpassword123"})
check("username pattern -> 400", st == 400)
# Registration & Login
pwd = "SecurePassword123!"
alice = register_user("alice" + uuid.uuid4().hex[:6], "Алиса", pwd)
bob = register_user("bob" + uuid.uuid4().hex[:6], "Боб", pwd)
st, _, body = req("POST", "/api/v1/users", {"username": alice["username"], "display_name": "dup", "password": pwd})
check("duplicate username -> 409", st == 409 and body["error"]["code"] == "conflict")
# ИСПРАВЛЕНО: Достаем токен из словаря ответа
alice_login_resp = login(alice["username"], pwd)
alice_token = alice_login_resp["token"]
check("login returns token", "token" in alice_login_resp and "user" in alice_login_resp)
# Auth checks
st, _, body = req("GET", "/api/v1/users/me")
check("no token -> 401", st == 401 and body["error"]["code"] == "unauthorized")
st, _, body = req("GET", "/api/v1/users/me", token="invalid_token")
check("invalid token -> 401", st == 401)
# Chat & Messages
st, _, chat = req("POST", "/api/v1/chats", {"title": "Чат", "member_ids": [alice["id"], bob["id"]]}, token=alice_token)
check("create chat 201", st == 201)
st, _, body = req("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "Привет"}, token=alice_token)
check("send message 201", st == 201 and body["text"] == "Привет")
st, _, body = req("GET", f"/api/v1/chats/{chat['id']}/messages?limit=10", token=alice_token)
check("get messages 200", st == 200 and len(body["items"]) == 1)
# Outsider check
eve = register_user("eve" + uuid.uuid4().hex[:6], "Ева", pwd)
eve_login_resp = login(eve["username"], pwd)
eve_token = eve_login_resp["token"] # ИСПРАВЛЕНО
st, _, body = req("GET", f"/api/v1/chats/{chat['id']}", token=eve_token)
check("outsider GET chat -> 404", st == 404 and body["error"]["code"] == "not_found")
# Logout (Путь согласно openapi.json: /auth/sessions/current)
st, _, _ = req("DELETE", "/api/v1/auth/sessions/current", token=alice_token)
check("logout 204", st == 204)
st, _, body = req("GET", "/api/v1/users/me", token=alice_token)
check("token revoked -> 401", st == 401)
print()
if FAILURES:
print(f"FAILED {len(FAILURES)}: {FAILURES}")
sys.exit(1)
print("ALL STUDENT TESTS PASSED")
if __name__ == "__main__":
main()