Files
mtusi2026lab3/student-tests/lab3.py
2026-11-12 21:23:41 +03:00

81 lines
3.1 KiB
Python

#!/usr/bin/env python3
"""Own lab3 checks: two replicas, shared idempotency and rolling replacement."""
import argparse
import subprocess
import sys
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--rolling-update", action="store_true")
args = parser.parse_args()
client = Client(args.base_url)
alice, bob, eve, chat = client.bootstrap()
instances = set()
for _ in range(40):
response = client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
instances.add(response["headers"].get("X-Instance-Id", ""))
if len(instances) >= 2:
break
check(len(instances) >= 2, "load balancer did not expose two API instances")
key = "parallel-" + uuid.uuid4().hex
text = "Одна запись при конкурентном повторе"
def send_once():
return client.message(alice, chat, text, key=key)["json"]
with ThreadPoolExecutor(max_workers=10) as pool:
messages = list(pool.map(lambda _: send_once(), range(10)))
check(len({message["id"] for message in messages}) == 1,
"concurrent idempotency created duplicate messages")
check(all(message == messages[0] for message in messages),
"idempotency replay returned different messages")
client.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 409,
actor=alice, body={"text": "Другой текст"},
headers={"Idempotency-Key": key})
client.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 400,
actor=alice, body={"text": "Без ключа"})
print("PASS: two API instances, shared idempotency and conflict semantics")
if args.rolling_update:
output = ROOT / "evidence" / "rolling-load.json"
output.parent.mkdir(parents=True, exist_ok=True)
load = subprocess.Popen([
sys.executable, str(ROOT / "tests" / "load.py"),
"--base-url", args.base_url, "--duration", "20", "--concurrency", "4",
"--output", str(output),
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
time.sleep(2)
result = subprocess.run([str(ROOT / "scripts" / "rolling-update.sh")], check=False)
check(result.returncode == 0, "rolling-update.sh failed")
finally:
try:
load.wait(timeout=40)
except subprocess.TimeoutExpired:
load.kill()
load.wait()
raise Failure("rolling load exceeded its deadline")
check(load.returncode == 0, "load failed during rolling replacement")
print("PASS: rolling replacement completed while load was running")
if __name__ == "__main__":
try:
main()
except (Failure, AssertionError, OSError) as error:
print("FAIL:", error)
raise SystemExit(1)