Files
mtusi2026lab5/student-tests/test_lab3.py
T
2026-11-20 20:11:39 +03:00

108 lines
4.8 KiB
Python

"""Собственные проверки лабораторной 3: реплики, LB и общая идемпотентность."""
from __future__ import annotations
import threading
import unittest
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4
import harness
from client import Client
class Lab3Tests(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
harness.wait_ready()
cls.api = harness.client()
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap()
def test_01_at_least_two_instances_and_stable_header(self) -> None:
"""LB действительно распределяет один и тот же токен между разными процессами."""
observed = harness.instance_ids(self.api, self.alice, 40)
self.assertGreaterEqual(len(observed), 2, "less than two X-Instance-Id values through LB")
for _ in range(10):
me = self.api.call("GET", "/api/v1/users/me", actor=self.alice, schema="User")["json"]
self.assertEqual(me["id"], self.alice["id"])
def test_02_concurrent_same_key_through_lb_creates_one_message(self) -> None:
"""Один ключ + одно тело одновременно через разные реплики = одно сообщение."""
key = uuid4().hex
text = "concurrent-idempotency-" + uuid4().hex
workers = 24
barrier = threading.Barrier(workers)
def worker(_: int) -> dict:
local = harness.client(10)
barrier.wait()
return local.message(self.alice, self.chat, text, key=key)
with ThreadPoolExecutor(max_workers=workers) as pool:
responses = list(pool.map(worker, range(workers)))
bodies = [response["json"] for response in responses]
instances = {response["headers"]["X-Instance-Id"] for response in responses}
self.assertGreaterEqual(len(instances), 2, "concurrent requests did not reach both replicas")
self.assertEqual(bodies, [bodies[0]] * workers, "replay returned a different Message")
messages = [m for m in harness.history(self.api, self.bob, self.chat["id"]) if m["text"] == text]
self.assertEqual(len(messages), 1, "idempotency key created %d messages" % len(messages))
self.assertEqual(messages[0], bodies[0])
def test_03_same_key_other_body_conflicts(self) -> None:
key = uuid4().hex
first = self.api.message(self.alice, self.chat, "first-" + uuid4().hex, key=key)["json"]
replay = self.api.message(self.alice, self.chat, first["text"], key=key)["json"]
self.assertEqual(replay, first)
self.api.call(
"POST",
"/api/v1/chats/" + self.chat["id"] + "/messages",
409,
actor=self.alice,
body={"text": "different body"},
headers={"Idempotency-Key": key},
)
def test_04_key_scope_user_and_chat(self) -> None:
key = uuid4().hex
text_alice = "scope-a-" + uuid4().hex
text_bob = "scope-b-" + uuid4().hex
alice_message = self.api.message(self.alice, self.chat, text_alice, key=key)["json"]
bob_message = self.api.message(self.bob, self.chat, text_bob, key=key)["json"]
self.assertNotEqual(alice_message["id"], bob_message["id"])
other_chat = self.api.call(
"POST",
"/api/v1/chats",
201,
actor=self.alice,
body={"title": "Другой чат", "member_ids": [self.alice["id"]]},
schema="Chat",
)["json"]
other = self.api.message(self.alice, other_chat, text_alice, key=key)["json"]
self.assertNotEqual(other["id"], alice_message["id"])
def test_05_key_validation(self) -> None:
path = "/api/v1/chats/" + self.chat["id"] + "/messages"
for bad in ("", "has space", "bad/slash", "x" * 129):
self.api.call(
"POST",
path,
400,
actor=self.alice,
body={"text": "bad-key"},
headers={"Idempotency-Key": bad},
)
self.api.call("POST", path, 400, actor=self.alice, body={"text": "no key"})
for good in ("a", "z" * 128):
self.api.message(self.alice, self.chat, "boundary-" + uuid4().hex, key=good)
def test_06_uncertain_retry_is_safe(self) -> None:
"""Повтор с тем же ключом после потери ответа не создаёт второй объект."""
key = uuid4().hex
text = "retry-after-conflict-" + uuid4().hex
first = self.api.message(self.alice, self.chat, text, key=key)["json"]
again = self.api.message(self.alice, self.chat, text, key=key)["json"]
self.assertEqual(first, again)
if __name__ == "__main__":
unittest.main(verbosity=2)