forked from mtusi2026/mtusi2026lab2
35 lines
1.9 KiB
Python
35 lines
1.9 KiB
Python
"""Гонка регистрации одинакового username и откат составной операции создания чата."""
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from common import *
|
|
|
|
N = 20
|
|
|
|
|
|
def main():
|
|
name = "race" + uuid.uuid4().hex[:10]
|
|
body = {"username": name, "display_name": "Race", "password": PASSWORD}
|
|
with ThreadPoolExecutor(N) as ex:
|
|
statuses = list(ex.map(lambda _: call("POST", "/api/v1/users", body)[0], range(N)))
|
|
created = statuses.count(201)
|
|
conflicts = statuses.count(409)
|
|
print(f"registration race: {N} parallel requests -> 201 x{created}, 409 x{conflicts}, other {N - created - conflicts}")
|
|
check(created == 1 and conflicts == N - 1, "exactly one registration must win, others 409")
|
|
|
|
alice = new_user("rb")
|
|
token = login(alice)["token"]
|
|
before = call("GET", "/api/v1/chats?limit=100", headers=bearer(token))[1]["items"]
|
|
# участник alice вставится первым, неизвестный — вторым: без транзакции чат остался бы
|
|
st, err, _, _ = call("POST", "/api/v1/chats", {"title": "Откат", "member_ids": [alice["id"], str(uuid.uuid4())]}, bearer(token))
|
|
check(st == 400, f"unknown member must be 400, got {st}")
|
|
after = call("GET", "/api/v1/chats?limit=100", headers=bearer(token))[1]["items"]
|
|
check(before == after, "failed chat creation must leave no chat/membership")
|
|
orphans = compose("exec", "-T", "postgres", "sh", "-c",
|
|
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -tAc "SELECT count(*) FROM chats c WHERE NOT EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id)"')
|
|
check(orphans.strip() == "0", "chats without members exist in DB")
|
|
print("rollback: chat with unknown member -> 400, chat list unchanged, 0 orphan chats in DB")
|
|
print("PASS: test_race")
|
|
|
|
|
|
run(main)
|