70 lines
2.7 KiB
Python
70 lines
2.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Конкурентный тест: 100 сообщений от 10 клиентов -> ровно 100 уникальных.
|
|
Проверяет защиту in-memory структур от гонок (RLock)."""
|
|
import sys
|
|
import threading
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
|
from client import Client, arguments, check, run # noqa: E402
|
|
|
|
TOTAL_MESSAGES = 100
|
|
CLIENTS = 10
|
|
|
|
|
|
def main():
|
|
args = arguments("Lab1 concurrency safety")
|
|
c = Client(args.base_url, args.ca_file)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
path = "/api/v1/chats/" + chat["id"]
|
|
|
|
# Каждый «клиент» — свой actor (alice/bob) для реалистичной конкуренции
|
|
actors = [alice, bob]
|
|
barrier = threading.Barrier(CLIENTS)
|
|
|
|
def worker(worker_id):
|
|
local = Client(args.base_url, args.ca_file, timeout=15)
|
|
actor = actors[worker_id % len(actors)]
|
|
barrier.wait() # синхронный старт всех потоков
|
|
produced = []
|
|
for i in range(TOTAL_MESSAGES // CLIENTS):
|
|
text = "c-%02d-%02d-%s" % (worker_id, i, uuid.uuid4().hex[:8])
|
|
msg = local.message(actor, chat, text)["json"]
|
|
produced.append(msg)
|
|
return produced
|
|
|
|
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
|
|
results = list(pool.map(worker, range(CLIENTS)))
|
|
|
|
all_ids = [m["id"] for chunk in results for m in chunk]
|
|
check(len(all_ids) == TOTAL_MESSAGES,
|
|
"expected %d message ids, got %d" % (TOTAL_MESSAGES, len(all_ids)))
|
|
check(len(set(all_ids)) == TOTAL_MESSAGES,
|
|
"duplicate message ids under concurrency: %d unique" % len(set(all_ids)))
|
|
|
|
# Читаем всю историю через пагинацию
|
|
collected = []
|
|
cursor = None
|
|
from urllib.parse import quote
|
|
for _ in range(50):
|
|
q = path + "/messages?limit=100"
|
|
if cursor:
|
|
q += "&cursor=" + quote(cursor, safe="")
|
|
page = c.call("GET", q, actor=alice, schema="MessagePage")["json"]
|
|
collected.extend(m["id"] for m in page["items"])
|
|
cursor = page["next_cursor"]
|
|
if cursor is None:
|
|
break
|
|
check(len(collected) == TOTAL_MESSAGES,
|
|
"stored messages: %d, expected %d" % (len(collected), TOTAL_MESSAGES))
|
|
check(len(set(collected)) == TOTAL_MESSAGES,
|
|
"stored messages contain duplicates: %d unique" % len(set(collected)))
|
|
|
|
print("PASS: lab1 concurrency: %d messages from %d clients, "
|
|
"%d unique stored and readable" % (TOTAL_MESSAGES, CLIENTS, len(set(collected))))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run(main) |