Files
mtusi2026lab4/student-tests/test_idempotency.py
T

69 lines
3.4 KiB
Python

"""Real HTTP races through the LB, with one shared session and key."""
from concurrent.futures import ThreadPoolExecutor
import os
from pathlib import Path
import sys
import threading
import unittest
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client
class Idempotency(unittest.TestCase):
def setUp(self):
self.c = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
self.a, self.b, self.e, self.chat = self.c.bootstrap()
self.path = "/api/v1/chats/" + self.chat["id"] + "/messages"
def test_same_key_concurrent_across_replicas(self):
key, barrier = uuid4().hex, threading.Barrier(12)
def send(_):
c = Client(self.c.base)
barrier.wait(timeout=10)
return c.message(self.a, self.chat, "Один результат 👋", key=key)
with ThreadPoolExecutor(max_workers=12) as pool:
results = list(pool.map(send, range(12)))
self.assertGreaterEqual(len({r["headers"]["X-Instance-Id"] for r in results}), 2)
self.assertTrue(all(r["json"] == results[0]["json"] for r in results))
history = self.c.call("GET", self.path, actor=self.b, schema="MessagePage")["json"]
self.assertEqual(history["items"], [results[0]["json"]])
print("PASS: concurrent_retries=12 observed_replicas=2 committed_messages=1", flush=True)
def test_conflicting_bodies_race(self):
key, barrier = uuid4().hex, threading.Barrier(2)
def send(text):
c = Client(self.c.base)
barrier.wait(timeout=10)
return c.call("POST", self.path, [201, 409], actor=self.a,
body={"text": text}, headers={"Idempotency-Key": key})
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(send, ["first", "second"]))
self.assertEqual(sorted(r["status"] for r in results), [201, 409])
history = self.c.call("GET", self.path, actor=self.a, schema="MessagePage")["json"]
self.assertEqual(len(history["items"]), 1)
def test_key_scope_and_access(self):
key = uuid4().hex
one = self.c.message(self.a, self.chat, "first", key=key)["json"]
two = self.c.message(self.b, self.chat, "second", key=key)["json"]
other = self.c.call("POST", "/api/v1/chats", 201, actor=self.a,
body={"title": "other", "member_ids": [self.a["id"]]}, schema="Chat")["json"]
three = self.c.message(self.a, other, "third", key=key)["json"]
self.assertEqual(len({m["id"] for m in (one, two, three)}), 3)
self.c.call("POST", self.path, 404, actor=self.e, body={"text": "first"}, headers={"Idempotency-Key": key})
self.c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.a)
self.c.call("POST", self.path, 401, actor=self.a, body={"text": "first"}, headers={"Idempotency-Key": key})
def test_invalid_keys_and_no_cached_error(self):
for key in ("", "a" * 129, "has space", "bad/key", "bad,key"):
self.c.call("POST", self.path, 400, actor=self.a, body={"text": "hello"}, headers={"Idempotency-Key": key})
key = uuid4().hex
self.c.call("POST", self.path, 400, actor=self.a, body={"text": " "}, headers={"Idempotency-Key": key})
self.c.message(self.a, self.chat, "valid after rejected body", key=key)
if __name__ == "__main__":
unittest.main()