forked from mtusi2026/mtusi2026lab4
Реализация лабораторной работы 4 на 4
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
"""Защита состояния от гонок: 100 сообщений от 10 параллельных клиентов"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from helpers import auth, message_headers, read_all_messages
|
||||
|
||||
CLIENTS = 10
|
||||
MESSAGES_PER_CLIENT = 10
|
||||
TOTAL_MESSAGES = CLIENTS * MESSAGES_PER_CLIENT
|
||||
PAGE_LIMIT = 30
|
||||
|
||||
|
||||
async def _send_concurrently(
|
||||
base_url: str, chat_id: str, users: list[dict]
|
||||
) -> list[int]:
|
||||
"""Каждый клиент — отдельный пользователь и пул соединений; старт по сигналу"""
|
||||
start = asyncio.Event()
|
||||
|
||||
async def client_worker(user: dict) -> list[int]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=base_url, headers=auth(user), timeout=30
|
||||
) as client:
|
||||
await start.wait()
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
json={"text": f"{user['username']}#{n}"},
|
||||
headers=message_headers(user),
|
||||
)
|
||||
for n in range(MESSAGES_PER_CLIENT)
|
||||
)
|
||||
)
|
||||
return [response.status_code for response in responses]
|
||||
|
||||
workers = [asyncio.create_task(client_worker(user)) for user in users]
|
||||
await asyncio.sleep(0)
|
||||
start.set()
|
||||
results = await asyncio.gather(*workers)
|
||||
return [status for statuses in results for status in statuses]
|
||||
|
||||
|
||||
def test_parallel_messages_are_not_lost_or_duplicated(
|
||||
api: httpx.Client, base_url: str, make_user, make_chat
|
||||
) -> None:
|
||||
users = [make_user(f"c{n}") for n in range(CLIENTS)]
|
||||
chat = make_chat(users[0], users)
|
||||
|
||||
started = time.perf_counter()
|
||||
statuses = asyncio.run(_send_concurrently(base_url, chat["id"], users))
|
||||
elapsed = time.perf_counter() - started
|
||||
|
||||
items, pages = read_all_messages(api, users[-1], chat["id"], PAGE_LIMIT)
|
||||
expected_texts = {
|
||||
f"{user['username']}#{n}" for user in users for n in range(MESSAGES_PER_CLIENT)
|
||||
}
|
||||
summary = {
|
||||
"clients": CLIENTS,
|
||||
"messages_sent": len(statuses),
|
||||
"status_201": statuses.count(201),
|
||||
"messages_read": len(items),
|
||||
"unique_ids": len({item["id"] for item in items}),
|
||||
"unique_texts": len({item["text"] for item in items}),
|
||||
"pages_read": pages,
|
||||
"send_seconds": round(elapsed, 3),
|
||||
}
|
||||
print("\nCONCURRENCY RESULT:", json.dumps(summary, ensure_ascii=False))
|
||||
|
||||
assert statuses == [201] * TOTAL_MESSAGES
|
||||
assert len(items) == TOTAL_MESSAGES
|
||||
assert summary["unique_ids"] == TOTAL_MESSAGES
|
||||
assert {item["text"] for item in items} == expected_texts
|
||||
keys = [(item["created_at"], item["id"]) for item in items]
|
||||
assert keys == sorted(keys)
|
||||
assert len(set(keys)) == TOTAL_MESSAGES
|
||||
Reference in New Issue
Block a user