import threading import unittest from concurrent.futures import ThreadPoolExecutor from api import call, history, new_chat, new_key, new_user, send class IdempotencyTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.alice, cls.bob, cls.eve = new_user("alice"), new_user("bob"), new_user("eve") cls.chat = new_chat(cls.alice, cls.bob) cls.path = "/api/v1/chats/" + cls.chat["id"] + "/messages" def test_key_is_required(self): status, body, _ = call("POST", self.path, {"text": "без ключа"}, user=self.alice) self.assertEqual(status, 400) self.assertEqual(body["error"]["code"], "invalid_request") def test_bad_keys(self): for key in ("", "a" * 129, "с пробелом", "кириллица", "a/b", "a,b"): with self.subTest(key=key[:12]): headers = {"Idempotency-Key": key.encode("utf-8").decode("latin-1")} self.assertEqual(call("POST", self.path, {"text": "x"}, user=self.alice, headers=headers)[0], 400) def test_good_key_alphabet(self): for key in ("a", "A.b_c:d-1", "x" * 128): with self.subTest(key=key[:12]): self.assertEqual(send(self.alice, self.chat, "ключ " + key, key=key)[0], 201) def test_repeat_returns_same_message(self): key = new_key() first = send(self.alice, self.chat, "Привет 👋", key=key) second = send(self.alice, self.chat, "Привет 👋", key=key) self.assertEqual((first[0], second[0]), (201, 201)) self.assertEqual(first[1], second[1]) def test_key_order_in_json_does_not_matter(self): key = new_key() headers = {"Idempotency-Key": key} first = call("POST", self.path, {"text": "порядок"}, user=self.alice, headers=headers) second = call("POST", self.path, raw=' { "text" : "порядок" } '.encode(), user=self.alice, headers=headers) self.assertEqual(first[1], second[1]) def test_other_text_with_same_key_is_409(self): key = new_key() first = send(self.alice, self.chat, "первый текст", key=key) status, body, _ = send(self.alice, self.chat, "другой текст", key=key) self.assertEqual(status, 409) self.assertEqual(body["error"]["code"], "conflict") # конфликт ничего не меняет: исходный текст по-прежнему возвращается self.assertEqual(send(self.alice, self.chat, "первый текст", key=key)[1], first[1]) def test_same_key_for_other_user_and_other_chat(self): key = new_key() other_chat = new_chat(self.alice) first = send(self.alice, self.chat, "общий ключ", key=key)[1] by_bob = send(self.bob, self.chat, "общий ключ", key=key)[1] in_other_chat = send(self.alice, other_chat, "общий ключ", key=key)[1] self.assertEqual(len({first["id"], by_bob["id"], in_other_chat["id"]}), 3) self.assertEqual(by_bob["sender_id"], self.bob["id"]) def test_repeat_checks_access_again(self): key = new_key() send(self.alice, self.chat, "только участникам", key=key) self.assertEqual(send(self.eve, self.chat, "только участникам", key=key)[0], 404) self.assertEqual(send({"token": "x" * 43}, self.chat, "только участникам", key=key)[0], 401) def test_invalid_body_does_not_take_key(self): key = new_key() self.assertEqual(send(self.alice, self.chat, "", key=key)[0], 400) self.assertEqual(send(self.alice, self.chat, "теперь верно", key=key)[0], 201) def test_parallel_repeat_through_different_replicas(self): user = new_user("idem") chat = new_chat(user) instances = set() for round_number in range(10): key = new_key() barrier = threading.Barrier(8) def post(_): barrier.wait() return send(user, chat, "сообщение %d" % round_number, key=key) with ThreadPoolExecutor(max_workers=8) as pool: results = list(pool.map(post, range(8))) self.assertEqual({status for status, _, _ in results}, {201}) self.assertEqual(len({message["id"] for _, message, _ in results}), 1) instances |= {headers["X-Instance-Id"] for _, _, headers in results} self.assertGreaterEqual(len(instances), 2, "запросы не дошли до разных реплик") items, _ = history(user, chat, 100) self.assertEqual(len(items), 10) print("\n10 ключей по 8 параллельных запросов: реплик %d, сообщений в истории %d" % (len(instances), len(items))) if __name__ == "__main__": unittest.main()