Files
mtusi2026lab2/student-tests/test_race.py
T

139 lines
5.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Гонки (уровень 4): одновременные запросы по отдельным соединениям.
- 100 сообщений от 10 клиентов → ровно 100 уникальных в истории
(лаба 1, сохраняется);
- 10 одновременных регистраций одного username → одна 201, девять 409:
уникальность держит индекс PostgreSQL, а не проверка «сначала SELECT».
Параллельность настоящая: 10 потоков стартуют одновременно за
`threading.Barrier`, у каждого свой клиент и своё соединение, открытое
до барьера. Тест требует, чтобы хотя бы 2 запроса были в полёте
одновременно, иначе гонка не доказана.
"""
import threading
from collections import Counter
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
import httpx
from helpers import (
USERS,
ClientFactory,
assert_error,
create_chat,
read_history,
register,
send,
unique_password,
unique_username,
)
CLIENTS = 10
MESSAGES_PER_CLIENT = 10
class InFlight:
"""Сколько запросов одновременно в полёте — максимум за прогон."""
def __init__(self) -> None:
self._lock = threading.Lock()
self.current = 0
self.peak = 0
def __enter__(self) -> None:
with self._lock:
self.current += 1
self.peak = max(self.peak, self.current)
def __exit__(self, *_exc: object) -> None:
with self._lock:
self.current -= 1
def run_together[T](
clients: list[httpx.Client],
work: Callable[[int, httpx.Client], T],
) -> list[T]:
"""Каждый клиент в своём потоке; старт — одновременно, за барьером."""
barrier = threading.Barrier(len(clients))
def worker(index: int) -> T:
own = clients[index]
# соединение открыто до барьера: после него сразу запросы
own.get("/health/live")
barrier.wait()
return work(index, own)
with ThreadPoolExecutor(max_workers=len(clients)) as pool:
return list(pool.map(worker, range(len(clients))))
def test_100_messages_from_10_clients(
client: httpx.Client,
new_client: ClientFactory,
) -> None:
users = [register(client, f"racer{index}") for index in range(CLIENTS)]
chat = create_chat(client, *users, title="Гонка")
in_flight = InFlight()
def send_all(index: int, own: httpx.Client) -> list[tuple[int, str, str]]:
results = []
for number in range(MESSAGES_PER_CLIENT):
text = f"client {index} message {number}"
with in_flight:
response = send(own, users[index], chat, text)
message_id = response.json().get("id", "") if response.is_success else ""
results.append((response.status_code, text, message_id))
return results
rows = run_together([new_client() for _ in range(CLIENTS)], send_all)
results = [row for group in rows for row in group]
statuses = Counter(status for status, _, _ in results)
items, sizes = read_history(client, users[0], chat, limit=30)
ids = [item["id"] for item in items]
keys = [(item["created_at"], item["id"]) for item in items]
print(
f"statuses={dict(statuses)} peak_in_flight={in_flight.peak} "
f"history={len(items)} unique_ids={len(set(ids))} pages={sizes}",
)
assert statuses == {201: CLIENTS * MESSAGES_PER_CLIENT}
assert in_flight.peak >= 2, "requests never overlapped: race is not proven"
assert len(items) == CLIENTS * MESSAGES_PER_CLIENT
assert len(set(ids)) == len(ids)
assert keys == sorted(keys)
# в истории ровно то, что подтвердил сервер, и тексты не перепутаны
assert {(item["id"], item["text"]) for item in items} == {
(message_id, text) for _, text, message_id in results
}
assert {item["sender_id"] for item in items} == {user["id"] for user in users}
def test_parallel_registration_of_one_username(new_client: ClientFactory) -> None:
username = unique_username("same")
in_flight = InFlight()
def register_same(_index: int, own: httpx.Client) -> httpx.Response:
body = {
"username": username,
"display_name": "Двойник",
"password": unique_password(),
}
with in_flight:
return own.post(USERS, json=body)
responses = run_together([new_client() for _ in range(CLIENTS)], register_same)
statuses = Counter(response.status_code for response in responses)
print(f"statuses={dict(statuses)} peak_in_flight={in_flight.peak}")
assert in_flight.peak >= 2, "requests never overlapped: race is not proven"
assert statuses == {201: 1, 409: CLIENTS - 1}
for response in responses:
if response.status_code == 409:
assert_error(response, 409, "conflict")
else:
assert response.json()["username"] == username