Files
mtusi2026lab2/tests/test_concurrency.py
T

133 lines
4.8 KiB
Python

"""Конкурентность на реальной БД: гонка регистрации и параллельная запись."""
import asyncio
from collections import Counter
from uuid import uuid4
import httpx
from fastapi.testclient import TestClient
from app.main import create_app
from tests.helpers import PASSWORD, bearer, create_chat, create_user
def test_parallel_registration_of_same_username_creates_exactly_one_user(make_settings):
"""Источник истины для уникальности — UNIQUE в БД, а не проверка «SELECT, потом INSERT»."""
app = create_app(make_settings(max_in_flight=64, db_pool_size=20, db_max_overflow=20))
async def scenario() -> list[int]:
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://testserver",
timeout=30,
) as client:
responses = await asyncio.gather(
*(
client.post(
"/api/v1/users",
json={
"username": "race_user",
"display_name": "Race",
"password": PASSWORD,
},
)
for _ in range(16)
)
)
return [response.status_code for response in responses]
statuses = Counter(asyncio.run(scenario()))
assert statuses == Counter({201: 1, 409: 15}), statuses # ни одного 500
def test_100_messages_from_10_clients(make_settings):
app = create_app(
make_settings(
max_messages=1000, max_in_flight=100, db_pool_size=20, db_max_overflow=20
)
)
with TestClient(app) as setup:
users = [create_user(setup, username=f"load_{i}_{uuid4().hex[:6]}") for i in range(10)]
chat = setup.post(
"/api/v1/chats",
headers=bearer(users[0]),
json={"title": "Concurrency", "member_ids": [u["id"] for u in users]},
).json()
async def scenario() -> None:
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://testserver",
timeout=30,
) as client:
async def worker(index: int, user: dict) -> list[dict]:
responses = await asyncio.gather(
*(
client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers=bearer(user),
json={"text": f"client-{index}-message-{n}"},
)
for n in range(10)
)
)
assert all(r.status_code == 201 for r in responses), [
r.text for r in responses if r.status_code != 201
]
return [r.json() for r in responses]
results = await asyncio.gather(*(worker(i, u) for i, u in enumerate(users)))
messages = [m for batch in results for m in batch]
assert len(messages) == 100
assert len({m["id"] for m in messages}) == 100
assert Counter(m["sender_id"] for m in messages) == Counter(
{u["id"]: 10 for u in users}
)
history = await client.get(
f"/api/v1/chats/{chat['id']}/messages?limit=100", headers=bearer(users[0])
)
items = history.json()["items"]
assert len(items) == 100
assert len({m["id"] for m in items}) == 100
asyncio.run(scenario())
def test_chat_creation_in_parallel_is_atomic(make_settings, db_engine):
from sqlalchemy import text
app = create_app(make_settings(max_in_flight=32, db_pool_size=20, db_max_overflow=20))
with TestClient(app) as setup:
alice = create_user(setup)
bob = create_user(setup)
async def scenario() -> None:
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://testserver",
timeout=30,
) as client:
responses = await asyncio.gather(
*(
client.post(
"/api/v1/chats",
headers=bearer(alice),
json={"title": f"c{i}", "member_ids": [alice["id"], bob["id"]]},
)
for i in range(10)
)
)
assert all(r.status_code == 201 for r in responses)
asyncio.run(scenario())
with db_engine.connect() as connection:
chats = connection.execute(text("SELECT count(*) FROM chats")).scalar_one()
members = connection.execute(text("SELECT count(*) FROM chat_members")).scalar_one()
assert chats == 10 and members == 20