forked from mtusi2026/mtusi2026lab2
104 lines
4.4 KiB
Python
104 lines
4.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Custom test suite for grade 4 criteria: concurrency & corner cases."""
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import json
|
|
import urllib.request
|
|
import urllib.error
|
|
from urllib.parse import quote
|
|
import uuid
|
|
import sys
|
|
from client import Client, check, Failure, run
|
|
|
|
BASE_URL = "http://localhost:8080"
|
|
|
|
def test_corner_cases():
|
|
print("--- 1. Тестирование граничных случаев (Corner cases) ---")
|
|
c = Client(BASE_URL)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
path = f"/api/v1/chats/{chat['id']}"
|
|
|
|
# 1. Дубликат username -> 409
|
|
c.call("POST", "/api/v1/users", 409, body=alice["registration"])
|
|
print("[+] 409 Conflict на дубликат username проверен")
|
|
|
|
# 2. Неверный JSON (malformed) -> 400
|
|
req = urllib.request.Request(
|
|
f"{BASE_URL}/api/v1/users",
|
|
data=b"invalid json syntax {",
|
|
headers={"Content-Type": "application/json", "Accept": "application/json"},
|
|
method="POST"
|
|
)
|
|
try:
|
|
c.opener.open(req)
|
|
raise Failure("Expected 400 on malformed JSON")
|
|
except urllib.error.HTTPError as err:
|
|
check(err.code == 400, f"Expected 400, got {err.code}")
|
|
print("[+] 400 Bad Request на битый JSON проверен")
|
|
|
|
# 3. Пустое / пробельное сообщение -> 400
|
|
c.call("POST", f"{path}/messages", 400, actor=alice, body={"text": " "})
|
|
print("[+] 400 Bad Request на пустое сообщение проверен")
|
|
|
|
# 4. Доступ чужого пользователя к чату -> 404 (не 403)
|
|
c.call("GET", path, 404, actor=eve)
|
|
c.call("GET", f"{path}/messages", 404, actor=eve)
|
|
c.call("POST", f"{path}/messages", 404, actor=eve, body={"text": "Взлом"})
|
|
print("[+] 404 Not Found при попытке доступа постороннего проверен")
|
|
|
|
# 5. Пагинация по нескольким страницам
|
|
for i in range(5):
|
|
c.message(alice, chat, f"Message {i}")
|
|
|
|
page = c.call("GET", f"{path}/messages?limit=2", actor=alice, schema="MessagePage")["json"]
|
|
check(len(page["items"]) == 2 and page["next_cursor"] is not None, "Page 1 failed")
|
|
cursor = page["next_cursor"]
|
|
|
|
page2 = c.call("GET", f"{path}/messages?limit=2&cursor={quote(cursor)}", actor=alice, schema="MessagePage")["json"]
|
|
check(len(page2["items"]) == 2, "Page 2 failed")
|
|
print("[+] Cursor-пагинация проверена")
|
|
|
|
print("PASS: Все граничные тесты пройдены успешно!\n")
|
|
|
|
def test_concurrency():
|
|
print("--- 2. Тестирование защиты от гонок (Concurrency: 100 сообщений от 10 клиентов) ---")
|
|
c = Client(BASE_URL)
|
|
alice, bob, _, chat = c.bootstrap()
|
|
path = f"/api/v1/chats/{chat['id']}/messages"
|
|
|
|
total_messages = 100
|
|
workers_count = 10
|
|
messages_per_worker = total_messages // workers_count
|
|
|
|
def worker_task(worker_id):
|
|
worker_client = Client(BASE_URL, timeout=10)
|
|
actor = alice if worker_id % 2 == 0 else bob
|
|
sent = []
|
|
for i in range(messages_per_worker):
|
|
text = f"Worker {worker_id} - msg {i} - {uuid.uuid4().hex[:6]}"
|
|
res = worker_client.call("POST", path, 201, actor=actor, body={"text": text}, schema="Message")["json"]
|
|
sent.append(res["id"])
|
|
return sent
|
|
|
|
with ThreadPoolExecutor(max_workers=workers_count) as pool:
|
|
results = list(pool.map(worker_task, range(workers_count)))
|
|
|
|
sent_ids = [msg_id for worker_result in results for msg_id in worker_result]
|
|
check(len(sent_ids) == total_messages, f"Expected {total_messages} sent, got {len(sent_ids)}")
|
|
check(len(set(sent_ids)) == total_messages, "Duplicate message IDs detected in responses")
|
|
|
|
# Считываем все сообщения из чата
|
|
read_page = c.call("GET", f"{path}?limit=100", actor=alice, schema="MessagePage")["json"]
|
|
saved_ids = {m["id"] for m in read_page["items"]}
|
|
|
|
# Проверяем, что все отправленные сообщения на месте
|
|
for m_id in sent_ids:
|
|
check(m_id in saved_ids, f"Message {m_id} lost under concurrency!")
|
|
|
|
print(f"PASS: Successfully delivered and verified {total_messages} unique messages under concurrent load.\n")
|
|
|
|
def main():
|
|
test_corner_cases()
|
|
test_concurrency()
|
|
|
|
if __name__ == "__main__":
|
|
run(main) |