"""Идемпотентность отправки сообщения: Idempotency-Key общий для всех реплик.""" import threading import unittest import uuid from concurrent.futures import ThreadPoolExecutor import api class IdempotencyTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.alice, cls.bob = api.new_user('Алиса'), api.new_user('Боб') cls.chat = api.new_chat(cls.alice, [cls.alice, cls.bob]) cls.path = '/api/v1/chats/%s/messages' % cls.chat['id'] def history(self): return [m for page in api.pages(self.path, self.alice, 100) for m in page] def test_replay_returns_the_same_message(self): key = uuid.uuid4().hex first = api.send(self.alice, self.chat, 'повтор ' + key, key=key) second = api.send(self.alice, self.chat, 'повтор ' + key, key=key) self.assertEqual((first.status, second.status), (201, 201)) self.assertEqual(second.json, first.json) self.assertEqual([m['text'] for m in self.history()].count('повтор ' + key), 1) def test_same_key_with_another_body_is_409(self): key = uuid.uuid4().hex self.assertEqual(api.send(self.alice, self.chat, 'первое тело', key=key).status, 201) response = api.send(self.alice, self.chat, 'другое тело', key=key) self.assertEqual(response.status, 409) self.assertEqual(response.json['error']['code'], 'conflict') self.assertNotIn('другое тело', [m['text'] for m in self.history()]) def test_json_formatting_does_not_matter(self): # Пробелы и запись Unicode в JSON не меняют смысл тела: это тот же повтор. key = uuid.uuid4().hex first = api.request('POST', self.path, user=self.alice, raw='{"text":"Привет"}'.encode(), key=key) second = api.request('POST', self.path, user=self.alice, raw=b'{ "text" : "\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442" }', key=key) self.assertEqual((first.status, second.status), (201, 201)) self.assertEqual(second.json, first.json) def test_missing_key_is_400(self): response = api.send(self.alice, self.chat, 'без ключа', key=None) self.assertEqual(response.status, 400) self.assertNotIn('без ключа', [m['text'] for m in self.history()]) def test_invalid_keys_are_400(self): # Кириллица уходит в заголовок байтами UTF-8, как её отправил бы обычный клиент. cyrillic = 'кириллица'.encode('utf-8').decode('latin-1') for key in ('', 'a' * 129, cyrillic, 'with space', 'semi;colon', 'slash/key'): with self.subTest(key=key): self.assertEqual(api.send(self.alice, self.chat, 'ключ', key=key).status, 400) def test_key_format_limits_are_accepted(self): # Свой чат на каждый запуск: область ключа включает чат, поэтому ключи не пересекаются с прошлыми. chat = api.new_chat(self.alice, [self.alice], title='Форматы ключей') for key in ('a' * 128, 'A.b_c:d-1', '0'): with self.subTest(key=key[:20]): self.assertEqual(api.send(self.alice, chat, 'формат ' + key, key=key).status, 201) def test_key_scope_is_user_and_chat(self): key = uuid.uuid4().hex other_chat = api.new_chat(self.alice, [self.alice], title='Другой чат') first = api.send(self.alice, self.chat, 'одинаковый ключ', key=key) in_other_chat = api.send(self.alice, other_chat, 'одинаковый ключ', key=key) by_other_user = api.send(self.bob, self.chat, 'одинаковый ключ', key=key) self.assertEqual({first.status, in_other_chat.status, by_other_user.status}, {201}) self.assertEqual(len({first.json['id'], in_other_chat.json['id'], by_other_user.json['id']}), 3) def test_failed_validation_is_not_remembered(self): # Ответ 400 не фиксируется: тот же ключ можно использовать с исправленным телом. key = uuid.uuid4().hex self.assertEqual(api.send(self.alice, self.chat, ' ', key=key).status, 400) self.assertEqual(api.send(self.alice, self.chat, 'исправлено', key=key).status, 201) def test_replay_checks_the_session_again(self): user = api.new_user('Выход') chat = api.new_chat(user, [user]) key = uuid.uuid4().hex self.assertEqual(api.send(user, chat, 'до выхода', key=key).status, 201) api.request('DELETE', '/api/v1/auth/sessions/current', user=user) self.assertEqual(api.send(user, chat, 'до выхода', key=key).status, 401) def test_parallel_requests_with_one_key_create_one_message(self): # Одновременные повторы расходятся по разным репликам и всё равно создают одно сообщение. key = uuid.uuid4().hex text = 'параллельно ' + key attempts = 20 start = threading.Barrier(attempts) def post(_): start.wait() return api.send(self.alice, self.chat, text, key=key) with ThreadPoolExecutor(max_workers=attempts) as pool: responses = list(pool.map(post, range(attempts))) self.assertEqual({response.status for response in responses}, {201}) self.assertEqual(len({response.json['id'] for response in responses}), 1) self.assertGreaterEqual(len({api.instance(response) for response in responses}), 2) self.assertEqual([m['text'] for m in self.history()].count(text), 1) if __name__ == '__main__': unittest.main()