154 lines
8.6 KiB
Python
154 lines
8.6 KiB
Python
"""Additional lab2 API cases, using the unchanged teacher client."""
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import uuid
|
|
from urllib.parse import quote
|
|
|
|
from client import LAB, check, timestamp
|
|
from validation_edges import acceptance as json_acceptance
|
|
|
|
|
|
def message_headers():
|
|
return {"Idempotency-Key": uuid.uuid4().hex} if LAB >= 3 else {}
|
|
|
|
|
|
def room(c, actor, members=None, title="Lab2 business fixture"):
|
|
return c.call("POST", "/api/v1/chats", 201, actor=actor,
|
|
body={"title": title, "member_ids": members or [actor["id"]]}, schema="Chat")["json"]
|
|
|
|
|
|
def history(c, actor, chat, limit=100):
|
|
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=" + str(limit)
|
|
items, cursors = [], set()
|
|
for _ in range(2000):
|
|
page = c.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
|
items.extend(page["items"])
|
|
cursor = page["next_cursor"]
|
|
if cursor is None:
|
|
check(len({x["id"] for x in items}) == len(items), "history duplicates message IDs")
|
|
return items
|
|
check(cursor not in cursors, "cursor cycle")
|
|
cursors.add(cursor)
|
|
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=" + str(limit) + "&cursor=" + quote(cursor, safe="")
|
|
raise AssertionError("history traversal exceeded test bound")
|
|
|
|
|
|
def boundaries(c):
|
|
actor, other = c.user("bounds"), c.user("other")
|
|
for title in ("", " \t\n", "😀" * 101):
|
|
c.call("POST", "/api/v1/chats", 400, actor=actor,
|
|
body={"title": title, "member_ids": [actor["id"]]})
|
|
for members in ([], [other["id"]], [actor["id"], actor["id"]],
|
|
[actor["id"], str(uuid.uuid4())], [actor["id"], "invalid"]):
|
|
c.call("POST", "/api/v1/chats", 400, actor=actor,
|
|
body={"title": "Invalid members", "member_ids": members})
|
|
chat = room(c, actor, title="😀" * 100)
|
|
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
|
for text in ("", " \t\n", "😀" * 4001):
|
|
c.call("POST", path, 400, actor=actor, body={"text": text}, headers=message_headers())
|
|
message = c.message(actor, chat, "😀" * 4000)["json"]
|
|
check(message["text"] == "😀" * 4000, "Unicode message boundary changed")
|
|
c.call("POST", path, 400, actor=actor, body={"text": "forged", "sender_id": other["id"]}, headers=message_headers())
|
|
for limit in ("0", "101", "-1", "abc", ""):
|
|
c.call("GET", path + "?limit=" + limit, 400, actor=actor)
|
|
for raw in (b'{"text":"x","extra":1}', b'{"Text":"x"}', b'{"text":null}',
|
|
b'{"text":1}', b'{"text":"x"} {}', b'{"text":"\xff"}'):
|
|
c.call("POST", path, 400, actor=actor, raw=raw,
|
|
headers={"Content-Type": "application/json", **message_headers()})
|
|
for target, body in (("/api/v1/chats", {"title": "Media", "member_ids": [actor["id"]]}),
|
|
(path, {"text": "Media"})):
|
|
c.call("POST", target, 415, actor=actor, body=body,
|
|
headers={"Content-Type": "text/plain", **(message_headers() if target == path else {})})
|
|
c.call("GET", "/api/v1/does-not-exist", 404, actor=actor)
|
|
return json_acceptance(c)
|
|
|
|
|
|
def chat_pagination(c):
|
|
owner, outsider = c.user("chatpages"), c.user("chatother")
|
|
empty = c.call("GET", "/api/v1/chats", actor=owner, schema="ChatPage")["json"]
|
|
check(empty == {"items": [], "next_cursor": None}, "empty chat list is not a finished empty page")
|
|
expected = [room(c, owner, title="Chat page " + str(i)) for i in range(7)]
|
|
room(c, outsider, title="Must not appear in owner's list")
|
|
ordered = sorted(expected, key=lambda x: (timestamp(x["created_at"]), uuid.UUID(x["id"]).int))
|
|
seen, cursors, cursor = [], set(), None
|
|
for _ in range(len(expected) + 1):
|
|
path = "/api/v1/chats?limit=2"
|
|
if cursor is not None:
|
|
path += "&cursor=" + quote(cursor, safe="")
|
|
page = c.call("GET", path, actor=owner, schema="ChatPage")["json"]
|
|
check(0 < len(page["items"]) <= 2, "invalid chat page size")
|
|
seen.extend(page["items"])
|
|
check(len(seen) <= len(expected), "chat pagination repeated or leaked items")
|
|
cursor = page["next_cursor"]
|
|
if cursor is None:
|
|
break
|
|
check(cursor not in cursors, "chat cursor cycle")
|
|
cursors.add(cursor)
|
|
rejected = c.call("GET", "/api/v1/chats?cursor=" + quote(cursor, safe=""),
|
|
400, actor=outsider)
|
|
check(rejected["json"]["error"]["code"] == "invalid_request", "foreign chat-list cursor returned wrong error")
|
|
else:
|
|
check(False, "chat pagination exceeded fixture bound")
|
|
check(len({item["id"] for item in seen}) == len(expected), "chat list omitted or repeated IDs")
|
|
check(seen == ordered, "chat pagination lost, repeated, changed or reordered items")
|
|
|
|
first = c.call("GET", "/api/v1/chats?limit=1", actor=owner, schema="ChatPage")["json"]
|
|
check(first["next_cursor"] is not None, "chat cursor ended before remaining items")
|
|
rest = c.call("GET", "/api/v1/chats?limit=100&cursor=" + quote(first["next_cursor"], safe=""),
|
|
actor=owner, schema="ChatPage")["json"]
|
|
check(first["items"] + rest["items"] == ordered and rest["next_cursor"] is None,
|
|
"changing chat-list limit lost, repeated or reordered items")
|
|
for query in ("limit=0", "limit=101", "limit=-1", "limit=abc", "limit=", "cursor=", "cursor=invalid"):
|
|
rejected = c.call("GET", "/api/v1/chats?" + query, 400, actor=owner)
|
|
check(rejected["json"]["error"]["code"] == "invalid_request", "invalid chat-list query returned wrong error")
|
|
return {"items": len(seen), "page_limit": 2, "foreign_cursors_rejected": len(cursors),
|
|
"changed_limit": [1, 100]}
|
|
|
|
|
|
def cursors(c):
|
|
actor, outsider = c.user("cursor"), c.user("outside")
|
|
first, second = room(c, actor), room(c, actor)
|
|
empty = c.call("GET", "/api/v1/chats/" + second["id"] + "/messages", actor=actor, schema="MessagePage")["json"]
|
|
check(empty == {"items": [], "next_cursor": None}, "empty history is not an empty finished page")
|
|
sent = [c.message(actor, first, "Page " + str(i))["json"] for i in range(7)]
|
|
path = "/api/v1/chats/" + first["id"] + "/messages"
|
|
page = c.call("GET", path + "?limit=1", actor=actor, schema="MessagePage")["json"]
|
|
cursor = quote(page["next_cursor"], safe="")
|
|
rest = c.call("GET", path + "?limit=100&cursor=" + cursor, actor=actor, schema="MessagePage")["json"]
|
|
ordered = sorted(sent, key=lambda x: (timestamp(x["created_at"]), uuid.UUID(x["id"]).int))
|
|
check(page["items"] + rest["items"] == ordered and rest["next_cursor"] is None,
|
|
"changing limit lost/repeated/reordered messages")
|
|
c.call("GET", "/api/v1/chats/" + second["id"] + "/messages?cursor=" + cursor, 400, actor=actor)
|
|
for value in ("", "not-a-cursor"):
|
|
c.call("GET", path + "?cursor=" + value, 400, actor=actor)
|
|
c.call("GET", path, 404, actor=outsider)
|
|
c.call("POST", path, 404, actor=outsider, body={"text": "hidden"}, headers=message_headers())
|
|
check(history(c, actor, first, limit=2) == ordered, "complete keyset traversal differs")
|
|
return {"message_items": len(sent), "chat_list": chat_pagination(c)}
|
|
|
|
|
|
def read_after_write(c, client_factory, concurrency=4):
|
|
members = [c.user("writer") for _ in range(10)]
|
|
actor = members[0]
|
|
chat = room(c, actor, members=[m["id"] for m in members])
|
|
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
|
# Warm the empty-history cache before starting concurrent writes.
|
|
c.call("GET", path, actor=actor, schema="MessagePage")
|
|
|
|
def write_then_read(index):
|
|
local = client_factory()
|
|
writer = members[index % len(members)]
|
|
confirmed = local.message(writer, chat, "Read-after-write " + str(index))["json"]
|
|
check(confirmed["sender_id"] == writer["id"], "message sender differs from authenticated writer")
|
|
page = local.call("GET", path, actor=writer, schema="MessagePage")["json"]
|
|
check(any(m == confirmed for m in page["items"]), "confirmed message absent from next read")
|
|
return confirmed
|
|
|
|
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
|
messages = list(pool.map(write_then_read, range(100)))
|
|
stored = history(c, actor, chat, limit=37)
|
|
check(len({m["id"] for m in messages}) == 100, "concurrent writes reused message IDs")
|
|
check(stored == sorted(messages, key=lambda m: (timestamp(m["created_at"]), uuid.UUID(m["id"]).int)),
|
|
"concurrent writes lost, duplicated, changed or reordered confirmations")
|
|
check({m["sender_id"] for m in stored} == {m["id"] for m in members}, "not all writers contributed")
|
|
return {"writers": len(members), "messages": len(stored), "concurrency": concurrency}
|