forked from mtusi2026/mtusi2026lab4
Реализация лабораторной работы 4 на 4
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
"""Гонка регистрации одинакового username и rollback создания чата"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
from helpers import assert_error, auth, psql, unique_password, unique_username
|
||||
|
||||
PARALLEL_REGISTRATIONS = 20
|
||||
|
||||
|
||||
async def _register_concurrently(base_url: str, username: str) -> list[int]:
|
||||
"""Все запросы стартуют по одному сигналу, у каждого свой пароль"""
|
||||
start = asyncio.Event()
|
||||
|
||||
async def register(client: httpx.AsyncClient) -> int:
|
||||
await start.wait()
|
||||
body = {
|
||||
"username": username,
|
||||
"display_name": "Гонка",
|
||||
"password": unique_password(),
|
||||
}
|
||||
response = await client.post("/api/v1/users", json=body)
|
||||
return response.status_code
|
||||
|
||||
limits = httpx.Limits(max_connections=PARALLEL_REGISTRATIONS)
|
||||
async with httpx.AsyncClient(
|
||||
base_url=base_url, timeout=30, limits=limits
|
||||
) as client:
|
||||
tasks = [
|
||||
asyncio.create_task(register(client)) for _ in range(PARALLEL_REGISTRATIONS)
|
||||
]
|
||||
await asyncio.sleep(0)
|
||||
start.set()
|
||||
return list(await asyncio.gather(*tasks))
|
||||
|
||||
|
||||
def test_same_username_race_creates_exactly_one_user(base_url: str) -> None:
|
||||
username = unique_username("race")
|
||||
statuses = asyncio.run(_register_concurrently(base_url, username))
|
||||
stored = psql(f"SELECT count(*) FROM users WHERE username = '{username}';")
|
||||
print(
|
||||
"\nREGISTRATION RACE:",
|
||||
json.dumps(
|
||||
{
|
||||
"requests": len(statuses),
|
||||
"status_201": statuses.count(201),
|
||||
"status_409": statuses.count(409),
|
||||
"rows_in_db": int(stored),
|
||||
}
|
||||
),
|
||||
)
|
||||
assert statuses.count(201) == 1
|
||||
assert statuses.count(409) == PARALLEL_REGISTRATIONS - 1
|
||||
assert stored == "1"
|
||||
|
||||
|
||||
def test_failed_chat_creation_is_rolled_back(api: httpx.Client, make_user) -> None:
|
||||
"""
|
||||
Строка chats вставляется первой, затем участники нарушают FK (неизвестный
|
||||
пользователь в конце списка). После 400 в БД не должно остаться ни чата
|
||||
с этим title, ни его участников: откатилась вся транзакция.
|
||||
"""
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
title = f"rollback-{uuid.uuid4().hex}"
|
||||
body = {"title": title, "member_ids": [alice["id"], bob["id"], str(uuid.uuid4())]}
|
||||
|
||||
response = api.post("/api/v1/chats", json=body, headers=auth(alice))
|
||||
|
||||
assert_error(response, 400, "invalid_request")
|
||||
assert psql(f"SELECT count(*) FROM chats WHERE title = '{title}';") == "0"
|
||||
orphan_members = psql(
|
||||
"SELECT count(*) FROM chat_members m "
|
||||
"LEFT JOIN chats c ON c.id = m.chat_id WHERE c.id IS NULL;"
|
||||
)
|
||||
assert orphan_members == "0"
|
||||
listed = api.get("/api/v1/chats", params={"limit": 100}, headers=auth(alice))
|
||||
assert all(chat["title"] != title for chat in listed.json()["items"])
|
||||
|
||||
|
||||
def test_successful_chat_creation_commits_all_members(
|
||||
api: httpx.Client, make_user
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
title = f"commit-{uuid.uuid4().hex}"
|
||||
body = {"title": title, "member_ids": [bob["id"], alice["id"]]}
|
||||
chat = api.post("/api/v1/chats", json=body, headers=auth(alice)).json()
|
||||
assert chat["member_ids"] == [bob["id"], alice["id"]]
|
||||
members = psql(f"SELECT count(*) FROM chat_members WHERE chat_id = '{chat['id']}';")
|
||||
assert members == "2"
|
||||
again = api.get(f"/api/v1/chats/{chat['id']}", headers=auth(bob)).json()
|
||||
assert again == chat
|
||||
Reference in New Issue
Block a user