#!/usr/bin/env python3 """Жизненный цикл ЛР 2: данные и сессии переживают перезапуск всего стенда (API, PostgreSQL, Valkey). Нужен запущенный compose-стенд; перезапуск делает scripts/restart.sh (volumes сохраняются).""" import os import sys import uuid import test_lab2 as api from test_sigterm import ROOT, run, wait_ready def compose_logs(): return run("docker", "compose", "--project-directory", str(ROOT), "--env-file", str(ROOT / ".env"), "logs", "api", "--no-color").stdout def main(): api.BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/") wait_ready(api.BASE_URL) alice = api.create_user("lifealice") bob = api.create_user("lifebob") outsider = api.create_user("lifeoutsider") chat = api.create_chat(alice, [alice, bob], "Lifecycle test") texts = ["private-lifecycle-" + uuid.uuid4().hex for _ in range(2)] sent = [api.create_message(user, chat, text) for user, text in zip((alice, bob), texts)] path = f"/api/v1/chats/{chat['id']}/messages" page = api.request("GET", path, 200, headers=api.auth(bob))["json"] if [m["id"] for m in page["items"]] != [m["id"] for m in sent]: raise AssertionError("Created messages are missing or reordered") print("PASS two users created and read two messages: HTTP 201, then HTTP 200") api.request("GET", path, 404, headers=api.auth(outsider)) api.request("POST", path, 404, headers=api.auth(outsider), body={"text": "Forbidden"}) print("PASS third user cannot read or write the chat: HTTP 404") logs = compose_logs() if any(text in logs for text in texts): raise AssertionError("Message contents leaked into container logs") if "req_id=" not in logs or "with status 201" not in logs: raise AssertionError("Request logs are missing") print("PASS request logs include IDs and statuses, without message contents") print("Command: scripts/restart.sh (API + PostgreSQL + Valkey, volumes kept)", flush=True) run(str(ROOT / "scripts" / "restart.sh"), timeout=120) wait_ready(api.BASE_URL, timeout=90) # те же токены, те же данные api.request("GET", "/api/v1/users/me", 200, headers=api.auth(alice)) after = api.request("GET", path, 200, headers=api.auth(bob))["json"] if after["items"] != page["items"]: raise AssertionError("History changed after restart") api.request("GET", path, 404, headers=api.auth(outsider)) print("PASS after restart: same tokens read the same history") api.request("DELETE", "/api/v1/auth/sessions/current", 204, headers=api.auth(alice)) api.request("GET", path, 401, headers=api.auth(alice)) api.request("GET", path, 200, headers=api.auth(bob)) print("PASS logout revokes only alice's session; bob's session still works") print("PASS persistent lifecycle: data and sessions survive full restart") if __name__ == "__main__": try: main() except Exception as exc: print(f"FAIL: {type(exc).__name__}: {exc}", file=sys.stderr) sys.exit(1)