Files
mtusi2026lab2/student-tests/test_api.py
T
2026-10-16 05:27:13 +03:00

171 lines
7.4 KiB
Python

#!/usr/bin/env python3
"""Собственные проверки контракта lab2 (дополняют публичный tests/smoke.py).
BASE_URL=http://127.0.0.1:8080 python3 student-tests/test_api.py
"""
import base64
import json
import os
import urllib.error
import urllib.request
import uuid
from urllib.parse import quote
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
PASSWORD = "Student-test-password-1"
def call(method, path, expected, body=None, token=None, raw=None,
content_type="auto", headers=None):
h = {"Accept": "application/json"}
data = raw
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode()
h["Content-Type"] = "application/json"
elif data is not None and content_type == "auto":
h["Content-Type"] = "application/json"
elif data is not None and content_type:
h["Content-Type"] = content_type
if token:
h["Authorization"] = "Bearer " + token
h.update(headers or {})
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
try:
resp = urllib.request.urlopen(req, timeout=15)
except urllib.error.HTTPError as e:
resp = e
raw_b = resp.read()
assert resp.status == expected, (method, path, resp.status, raw_b[:300])
rid = resp.headers.get("X-Request-Id")
assert rid, "missing X-Request-Id"
payload = json.loads(raw_b) if raw_b else None
if resp.status >= 400:
assert payload["error"]["request_id"] == rid
if resp.status == 401:
assert resp.headers.get("WWW-Authenticate"), "401 without WWW-Authenticate"
return payload
def unique(prefix):
return prefix + "_" + uuid.uuid4().hex[:12]
def basic(username, password):
return {"Authorization": "Basic " + base64.b64encode(
f"{username}:{password}".encode()).decode()}
def register(prefix, display_name="U"):
user = call("POST", "/api/v1/users", 201, {
"username": unique(prefix), "display_name": display_name, "password": PASSWORD})
user["token"] = call("POST", "/api/v1/auth/sessions", 201,
headers=basic(user["username"], PASSWORD))["token"]
return user
def test_registration_validation():
call("POST", "/api/v1/users", 400, raw=b"{not json")
call("POST", "/api/v1/users", 400, raw=b'{"username":"x"')
call("POST", "/api/v1/users", 415, raw=b'{"username":"aa1"}', content_type="text/plain")
call("POST", "/api/v1/users", 400,
{"username": unique("n"), "display_name": 1, "password": PASSWORD})
call("POST", "/api/v1/users", 400,
{"username": unique("n"), "display_name": "я" * 101, "password": PASSWORD})
call("POST", "/api/v1/users", 400,
{"username": unique("n"), "display_name": "N", "password": "short"})
call("POST", "/api/v1/users", 400,
{"username": unique("n"), "display_name": "N"})
call("POST", "/api/v1/users", 400,
{"username": unique("n"), "display_name": "N", "password": PASSWORD, "extra": 1})
name = unique("dup")
body = {"username": name, "display_name": "Same", "password": PASSWORD}
user = call("POST", "/api/v1/users", 201, body)
assert "password" not in user and "password_hash" not in user
call("POST", "/api/v1/users", 409, body)
def test_auth_transitions():
a = register("a", 'Alice "цитата"')
assert a["display_name"] == 'Alice "цитата"'
call("GET", "/api/v1/users/me", 401)
call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": a["id"]})
call("GET", "/api/v1/users/me", 401, headers=basic(a["username"], PASSWORD))
call("GET", "/api/v1/users/me", 401, token="not-a-real-token")
call("POST", "/api/v1/auth/sessions", 401)
call("POST", "/api/v1/auth/sessions", 401, headers=basic(a["username"], "wrong-password-1"))
me = call("GET", "/api/v1/users/me", 200, token=a["token"])
assert me["id"] == a["id"]
def test_messages_and_access():
a, b, eve = register("a"), register("b"), register("e")
chat = call("POST", "/api/v1/chats", 201,
{"title": "t", "member_ids": [a["id"], b["id"]]}, token=a["token"])
path = "/api/v1/chats/" + chat["id"] + "/messages"
call("POST", path, 400, {"text": ""}, token=a["token"])
call("POST", path, 400, {"text": " "}, token=a["token"])
call("POST", path, 400, {"text": "x" * 4001}, token=a["token"])
call("POST", path, 400, {"text": "hi", "sender_id": eve["id"]}, token=a["token"])
msg = call("POST", path, 201, {"text": 'раз "два" три'}, token=a["token"])
assert msg["text"] == 'раз "два" три' and msg["sender_id"] == a["id"]
call("GET", "/api/v1/chats/" + chat["id"], 404, token=eve["token"])
call("GET", path, 404, token=eve["token"])
call("POST", path, 404, {"text": "nope"}, token=eve["token"])
call("GET", "/api/v1/chats/not-a-uuid", 400, token=a["token"])
def test_chat_validation():
a, b = register("a"), register("b")
call("POST", "/api/v1/chats", 400,
{"title": "т" * 101, "member_ids": [a["id"], b["id"]]}, token=a["token"])
call("POST", "/api/v1/chats", 400,
{"title": "no caller", "member_ids": [b["id"]]}, token=a["token"])
call("POST", "/api/v1/chats", 400,
{"title": "dup", "member_ids": [a["id"], b["id"], b["id"]]}, token=a["token"])
call("POST", "/api/v1/chats", 400,
{"title": "unknown", "member_ids": [a["id"], str(uuid.uuid4())]}, token=a["token"])
def test_pagination():
a, b = register("a"), register("b")
chats = [call("POST", "/api/v1/chats", 201,
{"title": "chat-%d" % i, "member_ids": [a["id"], b["id"]]}, token=a["token"])
for i in range(3)]
p1 = call("GET", "/api/v1/chats?limit=1", 200, token=a["token"])
assert len(p1["items"]) == 1 and p1["next_cursor"]
p2 = call("GET", "/api/v1/chats?limit=1&cursor=" + quote(p1["next_cursor"], safe=""),
200, token=a["token"])
assert p1["items"][0]["id"] != p2["items"][0]["id"]
call("GET", "/api/v1/chats?limit=0", 400, token=a["token"])
call("GET", "/api/v1/chats?limit=101", 400, token=a["token"])
call("GET", "/api/v1/chats?limit=1&cursor=bad|cursor", 400, token=a["token"])
path = "/api/v1/chats/" + chats[0]["id"] + "/messages"
m1 = call("POST", path, 201, {"text": "one"}, token=a["token"])
m2 = call("POST", path, 201, {"text": "two"}, token=b["token"])
q1 = call("GET", path + "?limit=1", 200, token=a["token"])
assert len(q1["items"]) == 1 and q1["next_cursor"]
q2 = call("GET", path + "?limit=1&cursor=" + quote(q1["next_cursor"], safe=""),
200, token=a["token"])
assert len(q2["items"]) == 1 and q2["next_cursor"] is None
assert {q1["items"][0]["id"], q2["items"][0]["id"]} == {m1["id"], m2["id"]}
call("GET", path + "?limit=0", 400, token=a["token"])
other = "/api/v1/chats/" + chats[1]["id"] + "/messages"
call("GET", other + "?cursor=" + quote(q1["next_cursor"], safe=""), 400, token=a["token"])
def test_logout():
a = register("lo")
call("DELETE", "/api/v1/auth/sessions/current", 204, token=a["token"])
call("GET", "/api/v1/users/me", 401, token=a["token"])
call("DELETE", "/api/v1/auth/sessions/current", 401, token=a["token"])
if __name__ == "__main__":
for test in (test_registration_validation, test_auth_transitions, test_messages_and_access,
test_chat_validation, test_pagination, test_logout):
test()
print("ok", test.__name__)
print("PASS student-tests")