Реализовать lab2: PostgreSQL и постоянные Bearer-сессии
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,164 @@
|
||||
"""Adapted from Karpova lab1 archive: password + Basic/Bearer transition only."""
|
||||
"""Student tests for MTUSI Lab1 level 4 requirements."""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import quote
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
||||
|
||||
|
||||
def call(method, path, *, body=None, actor=None, raw=None, content_type=None):
|
||||
headers = {"Accept": "application/json"}
|
||||
if actor:
|
||||
headers["Authorization"] = "Bearer " + actor["token"]
|
||||
if body is not None:
|
||||
raw = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
content_type = "application/json"
|
||||
if content_type:
|
||||
headers["Content-Type"] = content_type
|
||||
req = Request(BASE_URL + path, data=raw, headers=headers, method=method)
|
||||
try:
|
||||
response = urlopen(req, timeout=5)
|
||||
status = response.status
|
||||
data = response.read()
|
||||
headers = response.headers
|
||||
except HTTPError as error:
|
||||
status = error.code
|
||||
data = error.read()
|
||||
headers = error.headers
|
||||
payload = None
|
||||
if headers.get_content_type() == "application/json" and data:
|
||||
payload = json.loads(data)
|
||||
return status, headers, payload
|
||||
|
||||
|
||||
def expect(status, actual, label):
|
||||
assert actual == status, f"{label}: expected {status}, got {actual}"
|
||||
|
||||
|
||||
def create_user(label, username=None):
|
||||
username = username or ("t_" + label + "_" + uuid.uuid4().hex[:10])
|
||||
status, headers, payload = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
body={"username": username, "display_name": "Тест " + label, "password": "Synthetic-lab1-port-123"},
|
||||
)
|
||||
expect(201, status, "create user")
|
||||
basic = base64.b64encode((payload['username']+':Synthetic-lab1-port-123').encode()).decode()
|
||||
req = Request(BASE_URL+'/api/v1/auth/sessions', method='POST', headers={'Authorization':'Basic '+basic})
|
||||
with urlopen(req, timeout=10) as response:
|
||||
payload['token'] = json.load(response)['token']
|
||||
return payload
|
||||
|
||||
|
||||
def main():
|
||||
# 1) malformed JSON must be 400, not FastAPI's default 422.
|
||||
status, headers, payload = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
raw=b'{"username":',
|
||||
content_type="application/json",
|
||||
)
|
||||
expect(400, status, "malformed JSON")
|
||||
assert payload["error"]["code"] == "invalid_request"
|
||||
assert headers.get("X-Request-Id") == payload["error"]["request_id"]
|
||||
|
||||
# 2) Duplicate username must be 409.
|
||||
username = "dup_" + uuid.uuid4().hex[:8]
|
||||
create_user("one", username=username)
|
||||
status, _, payload = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
body={"username": username, "display_name": "Дубликат", "password": "Synthetic-lab1-port-123"},
|
||||
)
|
||||
expect(409, status, "duplicate username")
|
||||
assert payload["error"]["code"] == "conflict"
|
||||
|
||||
alice = create_user("alice")
|
||||
bob = create_user("bob")
|
||||
eve = create_user("eve")
|
||||
|
||||
# 3) Create a private chat for Alice + Bob. Eve must not see it.
|
||||
status, _, chat = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
actor=alice,
|
||||
body={"title": "Private test", "member_ids": [alice["id"], bob["id"]]},
|
||||
)
|
||||
expect(201, status, "create chat")
|
||||
|
||||
status, _, _ = call("GET", f"/api/v1/chats/{chat['id']}", actor=eve)
|
||||
expect(404, status, "outsider chat access")
|
||||
|
||||
# 4) Blank message must be 400.
|
||||
status, _, payload = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
actor=alice,
|
||||
body={"text": " "},
|
||||
)
|
||||
expect(400, status, "blank message")
|
||||
assert payload["error"]["code"] == "invalid_request"
|
||||
|
||||
# 5) Send 3 messages and walk multiple pages using cursor.
|
||||
message_ids = []
|
||||
for i in range(3):
|
||||
status, _, message = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
actor=alice if i % 2 == 0 else bob,
|
||||
body={"text": f"page-{i} Привет 👋"},
|
||||
)
|
||||
expect(201, status, "create message")
|
||||
message_ids.append(message["id"])
|
||||
|
||||
seen = []
|
||||
cursor = None
|
||||
while True:
|
||||
path = f"/api/v1/chats/{chat['id']}/messages?limit=1"
|
||||
if cursor:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
status, _, payload = call("GET", path, actor=bob)
|
||||
expect(200, status, "message page")
|
||||
seen.extend(x["id"] for x in payload["items"])
|
||||
cursor = payload["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
|
||||
assert len(seen) == 3, f"pagination returned {len(seen)} messages"
|
||||
assert len(set(seen)) == 3, "pagination duplicated a message"
|
||||
assert set(seen) == set(message_ids), "pagination lost a message"
|
||||
|
||||
# A messages cursor from another resource is invalid.
|
||||
status, _, payload = call("GET", "/api/v1/chats?limit=1", actor=bob)
|
||||
expect(200, status, "chat list")
|
||||
bad_cursor = payload["next_cursor"]
|
||||
if bad_cursor is None:
|
||||
# Create enough chats to get a cursor.
|
||||
for i in range(2):
|
||||
call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
actor=bob,
|
||||
body={"title": f"Extra {i}", "member_ids": [bob["id"]]},
|
||||
)
|
||||
status, _, payload = call("GET", "/api/v1/chats?limit=1", actor=bob)
|
||||
expect(200, status, "chat list second try")
|
||||
bad_cursor = payload["next_cursor"]
|
||||
status, _, err = call(
|
||||
"GET",
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=1&cursor={quote(bad_cursor, safe='')}",
|
||||
actor=bob,
|
||||
)
|
||||
expect(400, status, "cursor from another resource")
|
||||
assert err["error"]["code"] == "invalid_request"
|
||||
|
||||
print("PASS: own negative, access-control and multi-page tests")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user