Files
mtusi2026lab2-fork/student-tests/check_dependencies.py

97 lines
3.6 KiB
Python

import base64
from concurrent.futures import ThreadPoolExecutor
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, Failure, check
def compose(*args):
subprocess.run(["docker", "compose", *args], check=True, timeout=45,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def ready(client):
deadline = time.monotonic() + 30
while True:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
if time.monotonic() >= deadline:
raise
time.sleep(0.25)
def main():
client = Client(timeout=4)
actor = client.user("deps")
path = "/api/v1/users/me"
client.call("GET", path, actor=actor, schema="User")
deadline = time.monotonic() + 5
while True:
cached = subprocess.check_output(
["docker", "compose", "exec", "-T", "cache", "redis-cli",
"EXISTS", f"user:v1:{actor['id']}"],
text=True, timeout=5,
).strip()
if cached == "1":
break
check(time.monotonic() < deadline, "profile was not cached")
time.sleep(0.1)
print("PASS: Redis contains the profile entry", flush=True)
wrong = base64.b64encode((actor["user"]["username"] + ":wrong-password").encode()).decode()
client.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + wrong})
client.call("GET", path, 401, headers={"X-User-Id": actor["id"]})
body = {**actor["registration"], "username": "race_" + uuid.uuid4().hex[:16]}
def register(_):
return Client().call("POST", "/api/v1/users", [201, 409], body=body)["status"]
with ThreadPoolExecutor(max_workers=4) as pool:
results = list(pool.map(register, range(4)))
check(sorted(results) == [201, 409, 409, 409], f"registration race: {results}")
before = client.call("GET", "/api/v1/chats", actor=actor, schema="ChatPage")["json"]
client.call("POST", "/api/v1/chats", 400, actor=actor, body={
"title": "Rollback", "member_ids": [actor["id"], str(uuid.uuid4())],
})
after = client.call("GET", "/api/v1/chats", actor=actor, schema="ChatPage")["json"]
check(before == after, "partial chat survived rollback")
print("PASS: wrong password, X-User-Id rejected, concurrent registration, chat rollback", flush=True)
for service, status in (("cache", 200), ("db", 503)):
compose("stop", service)
try:
client.call("GET", path, status, actor=actor, schema="User" if status == 200 else None)
client.call("GET", path, 401)
finally:
compose("start", service)
ready(client)
print(f"PASS: {service} stopped, authenticated GET returned {status}", flush=True)
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor)
client.call("GET", path, 401, actor=actor)
env = dict(os.environ, SESSION_TTL_SECONDS="2")
command = ["docker", "compose", "up", "-d", "--no-deps", "--force-recreate", "api"]
subprocess.run(command, env=env, check=True, timeout=45, stdout=subprocess.DEVNULL)
try:
ready(client)
short_session = client.user("expiry")
client.call("GET", path, actor=short_session, schema="User")
time.sleep(2.2)
client.call("GET", path, 401, actor=short_session)
finally:
compose("up", "-d", "--no-deps", "--force-recreate", "api")
ready(client)
print("PASS: logout and 2-second session expiry")
if __name__ == "__main__":
main()