Files
mtusi2026lab5/student-tests/test_api.py
T
2026-10-26 18:05:06 +03:00

88 lines
2.9 KiB
Python

#!/usr/bin/env python3
"""Black-box grading evidence beyond the public smoke test."""
from concurrent.futures import ThreadPoolExecutor
import json
import sys
import uuid
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run # noqa: E402
def collect_messages(client, actor, chat, page_size=17):
items = []
cursor = None
while True:
path = f"/api/v1/chats/{chat['id']}/messages?limit={page_size}"
if cursor:
path += "&cursor=" + quote(cursor, safe="")
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
items.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return items
def main():
args = arguments("Student negative, pagination and concurrency tests")
client = Client(args.base_url, args.ca_file)
alice, bob, outsider, chat = client.bootstrap()
client.call(
"POST",
"/api/v1/users",
400,
raw=b'{"username":',
headers={"Content-Type": "application/json"},
)
client.call(
"POST",
"/api/v1/users",
415,
raw=b'{"username":"wrong_media","display_name":"Wrong"}',
headers={"Content-Type": "text/plain"},
)
client.call("POST", "/api/v1/users", 409, body=alice["registration"])
client.call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
400,
actor=alice,
body={"text": " \t"},
)
client.call("GET", f"/api/v1/chats/{chat['id']}", 404, actor=outsider)
prefix = "race-" + uuid.uuid4().hex + "-"
def send(worker_id):
local = Client(args.base_url, args.ca_file)
return [
local.message(alice, chat, f"{prefix}{worker_id}-{index}")["json"]
for index in range(10)
]
with ThreadPoolExecutor(max_workers=10) as pool:
created = [message for batch in pool.map(send, range(10)) for message in batch]
check(len(created) == 100, "not all concurrent requests succeeded")
check(len({message["id"] for message in created}) == 100, "duplicate message ids returned")
history = collect_messages(client, bob, chat)
concurrent_history = [message for message in history if message["text"].startswith(prefix)]
check(len(concurrent_history) == 100, "history does not contain exactly 100 concurrent messages")
check(len({message["id"] for message in concurrent_history}) == 100, "history contains duplicates")
check(
history == sorted(history, key=lambda message: (message["created_at"], uuid.UUID(message["id"]).int)),
"multi-page history is out of order",
)
print("PASS: malformed JSON/media type, duplicate username, blank message, outsider access, pagination")
print("PASS: 10 clients created exactly 100 unique messages")
if __name__ == "__main__":
run(main)