Files
mtusi2026lab3/tests/test_idempotency.py

93 lines
2.8 KiB
Python

"""Pytest-проверки общей идемпотентности сообщений."""
from concurrent.futures import ThreadPoolExecutor
import uuid
import pytest
from tests.client import Client
@pytest.fixture
def scenario():
"""Создаёт отдельного пользователя и чат для теста."""
client = Client()
alice, _bob, _eve, chat = client.bootstrap()
return client, alice, chat
def test_replay_returns_original_message(scenario):
"""Повтор ключа возвращает исходное сообщение."""
client, alice, chat = scenario
key = uuid.uuid4().hex
first = client.message(alice, chat, 'same-body', key=key)['json']
replay = client.message(alice, chat, 'same-body', key=key)['json']
assert replay == first
def test_reused_key_with_different_body_returns_conflict(scenario):
"""Повтор ключа с другим телом возвращает 409."""
client, alice, chat = scenario
key = uuid.uuid4().hex
client.message(alice, chat, 'first-body', key=key)
client.call(
'POST',
'/api/v1/chats/' + chat['id'] + '/messages',
409,
actor=alice,
body={'text': 'different-body'},
headers={'Idempotency-Key': key},
)
@pytest.mark.parametrize(
'headers',
[
pytest.param({}, id='missing'),
pytest.param({'Idempotency-Key': 'invalid key'}, id='invalid'),
],
)
def test_invalid_idempotency_key_returns_bad_request(scenario, headers):
"""Отсутствующий или неверный ключ возвращает 400."""
client, alice, chat = scenario
client.call(
'POST',
'/api/v1/chats/' + chat['id'] + '/messages',
400,
actor=alice,
body={'text': 'validation'},
headers=headers,
)
def test_concurrent_retries_create_one_message(scenario):
"""Конкурентные повторы через две реплики создают одно сообщение."""
client, alice, chat = scenario
key = uuid.uuid4().hex
text = 'concurrent-idempotency-' + key
def send(_index):
return Client(timeout=5).message(alice, chat, text, key=key)
with ThreadPoolExecutor(max_workers=20) as pool:
responses = list(pool.map(send, range(20)))
message_ids = {response['json']['id'] for response in responses}
instance_ids = {response['headers']['X-Instance-Id'] for response in responses}
assert len(message_ids) == 1
assert len(instance_ids) >= 2
history = client.call(
'GET',
'/api/v1/chats/' + chat['id'] + '/messages?limit=100',
actor=alice,
schema='MessagePage',
)['json']['items']
matching = [message for message in history if message['text'] == text]
assert len(matching) == 1
assert matching[0]['id'] in message_ids