ЛР5: асинхронная обработка вложений (RabbitMQ + worker), transactional outbox, варианты, трек 5.1
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
"""Lab3 shared idempotency: replay, conflict and cross-replica concurrency."""
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import json
|
||||
import uuid
|
||||
|
||||
|
||||
def test_replay_same_key_returns_same_message(client, alice, chat):
|
||||
key = uuid.uuid4().hex
|
||||
first = client.send(alice["token"], chat["id"], "идемпотентно", key=key)
|
||||
assert first.status == 201, first.body
|
||||
replay = client.send(alice["token"], chat["id"], "идемпотентно", key=key)
|
||||
assert replay.status == 201, replay.body
|
||||
assert replay.json == first.json, "replay must return the same Message"
|
||||
|
||||
|
||||
def test_same_key_different_body_is_409(client, alice, chat):
|
||||
key = uuid.uuid4().hex
|
||||
assert client.send(alice["token"], chat["id"], "первый", key=key).status == 201
|
||||
conflict = client.send(alice["token"], chat["id"], "второй", key=key)
|
||||
assert conflict.status == 409, conflict.body
|
||||
assert conflict.json["error"]["code"] == "conflict"
|
||||
|
||||
|
||||
def test_missing_key_is_400(client, alice, chat):
|
||||
response = client.request(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
body={"text": "без ключа"},
|
||||
token=alice["token"],
|
||||
)
|
||||
assert response.status == 400, response.body
|
||||
assert response.json["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
def test_invalid_key_is_400(client, alice, chat):
|
||||
for bad in ("bad key", "has/slash", "x" * 129, "with$sign"):
|
||||
response = client.request(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
body={"text": "плохой ключ"},
|
||||
token=alice["token"],
|
||||
headers={"Idempotency-Key": bad},
|
||||
)
|
||||
assert response.status == 400, (bad, response.status, response.body)
|
||||
|
||||
|
||||
def test_concurrent_same_key_creates_exactly_one_message(client, alice, chat):
|
||||
key = uuid.uuid4().hex
|
||||
text = "конкурентный повтор " + uuid.uuid4().hex
|
||||
|
||||
def send(_):
|
||||
return client.send(alice["token"], chat["id"], text, key=key)
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
responses = list(pool.map(send, range(8)))
|
||||
|
||||
assert all(r.status == 201 for r in responses), [r.status for r in responses]
|
||||
bodies = {json.dumps(r.json, sort_keys=True) for r in responses}
|
||||
assert len(bodies) == 1, "parallel replays returned different messages"
|
||||
|
||||
history = client.list_messages(alice["token"], chat["id"], limit=100).json["items"]
|
||||
matching = [m for m in history if m["text"] == text]
|
||||
assert len(matching) == 1, f"expected exactly one stored message, got {len(matching)}"
|
||||
Reference in New Issue
Block a user