Files
mtusi2026lab3/tests/test_concurrent_idempotency.py
T
2026-10-15 00:18:02 +03:00

46 lines
1.4 KiB
Python

import concurrent.futures
import uuid
from client import Client, check
def main():
client = Client("http://localhost:8080")
alice, bob, eve, chat = client.bootstrap()
key = uuid.uuid4().hex
text = "Concurrent idempotency " + key
def send(_):
return client.message(alice, chat, text, key=key)
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
results = list(executor.map(send, range(20)))
message_ids = {result["json"]["id"] for result in results}
instances = {result["headers"]["X-Instance-Id"] for result in results}
page = client.call(
"GET",
"/api/v1/chats/" + chat["id"] + "/messages?limit=100",
actor=alice,
schema="MessagePage",
)["json"]
matches = [message for message in page["items"] if message["text"] == text]
print("Requests:", len(results))
print("Unique message IDs:", len(message_ids))
print("Instances:", sorted(instances))
print("Messages in history:", len(matches))
check(len(message_ids) == 1, "duplicate message IDs returned")
check(len(instances) >= 2, "requests did not reach both replicas")
check(len(matches) == 1, "duplicate messages found in history")
check(matches[0]["id"] in message_ids, "history message ID differs")
print("PASS: concurrent idempotency across replicas")
if __name__ == "__main__":
main()