Files
mtusi2026lab2/student-tests/test_deps.py
T

69 lines
2.2 KiB
Python

"""Dependency failure checks (Redis/Postgres). Optional: RUN_DEPS_TEST=1."""
from __future__ import annotations
import os
import subprocess
import time
from helpers import BASE_URL, call, register
def _compose(*args: str) -> None:
cmd = ["docker", "compose", "--env-file", ".env", *args]
subprocess.check_call(cmd, cwd=os.path.join(os.path.dirname(__file__), ".."))
def _wait_ready(timeout_s: int = 60) -> None:
deadline = time.time() + timeout_s
while time.time() < deadline:
try:
if call("GET", "/health/ready")["status"] == 200:
return
except Exception:
pass
time.sleep(1)
raise AssertionError("stack did not become ready in time")
def test_redis_stop_returns_503_or_unready():
if os.environ.get("RUN_DEPS_TEST") != "1":
print("SKIP test_redis_stop_returns_503_or_unready (set RUN_DEPS_TEST=1)")
return
actor = register("deps")
_compose("stop", "redis")
time.sleep(2)
try:
ready = call("GET", "/health/ready")
assert ready["status"] == 503, ready["status"]
me = call("GET", "/api/v1/users/me", token=actor["token"])
assert me["status"] in (401, 503)
finally:
_compose("start", "redis")
_wait_ready()
def test_postgres_stop_returns_503():
# Maintainer remark (level 4): cover PostgreSQL unavailability like Redis.
if os.environ.get("RUN_DEPS_TEST") != "1":
print("SKIP test_postgres_stop_returns_503 (set RUN_DEPS_TEST=1)")
return
actor = register("deps_pg")
_compose("stop", "postgres")
time.sleep(2)
try:
ready = call("GET", "/health/ready")
assert ready["status"] == 503, ready["status"]
# Authenticated business path must fail fast as 503 (not hang / not 500).
me = call("GET", "/api/v1/users/me", token=actor["token"])
assert me["status"] == 503, me["status"]
hist = call(
"GET",
f"/api/v1/chats/{actor['id']}/messages",
token=actor["token"],
)
assert hist["status"] in (400, 404, 503), hist["status"]
finally:
_compose("start", "postgres")
_wait_ready(90)