ЛР 2: закрыть уровень 4
Завершить PostgreSQL, Redis-сессии, миграции, таймауты и диагностику. Зафиксировать собственные тесты и доказательства финального прогона: 43 PASS, 0 FAIL, 0 SKIP; 768 HTTP-запросов без ошибок. Добавить официальный отчёт с запуском, архитектурой, SQL-планами и ограничениями. PR отложен до завершения уровня 5.
This commit is contained in:
@@ -0,0 +1,275 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab 1 level-4 acceptance checks against a running HTTP server.
|
||||
|
||||
Run: python3 student-tests/level4.py --base-url http://localhost:8080
|
||||
Creates only synthetic users, chats and messages.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, Failure, check, timestamp # noqa: E402
|
||||
from validation_edges import acceptance # noqa: E402
|
||||
|
||||
|
||||
def chat_for(client, members):
|
||||
return client.call(
|
||||
"POST", "/api/v1/chats", 201, actor=members[0],
|
||||
body={"title": "Проверка уровня 4", "member_ids": [x["id"] for x in members]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
|
||||
|
||||
def malformed_json(client):
|
||||
response = client.call(
|
||||
"POST", "/api/v1/users", 400,
|
||||
raw=b'{"username":', headers={"Content-Type": "application/json"},
|
||||
)
|
||||
check(response["json"]["error"]["code"] == "invalid_request", "wrong error for malformed JSON")
|
||||
|
||||
|
||||
def foreign_chat(client):
|
||||
owner, outsider = client.user("owner"), client.user("outsider")
|
||||
chat = chat_for(client, [owner])
|
||||
path = "/api/v1/chats/" + chat["id"]
|
||||
for method, suffix, body in (
|
||||
("GET", "", None),
|
||||
("GET", "/messages", None),
|
||||
("POST", "/messages", {"text": "synthetic"}),
|
||||
):
|
||||
result = client.call(method, path + suffix, 404, actor=outsider, body=body)
|
||||
check(result["json"]["error"]["code"] == "not_found", "foreign chat revealed")
|
||||
|
||||
|
||||
def empty_message(client):
|
||||
owner = client.user("empty")
|
||||
chat = chat_for(client, [owner])
|
||||
for value in ("", " \t\n "):
|
||||
result = client.call(
|
||||
"POST", "/api/v1/chats/" + chat["id"] + "/messages", 400,
|
||||
actor=owner, body={"text": value},
|
||||
)
|
||||
check(result["json"]["error"]["code"] == "invalid_request", "empty text accepted")
|
||||
|
||||
|
||||
def duplicate_username(client):
|
||||
owner = client.user("duplicate")
|
||||
result = client.call("POST", "/api/v1/users", 409, body=owner["registration"])
|
||||
check(result["json"]["error"]["code"] == "conflict", "duplicate username not rejected")
|
||||
|
||||
|
||||
def media_type(client):
|
||||
owner = client.user("media")
|
||||
chat = chat_for(client, [owner])
|
||||
requests = (
|
||||
("/api/v1/users", {"username": "media_probe", "display_name": "Probe"}, None),
|
||||
("/api/v1/chats", {"title": "Probe", "member_ids": [owner["id"]]}, owner),
|
||||
("/api/v1/chats/" + chat["id"] + "/messages", {"text": "synthetic"}, owner),
|
||||
)
|
||||
for path, body, actor in requests:
|
||||
response = client.call("POST", path, 415, actor=actor,
|
||||
raw=json.dumps(body).encode(), headers={"Content-Type": "text/plain"})
|
||||
check(response["json"]["error"]["code"] == "unsupported_media_type", "wrong 415 error code")
|
||||
|
||||
|
||||
def request_validation(client):
|
||||
owner = client.user("validation")
|
||||
chat = chat_for(client, [owner])
|
||||
cases = (
|
||||
("/api/v1/users", {"username": 123, "display_name": "Probe"}, None),
|
||||
("/api/v1/users", {"username": "validation_probe", "display_name": "Probe", "extra": True}, None),
|
||||
("/api/v1/chats", {"title": "Probe", "member_ids": [owner["id"], owner["id"]]}, owner),
|
||||
("/api/v1/chats", {"title": "Probe", "member_ids": []}, owner),
|
||||
("/api/v1/chats/" + chat["id"] + "/messages", {"text": 123}, owner),
|
||||
("/api/v1/chats/" + chat["id"] + "/messages", {"text": "synthetic", "sender_id": owner["id"]}, owner),
|
||||
)
|
||||
for path, body, actor in cases:
|
||||
response = client.call("POST", path, 400, actor=actor, body=body)
|
||||
check(response["json"]["error"]["code"] == "invalid_request", "wrong validation error code")
|
||||
|
||||
|
||||
def unknown_api_route(client):
|
||||
owner = client.user("route")
|
||||
response = client.call("GET", "/api/v1/does-not-exist", 404, actor=owner)
|
||||
check(response["json"]["error"]["code"] == "not_found", "wrong unknown-route error code")
|
||||
|
||||
|
||||
def pagination_parameters(client):
|
||||
owner = client.user("params")
|
||||
chat = chat_for(client, [owner])
|
||||
failures = []
|
||||
for path in ("/api/v1/chats", "/api/v1/chats/" + chat["id"] + "/messages"):
|
||||
for value in ("0", "101", "invalid", ""):
|
||||
try:
|
||||
response = client.call("GET", path + "?limit=" + value, 400, actor=owner)
|
||||
check(response["json"]["error"]["code"] == "invalid_request", "wrong limit error code")
|
||||
except Failure as exc:
|
||||
failures.append("limit=%r: %s" % (value, exc))
|
||||
client.call("GET", path + "?cursor=invalid", 400, actor=owner)
|
||||
check(not failures, "; ".join(failures))
|
||||
|
||||
|
||||
def cursor_binding(client):
|
||||
owner = client.user("cursor")
|
||||
first, second = chat_for(client, [owner]), chat_for(client, [owner])
|
||||
written = [client.message(owner, first, "cursor item %d" % i)["json"] for i in range(5)]
|
||||
path = "/api/v1/chats/" + first["id"] + "/messages"
|
||||
page = client.call("GET", path + "?limit=1", actor=owner, schema="MessagePage")["json"]
|
||||
cursor = quote(page["next_cursor"], safe="")
|
||||
client.call("GET", "/api/v1/chats/" + second["id"] + "/messages?cursor=" + cursor, 400, actor=owner)
|
||||
rest = client.call("GET", path + "?limit=100&cursor=" + cursor, actor=owner, schema="MessagePage")["json"]
|
||||
check(page["items"] + rest["items"] == written, "changing limit lost or duplicated messages")
|
||||
check(rest["next_cursor"] is None, "final cursor must be null")
|
||||
|
||||
|
||||
def chat_pagination(client):
|
||||
owner, outsider = client.user("chatpages"), client.user("chatother")
|
||||
expected = [chat_for(client, [owner]) for _ in range(7)]
|
||||
seen, cursor = [], None
|
||||
while True:
|
||||
path = "/api/v1/chats?limit=2"
|
||||
if cursor:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
page = client.call("GET", path, actor=owner, schema="ChatPage")["json"]
|
||||
seen.extend(page["items"])
|
||||
check(len(seen) <= 7, "chat pagination repeated items")
|
||||
next_cursor = page["next_cursor"]
|
||||
check(next_cursor is None or next_cursor != cursor, "chat cursor did not advance")
|
||||
if next_cursor is None:
|
||||
break
|
||||
client.call("GET", "/api/v1/chats?cursor=" + quote(next_cursor, safe=""), 400, actor=outsider)
|
||||
cursor = next_cursor
|
||||
check(seen == sorted(expected, key=lambda item: (timestamp(item["created_at"]), item["id"])),
|
||||
"chat pagination lost, repeated or reordered items")
|
||||
|
||||
|
||||
def unicode_boundaries(client):
|
||||
registration = {"username": "unicode_" + uuid.uuid4().hex[:12], "display_name": "😀" * 100}
|
||||
user = client.call("POST", "/api/v1/users", 201, body=registration, schema="User")["json"]
|
||||
check(user["display_name"] == registration["display_name"], "Unicode display name changed")
|
||||
client.call("POST", "/api/v1/users", 400,
|
||||
body={"username": "unicode_" + uuid.uuid4().hex[:12], "display_name": "😀" * 101})
|
||||
actor = {"id": user["id"]}
|
||||
chat = client.call("POST", "/api/v1/chats", 201, actor=actor,
|
||||
body={"title": "😀" * 100, "member_ids": [user["id"]]}, schema="Chat")["json"]
|
||||
message = client.message(actor, chat, "😀" * 4000)["json"]
|
||||
check(message["text"] == "😀" * 4000, "Unicode text changed")
|
||||
client.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 400,
|
||||
actor=actor, body={"text": "😀" * 4001})
|
||||
|
||||
|
||||
def multiple_pages(client):
|
||||
owner = client.user("pages")
|
||||
chat = chat_for(client, [owner])
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
written = [client.message(owner, chat, "page item %d" % i)["json"] for i in range(7)]
|
||||
seen = []
|
||||
cursor = None
|
||||
while True:
|
||||
url = path + "?limit=2"
|
||||
if cursor is not None:
|
||||
url += "&cursor=" + quote(cursor, safe="")
|
||||
page = client.call("GET", url, actor=owner, schema="MessagePage")["json"]
|
||||
check(0 < len(page["items"]) <= 2, "invalid page size")
|
||||
seen.extend(page["items"])
|
||||
next_cursor = page["next_cursor"]
|
||||
check(next_cursor is None or next_cursor != cursor, "cursor did not advance")
|
||||
check(len(seen) <= len(written), "pagination loop or duplicate")
|
||||
if next_cursor is None:
|
||||
break
|
||||
cursor = next_cursor
|
||||
ids = [item["id"] for item in seen]
|
||||
check(len(ids) == 7 and len(set(ids)) == 7, "pagination omitted or repeated messages")
|
||||
check(set(ids) == {item["id"] for item in written}, "pagination returned different messages")
|
||||
check(seen == sorted(seen, key=lambda item: (timestamp(item["created_at"]), item["id"])),
|
||||
"history is not ordered by (created_at, id)")
|
||||
|
||||
|
||||
def concurrent_messages(client):
|
||||
members = [client.user("race%d" % i) for i in range(10)]
|
||||
chat = chat_for(client, members)
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
barrier = threading.Barrier(10)
|
||||
|
||||
def sender(index):
|
||||
local = Client(client.base)
|
||||
barrier.wait(timeout=10)
|
||||
return [local.message(members[index], chat, "race %d %d" % (index, j))["json"]
|
||||
for j in range(10)]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
groups = list(pool.map(sender, range(10)))
|
||||
written = [item for group in groups for item in group]
|
||||
check(len(written) == 100 and len({item["id"] for item in written}) == 100,
|
||||
"100 writes were not acknowledged with unique IDs")
|
||||
|
||||
seen = []
|
||||
cursor = None
|
||||
while True:
|
||||
url = path + "?limit=37"
|
||||
if cursor is not None:
|
||||
url += "&cursor=" + quote(cursor, safe="")
|
||||
page = client.call("GET", url, actor=members[0], schema="MessagePage")["json"]
|
||||
seen.extend(page["items"])
|
||||
check(len(seen) <= 100, "history returned more than 100 messages")
|
||||
next_cursor = page["next_cursor"]
|
||||
check(next_cursor is None or next_cursor != cursor, "cursor did not advance")
|
||||
if next_cursor is None:
|
||||
break
|
||||
cursor = next_cursor
|
||||
|
||||
ids = [item["id"] for item in seen]
|
||||
check(len(ids) == 100 and len(set(ids)) == 100, "history does not contain 100 unique messages")
|
||||
check(set(ids) == {item["id"] for item in written}, "acknowledged messages missing from history")
|
||||
check({item["id"]: item for item in seen} == {item["id"]: item for item in written},
|
||||
"stored messages differ from acknowledged messages")
|
||||
check({item["sender_id"] for item in seen} == {member["id"] for member in members},
|
||||
"not all 10 clients contributed")
|
||||
print("RESULT: 10 clients x 10 writes; 100 acknowledged; 100 unique IDs in complete history")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url)
|
||||
failures = []
|
||||
scenarios = (
|
||||
("malformed JSON", malformed_json),
|
||||
("foreign chat", foreign_chat),
|
||||
("empty message", empty_message),
|
||||
("duplicate username", duplicate_username),
|
||||
("multiple pages", multiple_pages),
|
||||
("100 concurrent messages", concurrent_messages),
|
||||
("unsupported media type", media_type),
|
||||
("request validation", request_validation),
|
||||
("unknown API route", unknown_api_route),
|
||||
("pagination parameters", pagination_parameters),
|
||||
("cursor binding and changed limit", cursor_binding),
|
||||
("chat pagination", chat_pagination),
|
||||
("Unicode code-point boundaries", unicode_boundaries),
|
||||
("exact JSON field names", lambda c: acceptance(c, "key_case")),
|
||||
("strict UTF-8 and valid Unicode", lambda c: acceptance(c, "utf8")),
|
||||
("JSON required fields/types/document", lambda c: acceptance(c, "shape")),
|
||||
("additional contract boundaries", lambda c: acceptance(c, "boundaries")),
|
||||
)
|
||||
for name, scenario in scenarios:
|
||||
try:
|
||||
scenario(client)
|
||||
print("PASS:", name)
|
||||
except (Failure, OSError, ValueError) as exc:
|
||||
failures.append(name)
|
||||
print("FAIL: %s: %s" % (name, exc))
|
||||
print("SUMMARY: %d/%d passed" % (len(scenarios) - len(failures), len(scenarios)))
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user