forked from mtusi2026/mtusi2026lab3
58 lines
2.5 KiB
Python
58 lines
2.5 KiB
Python
import threading
|
|
import time
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
from common import PASSWORD, call, check, new_chat, new_user, read_history, run_tests, send
|
|
|
|
CLIENTS = 10
|
|
MESSAGES_PER_CLIENT = 10
|
|
REGISTRATIONS = 20
|
|
|
|
|
|
def test_concurrent_messages():
|
|
users = [new_user(f"race{i}") for i in range(CLIENTS)]
|
|
chat = new_chat(*users, title="race")
|
|
barrier = threading.Barrier(CLIENTS) # все клиенты стартуют одновременно
|
|
|
|
def client(index):
|
|
barrier.wait()
|
|
for n in range(MESSAGES_PER_CLIENT):
|
|
send(users[index], chat["id"], f"client-{index}-message-{n}")
|
|
|
|
started = time.monotonic()
|
|
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
|
|
list(pool.map(client, range(CLIENTS))) # list() пробрасывает ошибки из потоков
|
|
elapsed = time.monotonic() - started
|
|
|
|
history, pages = read_history(users[0], chat["id"], limit=30)
|
|
ids = {message["id"] for message in history}
|
|
expected = {f"client-{i}-message-{n}" for i in range(CLIENTS) for n in range(MESSAGES_PER_CLIENT)}
|
|
print(f"sent {CLIENTS * MESSAGES_PER_CLIENT} messages from {CLIENTS} clients in {elapsed:.2f} s; "
|
|
f"read {len(history)} in {pages} pages, unique ids: {len(ids)}")
|
|
check(len(history) == CLIENTS * MESSAGES_PER_CLIENT, "wrong number of messages")
|
|
check(len(ids) == len(history), "duplicate message ids")
|
|
check({message["text"] for message in history} == expected, "lost or changed message texts")
|
|
print("PASS: 100 concurrent messages from 10 clients, no losses and no duplicates")
|
|
|
|
|
|
def test_concurrent_registration():
|
|
username = "race_" + uuid.uuid4().hex[:10]
|
|
barrier = threading.Barrier(REGISTRATIONS)
|
|
|
|
def register(index):
|
|
barrier.wait()
|
|
body = {"username": username, "display_name": f"Client {index}", "password": PASSWORD}
|
|
return call("POST", "/api/v1/users", (201, 409), body=body).status
|
|
|
|
with ThreadPoolExecutor(max_workers=REGISTRATIONS) as pool:
|
|
statuses = list(pool.map(register, range(REGISTRATIONS)))
|
|
created, conflicts = statuses.count(201), statuses.count(409)
|
|
print(f"{REGISTRATIONS} parallel registrations of one username: 201 x{created}, 409 x{conflicts}")
|
|
check(created == 1 and conflicts == REGISTRATIONS - 1, "exactly one registration must win")
|
|
print("PASS: concurrent registration created exactly one user")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run_tests([test_concurrent_messages, test_concurrent_registration])
|