#!/usr/bin/env python3 """Verify that user, session and message survive a full service restart.""" import os import subprocess import sys import time import uuid from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) import urllib.request import urllib.error import json import base64 def http(method, url, body=None, headers=None, expect=None): h = {"Accept": "application/json"} if headers: h.update(headers) raw = None if body is not None: raw = json.dumps(body, ensure_ascii=False).encode("utf-8") h["Content-Type"] = "application/json" req = urllib.request.Request(url, data=raw, headers=h, method=method) try: resp = urllib.request.urlopen(req, timeout=10) except urllib.error.HTTPError as e: resp = e data = resp.read() if expect is not None: assert resp.status == expect, f"{method} {url}: got {resp.status}, want {expect}" return resp.status, json.loads(data) if data else None def wait_ready(base, timeout=90): deadline = time.monotonic() + timeout while time.monotonic() < deadline: try: s, _ = http("GET", base + "/health/ready") if s == 200: return except Exception: pass time.sleep(1) raise SystemExit("ready timeout") def main(): base = os.environ.get("BASE_URL", "http://127.0.0.1:8080") action = os.environ.get("ACTION_SCRIPT") if not action: print("FAIL: ACTION_SCRIPT not set") sys.exit(1) u = "persist_" + uuid.uuid4().hex[:8] pwd = "SuperSecretPassword123" s, user = http("POST", base + "/api/v1/users", body={"username": u, "display_name": "P", "password": pwd}, expect=201) alice_id = user["id"] cred = base64.b64encode(f"{u}:{pwd}".encode()).decode() s, sess = http("POST", base + "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred}, expect=201) token = sess["token"] s, chat = http("POST", base + "/api/v1/chats", body={"title": "P", "member_ids": [alice_id]}, headers={"Authorization": "Bearer " + token}, expect=201) s, msg = http("POST", base + f"/api/v1/chats/{chat['id']}/messages", body={"text": "persist"}, headers={"Authorization": "Bearer " + token}, expect=201) print(f"created user={alice_id} msg={msg['id']}", file=sys.stderr) print(f"running action: {action}", file=sys.stderr) subprocess.run(action, shell=True, check=True) wait_ready(base) s, me = http("GET", base + "/api/v1/users/me", headers={"Authorization": "Bearer " + token}, expect=200) assert me["id"] == alice_id, "user id changed" s, hist = http("GET", base + f"/api/v1/chats/{chat['id']}/messages?limit=10", headers={"Authorization": "Bearer " + token}, expect=200) assert any(m["id"] == msg["id"] for m in hist["items"]), "message lost" print("PASS: persistence verified") if __name__ == "__main__": main()