Files
mtusi2026lab2/student-tests/own_tests.py

104 lines
4.0 KiB
Python
Executable File

#!/usr/bin/env python3
import json
import sys
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check
PASSED = 0
def ok(label):
global PASSED
PASSED += 1
print("ok -", label)
def raw_call(base, method, path, data=None, headers=None):
h = {"Accept": "application/json"}
h.update(headers or {})
req = urllib.request.Request(base + path, data=data, headers=h, method=method)
try:
resp = urllib.request.urlopen(req, timeout=10)
except urllib.error.HTTPError as exc:
resp = exc
with resp:
return resp.code, resp.read()
def main():
base_url = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
c = Client(base_url)
alice, bob, eve, chat = c.bootstrap()
path = "/api/v1/chats/" + chat["id"]
status, body = raw_call(
base_url, "POST", "/api/v1/users",
data=b'{"username": "broken", "display_name": ',
headers={"Content-Type": "application/json", "X-User-Id": alice["id"]},
)
check(status == 400, "malformed JSON must yield 400, got %d" % status)
parsed = json.loads(body)
check(parsed["error"]["code"] == "invalid_request", "malformed JSON must report invalid_request")
ok("malformed JSON -> 400 invalid_request")
c.call("GET", path, 404, actor=eve)
c.call("GET", path + "/messages", 404, actor=eve)
ok("foreign chat access -> 404 (no leak)")
c.call("POST", path + "/messages", 400, actor=alice, body={"text": ""})
c.call("POST", path + "/messages", 400, actor=alice, body={"text": " "})
ok("empty/whitespace message text -> 400")
c.call("POST", "/api/v1/users", 409, body=alice["registration"])
me = c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["json"]
check(me == alice["user"], "existing user must be unaffected by a rejected duplicate registration")
ok("duplicate username -> 409, original user intact")
sent = [c.message(alice, chat, "page-msg-%d" % i)["json"] for i in range(7)]
collected = []
cursor = None
pages = 0
while True:
qs = "?limit=2" + ("&cursor=" + urllib.parse.quote(cursor, safe="") if cursor else "")
page = c.call("GET", path + "/messages" + qs, actor=bob, schema="MessagePage")["json"]
pages += 1
check(len(page["items"]) <= 2, "page must respect limit")
collected.extend(page["items"])
cursor = page["next_cursor"]
if not cursor:
break
check(pages < 50, "pagination did not terminate")
ids_seen = [m["id"] for m in collected]
check(len(ids_seen) == len(set(ids_seen)), "pagination must not repeat messages")
check({m["id"] for m in sent}.issubset(set(ids_seen)), "pagination must not drop messages")
tail = [m for m in collected if m["id"] in {s["id"] for s in sent}]
check(tail == sorted(tail, key=lambda m: (m["created_at"], m["id"])), "pagination must stay ordered")
ok("multi-page pagination traversal: %d pages, %d messages, no dup/loss" % (pages, len(collected)))
first_page = c.call("GET", path + "/messages?limit=1", actor=alice, schema="MessagePage")["json"]
check(first_page["next_cursor"], "need a non-null cursor to test cross-chat reuse")
chat2 = c.call(
"POST", "/api/v1/chats", 201, actor=alice,
body={"title": "second chat", "member_ids": [alice["id"], bob["id"]]}, schema="Chat",
)["json"]
c.message(alice, chat2, "unrelated message")
foreign_cursor = urllib.parse.quote(first_page["next_cursor"], safe="")
c.call("GET", "/api/v1/chats/" + chat2["id"] + "/messages?limit=1&cursor=" + foreign_cursor, 400, actor=alice)
ok("cursor from another chat -> 400 (cursor is bound to its resource)")
print("PASS: %d/%d student checks" % (PASSED, 6))
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print("FAIL:", exc)
raise SystemExit(1)