Files
mtusi2026lab2/scripts/check_grade4.py
T

86 lines
2.8 KiB
Python

"""Explicit local Docker checks: expiry, then Redis/PostgreSQL outages."""
import argparse
import subprocess
import sys
import time
from pathlib import Path
from uuid import uuid4
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check
def docker(*args):
subprocess.run(["docker", *args], cwd=ROOT, check=True, timeout=90,
stdout=subprocess.DEVNULL)
def wait_ready(c):
deadline = time.monotonic() + 45
while True:
try:
c.call("GET", "/health/ready", schema="Health")
return
except Failure:
if time.monotonic() >= deadline:
raise
time.sleep(0.2)
def check_expiry(base_url):
c = Client(base_url, timeout=8)
wait_ready(c)
actor = c.user("expiry")
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
time.sleep(2.2)
c.call("GET", "/api/v1/users/me", 401, actor=actor)
print("PASS: SESSION_TTL_SECONDS=2; active token becomes 401 after expiry")
def check_outage(c, service, stop, start):
wait_ready(c)
actor = c.user("outage")
try:
stop()
for path in ("/health/ready", "/api/v1/users/me"):
response = c.call("GET", path, 503,
actor=actor if path.startswith("/api/") else None)
check(response["elapsed"] < 8, service + " failure took too long")
check(response["json"]["error"]["code"] == "unavailable", "wrong outage error")
c.call("GET", "/health/live", schema="Health")
c.call("GET", "/api/v1/users/me", 401)
finally:
start()
wait_ready(c)
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
print("PASS: " + service + " outage -> bounded 503; live=200; anonymous=401; old token recovers")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--expiry-port", type=int, default=8081)
args = parser.parse_args()
check(1 <= args.expiry_port <= 65535, "invalid expiry port")
name = "lab2-expiry-" + uuid4().hex[:12]
started = False
try:
docker("compose", "run", "-d", "--rm", "--no-deps", "--name", name,
"-e", "SESSION_TTL_SECONDS=2", "-p", "127.0.0.1:" + str(args.expiry_port) + ":8080", "api")
started = True
check_expiry("http://127.0.0.1:" + str(args.expiry_port))
finally:
if started:
docker("stop", name)
c = Client(args.base_url, timeout=8)
for service in ("redis", "postgres"):
check_outage(c, service,
lambda s=service: docker("compose", "stop", s),
lambda s=service: docker("compose", "up", "-d", "--wait", s))
if __name__ == "__main__":
main()