Files
mtusi2026lab3/student_tests/test_idempotency_parallel.py

43 lines
1.8 KiB
Python

#!/usr/bin/env python3
"""30 параллельных POST с одним Idempotency-Key через LB: ровно одно сообщение, везде 201 и один id."""
import json
import sys
import threading
import uuid
from common import call, setup
BASE = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
THREADS, ROUNDS = 30, 5
auth, chat = setup(BASE)
path = f"/api/v1/chats/{chat}/messages"
replicas = set()
for rnd in range(ROUNDS):
key = uuid.uuid4().hex
barrier = threading.Barrier(THREADS)
results = [None] * THREADS
def work(i, rnd=rnd, key=key, barrier=barrier, results=results):
barrier.wait()
s, h, b = call(BASE, "POST", path, {"text": f"parallel {rnd}"}, {**auth, "Idempotency-Key": key}, timeout=10)
results[i] = (s, h.get("x-instance-id"), json.loads(b) if s == 201 else None)
ts = [threading.Thread(target=work, args=(i,)) for i in range(THREADS)]
[t.start() for t in ts]
[t.join() for t in ts]
codes = {r[0] for r in results}
msg_ids = {r[2]["id"] for r in results if r[0] == 201}
replicas |= {r[1] for r in results}
assert codes == {201}, f"round {rnd}: codes {codes}"
assert len(msg_ids) == 1, f"round {rnd}: {len(msg_ids)} different messages"
s, _, _ = call(BASE, "POST", path, {"text": "other body"}, {**auth, "Idempotency-Key": key})
assert s == 409, f"round {rnd}: other body gave {s}"
s, _, b = call(BASE, "GET", path + "?limit=100", headers=auth)
count = len(json.loads(b)["items"])
assert count == ROUNDS, f"history has {count} messages, expected {ROUNDS}"
print(json.dumps({"rounds": ROUNDS, "parallel_requests_per_round": THREADS,
"messages_in_history": count, "replicas_that_answered": sorted(r for r in replicas if r)}))
print("PASS: same key in parallel -> exactly one message; different body -> 409")