Files
mtusi2026lab5/student-tests/test_idempotency.py
T

76 lines
2.3 KiB
Python

from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4
import httpx
import pytest
from conftest import BASE_URL, check, headers, history
@pytest.mark.parametrize("key", [None, "", "a b", "x" * 129, "a/b"])
def test_key_required_and_valid(client, actors, chat, key):
h = headers(actors[0])
h.pop("Idempotency-Key")
if key is not None:
h["Idempotency-Key"] = key
check(
client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers=h,
json={"text": "Key"},
),
400,
"Error",
)
def test_parallel_replay_across_instances(client, actors, chat):
h = headers(actors[0])
path = f"/api/v1/chats/{chat['id']}/messages"
def send(_):
with httpx.Client(base_url=BASE_URL, trust_env=False, timeout=15) as c:
r = c.post(path, headers=h, json={"text": "Один результат 🌍"})
return check(r, 201, "Message"), r.headers["x-instance-id"]
with ThreadPoolExecutor(max_workers=10) as pool:
results = list(pool.map(send, range(30)))
assert len({r[0]["id"] for r in results}) == 1
assert len({r[1] for r in results}) >= 2
assert history(client, actors[0], chat["id"]) == [results[0][0]]
check(
client.post(path, headers=h, json={"text": "Другой текст"}),
409,
"Error",
)
# Другой пользователь может независимо использовать тот же ключ.
other = headers(actors[1])
other["Idempotency-Key"] = h["Idempotency-Key"]
second = check(
client.post(path, headers=other, json={"text": "Боб"}), 201, "Message"
)
assert second["id"] != results[0][0]["id"]
def test_replay_rechecks_acl(client, actors, chat):
h = headers(actors[0])
path = f"/api/v1/chats/{chat['id']}/messages"
check(
client.post(path, headers=h, json={"text": "Existing"}), 201, "Message"
)
outsider = headers(actors[2])
outsider["Idempotency-Key"] = h["Idempotency-Key"]
check(
client.post(path, headers=outsider, json={"text": "Existing"}),
404,
"Error",
)
check(
client.post(
path,
headers={"Idempotency-Key": uuid4().hex},
json={"text": "Existing"},
),
401,
"Error",
)