Files
mtusi2026lab3/student-tests/idempotency_persistence.py
T

89 lines
2.8 KiB
Python

#!/usr/bin/env python3
"""Idempotency state must survive a full API/PostgreSQL/Redis restart."""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
from common import HttpClient, assert_status
ROOT = Path(__file__).resolve().parents[1]
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument(
"--restart-script",
default="scripts/restart.cmd" if os.name == "nt" else "scripts/restart.sh",
)
args = parser.parse_args()
script = (ROOT / args.restart_script).resolve()
if not script.is_file():
raise SystemExit(f"restart script not found: {script}")
client = HttpClient(args.base_url)
user, registration = client.register()
session = client.login(registration)
token = session["token"]
status, _headers, chat, _raw = client.call(
"POST",
"/api/v1/chats",
body={"title": "Idempotency persistence", "member_ids": [user["id"]]},
token=token,
)
assert_status(status, 201, "chat")
key = uuid.uuid4().hex
text = "persist replay " + uuid.uuid4().hex
status, _headers, first, _raw = client.call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
body={"text": text},
token=token,
headers={"Idempotency-Key": key},
)
assert_status(status, 201, "first message")
subprocess.run([str(script)], cwd=ROOT, check=True, stdout=subprocess.DEVNULL)
deadline = time.monotonic() + 90
while True:
try:
status, _headers, _payload, _raw = client.call("GET", "/health/ready")
if status == 200:
break
except OSError:
pass
if time.monotonic() > deadline:
raise AssertionError("stack did not become ready after restart")
time.sleep(0.5)
status, _headers, replay, _raw = client.call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
body={"text": text},
token=token,
headers={"Idempotency-Key": key},
)
assert_status(status, 201, "replay after restart")
if replay != first:
raise AssertionError("replay after restart returned a different Message")
status, _headers, page, _raw = client.call(
"GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", token=token
)
assert_status(status, 200, "history")
copies = [item for item in page["items"] if item["text"] == text]
if len(copies) != 1:
raise AssertionError(f"history contains {len(copies)} copies after restart")
print("PASS: same Idempotency-Key returned the same Message after full restart")
if __name__ == "__main__":
main()