forked from mtusi2026/mtusi2026lab2
выполнение лр2 на 4
This commit is contained in:
Executable
+120
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Student-written negative/edge-case tests, additional to the public tests/smoke.py.
|
||||
|
||||
Covers level-4 requirements from README.md:
|
||||
- malformed JSON
|
||||
- foreign chat access
|
||||
- empty message text
|
||||
- duplicate username
|
||||
- multi-page pagination traversal
|
||||
"""
|
||||
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 # noqa: E402
|
||||
|
||||
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"]
|
||||
|
||||
# 1. Malformed JSON body -> 400 invalid_request, not a 500.
|
||||
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")
|
||||
|
||||
# 2. Foreign chat: eve is not a member -> 404, not 403 (no existence leak).
|
||||
c.call("GET", path, 404, actor=eve)
|
||||
c.call("GET", path + "/messages", 404, actor=eve)
|
||||
ok("foreign chat access -> 404 (no leak)")
|
||||
|
||||
# 3. Empty / whitespace-only message text -> 400.
|
||||
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")
|
||||
|
||||
# 4. Duplicate username -> 409 conflict, original user untouched.
|
||||
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")
|
||||
|
||||
# 5. Multi-page pagination traversal: write N messages, walk every page with a small
|
||||
# limit and confirm the full, ordered, duplicate-free set is recovered.
|
||||
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)))
|
||||
|
||||
# 6. A cursor is bound to the chat it was issued for: reusing it on a
|
||||
# different chat the same actor can also read must be rejected.
|
||||
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)
|
||||
Reference in New Issue
Block a user