forked from mtusi2026/mtusi2026lab2
334 lines
12 KiB
Python
334 lines
12 KiB
Python
#!/usr/bin/env python3
|
||
"""Собственные тесты студента для lab1: негативные сценарии и конкурентность."""
|
||
import base64
|
||
import concurrent.futures
|
||
import json
|
||
import urllib.error
|
||
import urllib.parse
|
||
import urllib.request
|
||
import uuid
|
||
|
||
BASE_URL = "http://localhost:8080"
|
||
|
||
|
||
def request(method, path, body=None, headers=None, expected=200):
|
||
"""Выполнить HTTP-запрос и проверить статус ответа."""
|
||
h = {"Accept": "application/json"}
|
||
if body is not None:
|
||
raw = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||
h["Content-Type"] = "application/json"
|
||
else:
|
||
raw = None
|
||
h.update(headers or {})
|
||
req = urllib.request.Request(BASE_URL + path, data=raw, headers=h, method=method)
|
||
try:
|
||
resp = urllib.request.urlopen(req)
|
||
except urllib.error.HTTPError as e:
|
||
resp = e
|
||
if resp.code != expected:
|
||
data = resp.read().decode()
|
||
raise AssertionError(
|
||
f"{method} {path}: ожидался {expected}, получен {resp.code}: {data}"
|
||
)
|
||
data = resp.read()
|
||
return json.loads(data.decode()) if data else None
|
||
|
||
|
||
def test_invalid_json():
|
||
"""Некорректный JSON должен возвращать 400."""
|
||
req = urllib.request.Request(
|
||
BASE_URL + "/api/v1/users",
|
||
data=b"{not json",
|
||
headers={"Content-Type": "application/json"},
|
||
method="POST",
|
||
)
|
||
try:
|
||
urllib.request.urlopen(req)
|
||
raise AssertionError("ожидалась ошибка 400")
|
||
except urllib.error.HTTPError as e:
|
||
assert e.code == 400, f"ожидался 400, получен {e.code}"
|
||
data = json.loads(e.read().decode())
|
||
assert data["error"]["code"] == "invalid_request"
|
||
print("PASS: invalid_json")
|
||
|
||
|
||
def test_empty_message():
|
||
"""Пустой или пробельный текст сообщения должен возвращать 400."""
|
||
alice = request("POST", "/api/v1/users", body={"username": "u_alice_" + uuid.uuid4().hex[:12], "display_name": "Alice"}, expected=201)
|
||
bob = request("POST", "/api/v1/users", body={"username": "u_bob_" + uuid.uuid4().hex[:12], "display_name": "Bob"}, expected=201)
|
||
chat = request(
|
||
"POST",
|
||
"/api/v1/chats",
|
||
body={"title": "Test", "member_ids": [alice["id"], bob["id"]]},
|
||
headers={"X-User-Id": alice["id"]},
|
||
expected=201,
|
||
)
|
||
|
||
for text in ["", " ", "\t\n"]:
|
||
req = urllib.request.Request(
|
||
BASE_URL + f"/api/v1/chats/{chat['id']}/messages",
|
||
data=json.dumps({"text": text}).encode(),
|
||
headers={"Content-Type": "application/json", "X-User-Id": alice["id"]},
|
||
method="POST",
|
||
)
|
||
try:
|
||
urllib.request.urlopen(req)
|
||
raise AssertionError(f"ожидалась ошибка 400 для текста {repr(text)}")
|
||
except urllib.error.HTTPError as e:
|
||
assert e.code == 400, f"ожидался 400, получен {e.code}"
|
||
print("PASS: empty_message")
|
||
|
||
|
||
def test_duplicate_username():
|
||
"""Дублирующийся username должен возвращать 409."""
|
||
username = "u_dup_" + uuid.uuid4().hex[:12]
|
||
request(
|
||
"POST",
|
||
"/api/v1/users",
|
||
body={"username": username, "display_name": "First"},
|
||
expected=201,
|
||
)
|
||
req = urllib.request.Request(
|
||
BASE_URL + "/api/v1/users",
|
||
data=json.dumps({"username": username, "display_name": "Second"}).encode(),
|
||
headers={"Content-Type": "application/json"},
|
||
method="POST",
|
||
)
|
||
try:
|
||
urllib.request.urlopen(req)
|
||
raise AssertionError("ожидалась ошибка 409")
|
||
except urllib.error.HTTPError as e:
|
||
assert e.code == 409, f"ожидался 409, получен {e.code}"
|
||
print("PASS: duplicate_username")
|
||
|
||
|
||
def test_extra_fields_rejected():
|
||
"""Лишние JSON-поля в пользователе, чате и сообщении должны возвращать 400."""
|
||
request(
|
||
"POST",
|
||
"/api/v1/users",
|
||
body={"username": "u_extra_" + uuid.uuid4().hex[:12], "display_name": "Extra", "role": "admin"},
|
||
expected=400,
|
||
)
|
||
|
||
alice = request("POST", "/api/v1/users", body={"username": "u_alice_" + uuid.uuid4().hex[:12], "display_name": "Alice"}, expected=201)
|
||
bob = request("POST", "/api/v1/users", body={"username": "u_bob_" + uuid.uuid4().hex[:12], "display_name": "Bob"}, expected=201)
|
||
|
||
request(
|
||
"POST",
|
||
"/api/v1/chats",
|
||
body={"title": "Extra", "member_ids": [alice["id"], bob["id"]], "owner_id": alice["id"]},
|
||
headers={"X-User-Id": alice["id"]},
|
||
expected=400,
|
||
)
|
||
|
||
chat = request(
|
||
"POST",
|
||
"/api/v1/chats",
|
||
body={"title": "Strict", "member_ids": [alice["id"], bob["id"]]},
|
||
headers={"X-User-Id": alice["id"]},
|
||
expected=201,
|
||
)
|
||
request(
|
||
"POST",
|
||
f"/api/v1/chats/{chat['id']}/messages",
|
||
body={"text": "hello", "sender_id": bob["id"]},
|
||
headers={"X-User-Id": alice["id"]},
|
||
expected=400,
|
||
)
|
||
print("PASS: extra_fields_rejected")
|
||
|
||
|
||
def test_foreign_chat():
|
||
"""Посторонний пользователь не должен иметь доступ к чужому чату (404)."""
|
||
alice = request("POST", "/api/v1/users", body={"username": "u_alice_" + uuid.uuid4().hex[:12], "display_name": "Alice"}, expected=201)
|
||
bob = request("POST", "/api/v1/users", body={"username": "u_bob_" + uuid.uuid4().hex[:12], "display_name": "Bob"}, expected=201)
|
||
eve = request("POST", "/api/v1/users", body={"username": "u_eve_" + uuid.uuid4().hex[:12], "display_name": "Eve"}, expected=201)
|
||
chat = request(
|
||
"POST",
|
||
"/api/v1/chats",
|
||
body={"title": "Secret", "member_ids": [alice["id"], bob["id"]]},
|
||
headers={"X-User-Id": alice["id"]},
|
||
expected=201,
|
||
)
|
||
|
||
# Eve не может прочитать чат
|
||
req = urllib.request.Request(
|
||
BASE_URL + f"/api/v1/chats/{chat['id']}",
|
||
headers={"X-User-Id": eve["id"]},
|
||
method="GET",
|
||
)
|
||
try:
|
||
urllib.request.urlopen(req)
|
||
raise AssertionError("ожидалась ошибка 404")
|
||
except urllib.error.HTTPError as e:
|
||
assert e.code == 404, f"ожидался 404, получен {e.code}"
|
||
print("PASS: foreign_chat")
|
||
|
||
|
||
def test_pagination():
|
||
"""Курсорная пагинация не должна пропускать или дублировать сообщения."""
|
||
alice = request("POST", "/api/v1/users", body={"username": "u_alice_" + uuid.uuid4().hex[:12], "display_name": "Alice"}, expected=201)
|
||
bob = request("POST", "/api/v1/users", body={"username": "u_bob_" + uuid.uuid4().hex[:12], "display_name": "Bob"}, expected=201)
|
||
chat = request(
|
||
"POST",
|
||
"/api/v1/chats",
|
||
body={"title": "Pages", "member_ids": [alice["id"], bob["id"]]},
|
||
headers={"X-User-Id": alice["id"]},
|
||
expected=201,
|
||
)
|
||
|
||
texts = [f"msg{i}" for i in range(5)]
|
||
for t in texts:
|
||
request(
|
||
"POST",
|
||
f"/api/v1/chats/{chat['id']}/messages",
|
||
body={"text": t},
|
||
headers={"X-User-Id": alice["id"]},
|
||
expected=201,
|
||
)
|
||
|
||
all_ids = []
|
||
cursor = None
|
||
while True:
|
||
url = f"/api/v1/chats/{chat['id']}/messages?limit=2"
|
||
if cursor:
|
||
url += f"&cursor={cursor}"
|
||
page = request("GET", url, headers={"X-User-Id": alice["id"]})
|
||
all_ids.extend([m["id"] for m in page["items"]])
|
||
cursor = page.get("next_cursor")
|
||
if cursor is None:
|
||
break
|
||
|
||
assert len(all_ids) == 5, f"ожидалось 5 сообщений, получено {len(all_ids)}"
|
||
assert len(set(all_ids)) == 5, "обнаружены дублирующиеся сообщения в пагинации"
|
||
print("PASS: pagination")
|
||
|
||
|
||
def test_cursor_validation():
|
||
"""Курсор должен быть непустым, корректным и привязанным к своему чату."""
|
||
alice = request("POST", "/api/v1/users", body={"username": "u_alice_" + uuid.uuid4().hex[:12], "display_name": "Alice"}, expected=201)
|
||
bob = request("POST", "/api/v1/users", body={"username": "u_bob_" + uuid.uuid4().hex[:12], "display_name": "Bob"}, expected=201)
|
||
chat1 = request(
|
||
"POST",
|
||
"/api/v1/chats",
|
||
body={"title": "Cursor1", "member_ids": [alice["id"], bob["id"]]},
|
||
headers={"X-User-Id": alice["id"]},
|
||
expected=201,
|
||
)
|
||
chat2 = request(
|
||
"POST",
|
||
"/api/v1/chats",
|
||
body={"title": "Cursor2", "member_ids": [alice["id"], bob["id"]]},
|
||
headers={"X-User-Id": alice["id"]},
|
||
expected=201,
|
||
)
|
||
|
||
for text in ["first", "second"]:
|
||
request(
|
||
"POST",
|
||
f"/api/v1/chats/{chat1['id']}/messages",
|
||
body={"text": text},
|
||
headers={"X-User-Id": alice["id"]},
|
||
expected=201,
|
||
)
|
||
|
||
page = request(
|
||
"GET",
|
||
f"/api/v1/chats/{chat1['id']}/messages?limit=1",
|
||
headers={"X-User-Id": alice["id"]},
|
||
)
|
||
cursor = page["next_cursor"]
|
||
quoted_cursor = urllib.parse.quote(cursor, safe="")
|
||
|
||
request(
|
||
"GET",
|
||
f"/api/v1/chats/{chat2['id']}/messages?cursor={quoted_cursor}",
|
||
headers={"X-User-Id": alice["id"]},
|
||
expected=400,
|
||
)
|
||
|
||
bad_content_cursor = base64.urlsafe_b64encode(b"{}").decode("ascii")
|
||
for bad_cursor in ["", "not-base64", "abcd", bad_content_cursor]:
|
||
request(
|
||
"GET",
|
||
f"/api/v1/chats/{chat1['id']}/messages?cursor={urllib.parse.quote(bad_cursor, safe='')}",
|
||
headers={"X-User-Id": alice["id"]},
|
||
expected=400,
|
||
)
|
||
|
||
print("PASS: cursor_validation")
|
||
|
||
|
||
def test_invalid_chat_uuid():
|
||
"""Некорректный UUID чата должен давать 400, а не 404."""
|
||
alice = request("POST", "/api/v1/users", body={"username": "u_alice_" + uuid.uuid4().hex[:12], "display_name": "Alice"}, expected=201)
|
||
headers = {"X-User-Id": alice["id"]}
|
||
|
||
request("GET", "/api/v1/chats/not-a-uuid", headers=headers, expected=400)
|
||
request("GET", "/api/v1/chats/not-a-uuid/messages", headers=headers, expected=400)
|
||
request(
|
||
"POST",
|
||
"/api/v1/chats/not-a-uuid/messages",
|
||
body={"text": "hello"},
|
||
headers=headers,
|
||
expected=400,
|
||
)
|
||
print("PASS: invalid_chat_uuid")
|
||
|
||
|
||
def test_concurrent_messages():
|
||
"""Конкурентная отправка: 100 сообщений от 10 клиентов, все должны быть уникальны."""
|
||
alice = request("POST", "/api/v1/users", body={"username": "u_alice_" + uuid.uuid4().hex[:12], "display_name": "Alice"}, expected=201)
|
||
bob = request("POST", "/api/v1/users", body={"username": "u_bob_" + uuid.uuid4().hex[:12], "display_name": "Bob"}, expected=201)
|
||
chat = request(
|
||
"POST",
|
||
"/api/v1/chats",
|
||
body={"title": "Concurrent", "member_ids": [alice["id"], bob["id"]]},
|
||
headers={"X-User-Id": alice["id"]},
|
||
expected=201,
|
||
)
|
||
|
||
def send(i):
|
||
actor = alice if i % 2 == 0 else bob
|
||
return request(
|
||
"POST",
|
||
f"/api/v1/chats/{chat['id']}/messages",
|
||
body={"text": f"message {i}"},
|
||
headers={"X-User-Id": actor["id"]},
|
||
expected=201,
|
||
)
|
||
|
||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as ex:
|
||
futures = [ex.submit(send, i) for i in range(100)]
|
||
results = [f.result() for f in concurrent.futures.as_completed(futures)]
|
||
|
||
msg_ids = [r["id"] for r in results]
|
||
assert len(set(msg_ids)) == 100, f"ожидалось 100 уникальных сообщений, получено {len(set(msg_ids))}"
|
||
|
||
# Проверяем, что все 100 сообщений доступны для чтения
|
||
page = request(
|
||
"GET",
|
||
f"/api/v1/chats/{chat['id']}/messages?limit=100",
|
||
headers={"X-User-Id": alice["id"]},
|
||
)
|
||
assert len(page["items"]) == 100, f"ожидалось 100 элементов, получено {len(page['items'])}"
|
||
print("PASS: concurrent_messages (100 уникальных сообщений от 10 потоков)")
|
||
|
||
|
||
def main():
|
||
test_invalid_json()
|
||
test_empty_message()
|
||
test_duplicate_username()
|
||
test_extra_fields_rejected()
|
||
test_foreign_chat()
|
||
test_pagination()
|
||
test_cursor_validation()
|
||
test_invalid_chat_uuid()
|
||
test_concurrent_messages()
|
||
print("\n=== ВСЕ СОБСТВЕННЫЕ ТЕСТЫ ПРОЙДЕНЫ ===")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|