from concurrent.futures import ThreadPoolExecutor import threading import unittest import uuid from helpers import call, new_chat, new_user, read_all_messages PARALLEL = 20 def post(chat, user, key, body=None, raw=None): return call('POST', '/api/v1/chats/%s/messages' % chat['id'], body, user['token'], raw=raw, headers={'Idempotency-Key': key}) class IdempotencyTest(unittest.TestCase): def setUp(self): self.alice, self.bob = new_user('alice'), new_user('bob') self.chat = new_chat(self.alice, self.bob) def history(self): return read_all_messages(self.chat['id'], self.alice['token'], limit=100)[0] def test_replay_returns_same_message(self): """Повтор того же запроса с тем же ключом -> тот же 201 и тот же Message, дубля нет""" key = uuid.uuid4().hex first = post(self.chat, self.alice, key, {'text': 'один раз'}) second = post(self.chat, self.alice, key, {'text': 'один раз'}) self.assertEqual((first[0], second[0]), (201, 201)) self.assertEqual(first[2], second[2]) self.assertEqual([m['id'] for m in self.history()], [first[2]['id']]) def test_json_formatting_does_not_matter(self): """Порядок/пробелы в JSON семантически равны: повтор с другим форматированием -> тот же Message""" key = uuid.uuid4().hex first = post(self.chat, self.alice, key, raw='{"text":"формат"}'.encode()) second = post(self.chat, self.alice, key, raw='{ "text" : "формат" }'.encode()) self.assertEqual((first[0], second[0]), (201, 201)) self.assertEqual(first[2]['id'], second[2]['id']) def test_other_body_with_same_key_conflicts(self): """Тот же ключ с другим телом -> 409, второе сообщение не создаётся""" key = uuid.uuid4().hex self.assertEqual(post(self.chat, self.alice, key, {'text': 'первое'})[0], 201) status, _, body = post(self.chat, self.alice, key, {'text': 'другое'}) self.assertEqual((status, body['error']['code']), (409, 'conflict')) self.assertEqual(len(self.history()), 1) def test_missing_or_invalid_key(self): """Нет ключа, пустой, недопустимые символы, длиннее 128 -> 400""" for key in (None, '', 'bad key', 'bad/key', 'café', 'x' * 129): with self.subTest(key=key): self.assertEqual(post(self.chat, self.alice, key, {'text': 'x'})[0], 400) self.assertEqual(post(self.chat, self.alice, 'A.b_c:d-1' + 'x' * 119, {'text': 'граница'})[0], 201) def test_key_scope_is_user_and_chat(self): """Одинаковый ключ у разных пользователей и в разных чатах — независимые сообщения""" key = uuid.uuid4().hex other_chat = new_chat(self.alice, title='Другой') a = post(self.chat, self.alice, key, {'text': 'от Алисы'}) b = post(self.chat, self.bob, key, {'text': 'от Боба'}) c = post(other_chat, self.alice, key, {'text': 'от Алисы'}) self.assertEqual([a[0], b[0], c[0]], [201, 201, 201]) self.assertEqual(len({a[2]['id'], b[2]['id'], c[2]['id']}), 3) def test_replay_rechecks_session_and_access(self): """Повтор снова проверяет сессию и доступ: после logout -> 401, посторонний с тем же ключом -> 404""" key = uuid.uuid4().hex self.assertEqual(post(self.chat, self.alice, key, {'text': 'до выхода'})[0], 201) eve = new_user('eve') self.assertEqual(post(self.chat, eve, key, {'text': 'до выхода'})[0], 404) call('DELETE', '/api/v1/auth/sessions/current', token=self.alice['token']) self.assertEqual(post(self.chat, self.alice, key, {'text': 'до выхода'})[0], 401) def test_parallel_retries_through_replicas_create_one_message(self): """20 одновременных POST с одним ключом через LB (разные реплики) -> ровно одно сообщение, все 201 с одним id""" key = uuid.uuid4().hex barrier = threading.Barrier(PARALLEL) def send(_): barrier.wait() status, headers, body = post(self.chat, self.alice, key, {'text': 'конкурентный повтор'}) return status, headers['X-Instance-Id'], body with ThreadPoolExecutor(max_workers=PARALLEL) as pool: results = list(pool.map(send, range(PARALLEL))) self.assertEqual({status for status, _, _ in results}, {201}) self.assertEqual(len({body['id'] for _, _, body in results}), 1) self.assertGreaterEqual(len({instance for _, instance, _ in results}), 2, 'запросы не попали на разные реплики') self.assertEqual(len(self.history()), 1) print('\n 20 повторов: реплики %s, сообщений в истории: %d' % (sorted({instance for _, instance, _ in results}), len(self.history()))) if __name__ == '__main__': unittest.main()