Files
2026-10-16 19:49:48 +03:00

37 lines
1.5 KiB
Python

"""Гонки (перенесено из lab1 + гонка регистрации одинакового username, требуемая уровнем 4)."""
import json
import threading
import uuid
from concurrent.futures import ThreadPoolExecutor
from test_own import PASSWORD, make_user, request
def test_concurrent_writes():
u = make_user("race")
_, b = request("POST", "/api/v1/chats", {"title": "R", "member_ids": [u["id"]]}, u["auth"])
chat = json.loads(b)
def worker(cid):
for i in range(10):
request("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": f"c{cid}-m{i}"}, u["auth"])
threads = [threading.Thread(target=worker, args=(i,)) for i in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
_, b = request("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", None, u["auth"])
d = json.loads(b)
assert len(d["items"]) == 100, len(d["items"])
assert len({m["id"] for m in d["items"]}) == 100
def test_concurrent_registration_same_username():
"""16 одновременных регистраций одного username: ровно одна успешна, остальные — 409 (решает UNIQUE в БД)."""
body = {"username": "race_" + uuid.uuid4().hex[:12], "display_name": "R", "password": PASSWORD}
with ThreadPoolExecutor(max_workers=16) as pool:
codes = list(pool.map(lambda _: request("POST", "/api/v1/users", body)[0], range(16)))
assert codes.count(201) == 1 and codes.count(409) == 15, codes