Files
mtusi2026lab3/student-tests/test_lab3.py
T
2026-11-04 16:11:13 +03:00

84 lines
2.8 KiB
Python

#!/usr/bin/env python3
"""Student acceptance checks for shared idempotency across API replicas."""
from concurrent.futures import ThreadPoolExecutor
import os
import sys
import unittest
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client
BASE = os.environ.get('BASE_URL', 'http://localhost:8080').rstrip('/')
class Lab3IdempotencyTests(unittest.TestCase):
def setUp(self):
self.client = Client(BASE)
self.alice, self.bob, _eve, self.chat = self.client.bootstrap()
self.key = 'test-' + uuid.uuid4().hex
def test_same_key_and_body_replay_same_message(self):
first = self.client.message(self.alice, self.chat, 'replay me', key=self.key)
replay = self.client.message(self.alice, self.chat, 'replay me', key=self.key)
self.assertEqual(first['json'], replay['json'])
def test_same_key_with_different_body_conflicts(self):
self.client.message(self.alice, self.chat, 'original', key=self.key)
response = self.client.call(
'POST',
'/api/v1/chats/' + self.chat['id'] + '/messages',
409,
actor=self.alice,
body={'text': 'different'},
headers={'Idempotency-Key': self.key},
)
self.assertEqual(response['json']['error']['code'], 'conflict')
def test_key_is_required_and_validated(self):
path = '/api/v1/chats/' + self.chat['id'] + '/messages'
self.client.call(
'POST', path, 400, actor=self.alice, body={'text': 'missing key'}
)
self.client.call(
'POST',
path,
400,
actor=self.alice,
body={'text': 'invalid key'},
headers={'Idempotency-Key': 'not valid'},
)
def test_concurrent_retries_create_one_message(self):
text = 'concurrent-' + uuid.uuid4().hex
with ThreadPoolExecutor(max_workers=16) as pool:
results = list(pool.map(
lambda _index: self.client.message(
self.alice, self.chat, text, key=self.key
),
range(16),
))
messages = [result['json'] for result in results]
self.assertTrue(all(message == messages[0] for message in messages))
instances = {result['headers'].get('X-Instance-Id') for result in results}
self.assertGreaterEqual(len(instances), 2)
history = self.client.call(
'GET',
'/api/v1/chats/' + self.chat['id'] + '/messages?limit=100',
actor=self.bob,
schema='MessagePage',
)['json']['items']
self.assertEqual(
sum(message['text'] == text for message in history),
1,
)
if __name__ == '__main__':
unittest.main()