forked from mtusi2026/mtusi2026lab3
38 lines
1.4 KiB
Python
38 lines
1.4 KiB
Python
"""Concurrency: 100 parallel unique messages survive without loss."""
|
|
from __future__ import annotations
|
|
|
|
import concurrent.futures
|
|
import os
|
|
|
|
|
|
def _register(client, label):
|
|
username = f"s_race_{label}_{os.urandom(4).hex()}"
|
|
password = "T3st-" + os.urandom(8).hex()
|
|
assert client.register(username, password).status == 201
|
|
token = client.login(username, password).json["token"]
|
|
return {"id": client.me(token).json["id"], "token": token}
|
|
|
|
|
|
def test_100_concurrent_messages_are_not_lost(client, alice):
|
|
senders = [_register(client, str(i)) for i in range(10)]
|
|
members = [alice["id"]] + [sender["id"] for sender in senders]
|
|
chat = client.create_chat(alice["token"], members).json
|
|
|
|
def worker(task):
|
|
sender, index = task
|
|
response = client.send(sender["token"], chat["id"], f"race-{index}")
|
|
assert response.status == 201, response.body
|
|
return response.json["id"]
|
|
|
|
tasks = [(senders[index // 10], index) for index in range(100)]
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=25) as pool:
|
|
created = list(pool.map(worker, tasks))
|
|
|
|
assert len(created) == 100
|
|
assert len(set(created)) == 100, "duplicate message ids"
|
|
history = client.list_messages(alice["token"], chat["id"], limit=100).json
|
|
stored = [item["id"] for item in history["items"]]
|
|
assert len(stored) == 100, f"stored {len(stored)} of 100"
|
|
assert len(set(stored)) == 100
|
|
assert set(stored) == set(created)
|