Files
mtusi2026lab2/tests/test_concurrency.py
T
2026-10-23 00:20:58 +03:00

115 lines
4.0 KiB
Python

"""Конкурентность на реальной БД: гонка регистрации и параллельная запись."""
import asyncio
from collections import Counter
from uuid import uuid4
from sqlalchemy import text
from app.main import create_app
from tests.conftest import make_client
from tests.helpers import PASSWORD, bearer, create_user
async def test_parallel_registration_of_same_username_creates_exactly_one_user(make_settings):
app = create_app(make_settings(max_in_flight=64, db_pool_size=20, db_max_overflow=20))
async with make_client(app) as client:
responses = await asyncio.gather(
*(
client.post(
"/api/v1/users",
json={
"username": "race_user",
"display_name": "Race",
"password": PASSWORD,
},
)
for _ in range(16)
)
)
await app.state.engine.dispose()
statuses = Counter(response.status_code for response in responses)
assert statuses == Counter({201: 1, 409: 15}), statuses
async 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
)
)
async with make_client(app) as client:
users = [
await create_user(client, username=f"load_{i}_{uuid4().hex[:6]}")
for i in range(10)
]
created = await client.post(
"/api/v1/chats",
headers=bearer(users[0]),
json={"title": "Concurrency", "member_ids": [u["id"] for u in users]},
)
chat = created.json()
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
await app.state.engine.dispose()
async def test_chat_creation_in_parallel_is_atomic(make_settings, db_engine):
app = create_app(make_settings(max_in_flight=32, db_pool_size=20, db_max_overflow=20))
async with make_client(app) as client:
alice = await create_user(client)
bob = await create_user(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)
await app.state.engine.dispose()
async with db_engine.connect() as connection:
chats = (await connection.execute(text("SELECT count(*) FROM chats"))).scalar_one()
members = (
await connection.execute(text("SELECT count(*) FROM chat_members"))
).scalar_one()
assert chats == 10 and members == 20