Lab2: starting
This commit is contained in:
@@ -0,0 +1,227 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
def request(
|
||||
base_url: str,
|
||||
method: str,
|
||||
path: str,
|
||||
body: bytes | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> tuple[int, dict, dict[str, str]]:
|
||||
request_headers = {"Accept": "application/json"}
|
||||
if headers:
|
||||
request_headers.update(headers)
|
||||
|
||||
req = urllib.request.Request(
|
||||
f"{base_url.rstrip('/')}{path}",
|
||||
data=body,
|
||||
headers=request_headers,
|
||||
method=method,
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
raw = response.read().decode("utf-8")
|
||||
return response.status, json.loads(raw) if raw else {}, dict(response.headers.items())
|
||||
except urllib.error.HTTPError as exc:
|
||||
raw = exc.read().decode("utf-8")
|
||||
return exc.code, json.loads(raw) if raw else {}, dict(exc.headers.items())
|
||||
|
||||
|
||||
def json_request(
|
||||
base_url: str,
|
||||
method: str,
|
||||
path: str,
|
||||
payload: dict,
|
||||
user_id: str | None = None,
|
||||
) -> tuple[int, dict, dict[str, str]]:
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if user_id:
|
||||
headers["X-User-Id"] = user_id
|
||||
return request(
|
||||
base_url,
|
||||
method,
|
||||
path,
|
||||
json.dumps(payload).encode("utf-8"),
|
||||
headers,
|
||||
)
|
||||
|
||||
|
||||
def expect_error(status: int, body: dict, expected_status: int, expected_code: str) -> None:
|
||||
assert status == expected_status, f"expected HTTP {expected_status}, got {status}: {body}"
|
||||
assert body.get("error", {}).get("code") == expected_code, (
|
||||
f"expected error.code={expected_code!r}, got {body}"
|
||||
)
|
||||
assert body.get("error", {}).get("request_id"), f"missing error request_id: {body}"
|
||||
|
||||
def create_user(base_url: str, suffix: str) -> dict:
|
||||
status, body, _ = json_request(
|
||||
base_url,
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{
|
||||
"username": f"u_{suffix}",
|
||||
"display_name": f"User {suffix}",
|
||||
},
|
||||
)
|
||||
assert status == 201, f"create user failed: {status}, {body}"
|
||||
return body
|
||||
|
||||
def create_chat(base_url: str, owner_id: str, member_ids: list[str], suffix: str) -> dict:
|
||||
status, body, _ = json_request(
|
||||
base_url,
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{
|
||||
"title": f"Extra tests {suffix}",
|
||||
"member_ids": member_ids,
|
||||
},
|
||||
owner_id,
|
||||
)
|
||||
assert status == 201, f"create chat failed: {status}, {body}"
|
||||
return body
|
||||
|
||||
|
||||
def test_malformed_json(base_url: str) -> None:
|
||||
status, body, _ = request(
|
||||
base_url,
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
b'{"username": "bad_json",',
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
expect_error(status, body, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_foreign_chat(base_url: str, owner: dict, outsider: dict, suffix: str) -> None:
|
||||
chat = create_chat(base_url, owner["id"], [owner["id"]], suffix)
|
||||
status, body, _ = request(
|
||||
base_url,
|
||||
"GET",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers={"X-User-Id": outsider["id"]},
|
||||
)
|
||||
expect_error(status, body, 404, "not_found")
|
||||
|
||||
|
||||
def test_empty_message(base_url: str, owner: dict, suffix: str) -> None:
|
||||
chat = create_chat(base_url, owner["id"], [owner["id"]], suffix)
|
||||
status, body, _ = json_request(
|
||||
base_url,
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
{"text": " "},
|
||||
owner["id"],
|
||||
)
|
||||
expect_error(status, body, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_duplicate_username(base_url: str, suffix: str) -> None:
|
||||
username = f"dup_{suffix}"
|
||||
|
||||
status, body, _ = json_request(
|
||||
base_url,
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": username, "display_name": "Original"},
|
||||
)
|
||||
assert status == 201, f"first user creation failed: {status}, {body}"
|
||||
|
||||
status, body, _ = json_request(
|
||||
base_url,
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": username, "display_name": "Duplicate"},
|
||||
)
|
||||
expect_error(status, body, 409, "conflict")
|
||||
|
||||
|
||||
def test_message_pagination(base_url: str, owner: dict, suffix: str) -> None:
|
||||
chat = create_chat(base_url, owner["id"], [owner["id"]], suffix)
|
||||
expected_texts = [f"page_{suffix}_{index}" for index in range(7)]
|
||||
|
||||
for text in expected_texts:
|
||||
status, body, _ = json_request(
|
||||
base_url,
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
{"text": text},
|
||||
owner["id"],
|
||||
)
|
||||
assert status == 201, f"message creation failed: {status}, {body}"
|
||||
|
||||
received = []
|
||||
cursor = None
|
||||
|
||||
while True:
|
||||
query = {"limit": "3"}
|
||||
if cursor:
|
||||
query["cursor"] = cursor
|
||||
|
||||
status, body, _ = request(
|
||||
base_url,
|
||||
"GET",
|
||||
f"/api/v1/chats/{chat['id']}/messages?{urllib.parse.urlencode(query)}",
|
||||
headers={"X-User-Id": owner["id"]},
|
||||
)
|
||||
assert status == 200, f"history request failed: {status}, {body}"
|
||||
|
||||
received.extend(body["items"])
|
||||
cursor = body["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
|
||||
received_ids = [message["id"] for message in received]
|
||||
received_texts = [message["text"] for message in received]
|
||||
|
||||
assert len(received) == len(expected_texts), (
|
||||
f"expected {len(expected_texts)} messages, got {len(received)}"
|
||||
)
|
||||
assert len(set(received_ids)) == len(expected_texts), "pagination returned duplicate message IDs"
|
||||
assert received_texts == expected_texts, (
|
||||
f"unexpected message order/content: {received_texts}"
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = parser.parse_args()
|
||||
|
||||
suffix = uuid.uuid4().hex[:12]
|
||||
owner = create_user(args.base_url, f"owner_{suffix}")
|
||||
outsider = create_user(args.base_url, f"outsider_{suffix}")
|
||||
|
||||
tests = [
|
||||
("malformed JSON -> 400 invalid_request", lambda: test_malformed_json(args.base_url)),
|
||||
("foreign chat -> 404 not_found", lambda: test_foreign_chat(args.base_url, owner, outsider, suffix)),
|
||||
("empty message -> 400 invalid_request", lambda: test_empty_message(args.base_url, owner, suffix)),
|
||||
("duplicate username -> 409 conflict", lambda: test_duplicate_username(args.base_url, suffix)),
|
||||
("message pagination across pages", lambda: test_message_pagination(args.base_url, owner, suffix)),
|
||||
]
|
||||
|
||||
for name, test in tests:
|
||||
test()
|
||||
print(f"PASS: {name}")
|
||||
|
||||
print("PASS: extra lab1 scenarios (5/5)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except AssertionError as exc:
|
||||
print(f"FAIL: {exc}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
except Exception as exc:
|
||||
print(f"FAIL: unexpected error: {type(exc).__name__}: {exc}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
Reference in New Issue
Block a user