Files

231 lines
10 KiB
Python

#!/usr/bin/env python3
"""Unit tests for the Lifecycle checks live plugin (stdlib only).
A fake hub (``http.server`` on 127.0.0.1) stands in for the ai-agent's
``conversations.checks`` bridge; the ``checks`` handler runs as a subprocess
with the stripped env the hub gives it. The Details slot is rendered in jsdom
when a ``node_modules`` with jsdom is around (``AI_AGENT_DIR``/frontend,
default ~/projects/ai-agent).
python3 -m unittest discover -s tests
"""
from __future__ import annotations
import json
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
import threading
import unittest
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
ROOT = pathlib.Path(__file__).resolve().parent.parent
TESTS = ROOT / "tests"
MANIFEST = json.loads((ROOT / "plugin.json").read_text())
TOKEN = "aiah1.owner.lifecycle.123.sig"
CONV = "0193a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b"
SID = "aaaaaaaa-1111-4111-8111-111111111111"
ANSWER = {"sessionId": SID, "conversationId": CONV, "state": "finished",
"committed": "2026-11-27T09:05:00Z", "pushed": "2026-11-27T09:06:00Z",
"merged": None, "deployed": "2026-11-27T09:30:00Z", "notified": None}
class _Hub(BaseHTTPRequestHandler):
status = 200
body: dict = ANSWER
seen: list = []
def do_GET(self):
_Hub.seen.append(self.path)
if self.headers.get("Authorization") != f"Bearer {TOKEN}":
return self._send(401, {"error": {"message": "unknown token", "kind": "auth"}})
if _Hub.status != 200:
return self._send(_Hub.status, {"error": {"message": "plugin lacks conversations.checks capability",
"kind": "capability"}})
self._send(200, _Hub.body)
def _send(self, code, body):
raw = json.dumps(body).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def log_message(self, *a):
pass
class TestHandler(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.srv = ThreadingHTTPServer(("127.0.0.1", 0), _Hub)
threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
cls.url = f"http://127.0.0.1:{cls.srv.server_address[1]}"
@classmethod
def tearDownClass(cls):
cls.srv.shutdown()
def setUp(self):
_Hub.status, _Hub.body, _Hub.seen = 200, ANSWER, []
def run_action(self, payload, token=TOKEN, url=None):
script = ROOT / MANIFEST["actions"]["checks"]["script"]
with tempfile.TemporaryDirectory() as td:
env = {"PATH": "/usr/bin:/bin", "AIA_TOOLS_URL": url or self.url, "AIA_TOOLS_TOKEN": token,
"AIA_PLUGIN_ID": "lifecycle", "AIA_PLUGIN_DATA_DIR": td}
return subprocess.run([sys.executable, "-I", str(script)], input=json.dumps(payload),
capture_output=True, text=True, env=env, timeout=30)
def test_reads_the_conversation_first(self):
p = self.run_action({"conversationId": CONV, "sessionId": SID})
self.assertEqual(p.returncode, 0, p.stderr)
self.assertEqual(json.loads(p.stdout), {"found": True, **ANSWER})
self.assertEqual(urllib.parse.urlsplit(_Hub.seen[-1]).path,
f"/plugins/lifecycle/hub/conversations/{CONV}/checks")
def test_falls_back_on_the_session(self):
p = self.run_action({"conversationId": "../../x", "sessionId": SID})
self.assertEqual(p.returncode, 0, p.stderr)
self.assertEqual(_Hub.seen[-1], f"/plugins/lifecycle/hub/conversations/{SID}/checks")
def test_only_known_fields_go_out(self):
_Hub.body = {**ANSWER, "title": "secret", "pushed": 3, "state": ["x"]}
out = json.loads(self.run_action({"sessionId": SID}).stdout)
self.assertNotIn("title", out)
self.assertIsNone(out["pushed"])
self.assertIsNone(out["state"])
def test_unknown_is_not_found_not_an_error(self):
_Hub.status = 404
p = self.run_action({"sessionId": SID})
self.assertEqual(p.returncode, 0, p.stderr)
self.assertEqual(json.loads(p.stdout), {"found": False})
def test_errors_are_reported(self):
p = self.run_action({})
self.assertNotEqual(p.returncode, 0)
self.assertIn("which conversation", p.stderr)
self.assertEqual(_Hub.seen, [])
_Hub.status = 403
p = self.run_action({"sessionId": SID})
self.assertNotEqual(p.returncode, 0)
self.assertIn("conversations.checks", p.stderr)
p = self.run_action({"sessionId": SID}, url="http://127.0.0.1:9")
self.assertIn("didn't answer", p.stderr)
def _node_modules() -> pathlib.Path | None:
ai = pathlib.Path(os.path.expanduser(os.environ.get("AI_AGENT_DIR", "~/projects/ai-agent")))
for d in (ai / "frontend" / "node_modules", ROOT / "node_modules"):
if (d / "jsdom").is_dir():
return d
return None
NODE_MODULES = _node_modules()
@unittest.skipUnless(NODE_MODULES and shutil.which("node"), "no node + jsdom (AI_AGENT_DIR/frontend/node_modules)")
class TestSlot(unittest.TestCase):
def render(self, init, steps=(), fixtures=None):
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f:
json.dump(fixtures if fixtures is not None else {CONV: {"found": True, **ANSWER}}, f)
try:
p = subprocess.run(["node", str(TESTS / "render_harness.js"), str(ROOT / "ui" / "conv-checks.html"),
f.name, json.dumps(init), json.dumps(list(steps))],
capture_output=True, text=True, timeout=60,
env={**os.environ, "NODE_PATH": str(NODE_MODULES)})
finally:
os.unlink(f.name)
self.assertEqual(p.returncode, 0, p.stderr)
out = json.loads(p.stdout)
self.assertEqual(out["errors"], [])
return out
def test_the_row_as_the_core_drew_it(self):
out = self.render({"sessionId": SID, "conversationId": CONV})
self.assertEqual([(c["key"], c["lit"]) for c in out["checks"]], [
("committed", True), ("pushed", True), ("merged", False), ("deployed", True),
("notified", False), ("completed", True)])
titles = {c["key"]: c["title"] for c in out["checks"]}
self.assertRegex(titles["committed"], r"^Committed · (\d+(m|h|d|mo) ago|just now)$")
self.assertEqual(titles["merged"], "Merged: not yet")
self.assertEqual(titles["completed"], "Completed")
self.assertEqual(out["label"], "Lifecycle checks")
self.assertIs(out["empty"], False)
self.assertEqual(out["heights"][-1], 18)
self.assertEqual([c for c in out["calls"] if c[0] == "query"],
[["query", "checks", {"conversationId": CONV, "sessionId": SID}]])
def test_not_finished_leaves_completed_dark_in_french(self):
out = self.render({"sessionId": SID, "conversationId": CONV, "lang": "fr"},
fixtures={CONV: {"found": True, **ANSWER, "state": "running"}})
titles = {c["key"]: (c["lit"], c["title"]) for c in out["checks"]}
self.assertEqual(titles["completed"], (False, "Terminé : pas encore"))
self.assertRegex(titles["deployed"][1], r"^Déployé · (il y a|à l'instant)")
self.assertEqual(out["label"], "Étapes du cycle de vie")
def test_unknown_conversation_folds_away(self):
out = self.render({"sessionId": SID, "conversationId": CONV}, fixtures={})
self.assertEqual(out["checks"], [])
self.assertIs(out["empty"], True)
self.assertEqual(out["heights"][-1], 0)
none = self.render({})
self.assertIs(none["empty"], True)
self.assertEqual(none["calls"], [])
def test_a_meta_event_for_this_session_reads_again(self):
steps = [{"fixture": {CONV: {"found": True, **ANSWER, "merged": "2026-11-27T10:00:00Z"}}},
{"event": {"type": "meta", "id": "someone-else"}},
{"event": {"type": "meta", "id": SID}},
{"wait": 600}]
out = self.render({"sessionId": SID, "conversationId": CONV}, steps)
self.assertEqual(sum(1 for c in out["calls"] if c[0] == "refresh"), 1)
self.assertTrue(next(c for c in out["checks"] if c["key"] == "merged")["lit"])
def test_transcript_events_are_throttled_and_running_flips_read(self):
steps = [{"event": {"type": "transcript", "ids": [CONV]}}, {"wait": 600}]
out = self.render({"sessionId": SID, "conversationId": CONV}, steps)
self.assertEqual(sum(1 for c in out["calls"] if c[0] == "refresh"), 0) # ≥ 10 s after the last read
steps = [{"update": {"running": False}}, {"wait": 600}]
out = self.render({"sessionId": SID, "conversationId": CONV, "update": {"running": True}}, steps)
self.assertEqual(sum(1 for c in out["calls"] if c[0] == "refresh"), 1)
class TestPackage(unittest.TestCase):
def test_manifest(self):
self.assertEqual(MANIFEST["id"], "lifecycle")
self.assertEqual(MANIFEST["capabilities"], ["conversations.checks"])
self.assertRegex(MANIFEST["color"], r"^#[0-9a-f]{6}$")
# the id core's DETAIL_CARD_RENAMES maps the retired `checks` card onto
self.assertEqual([(s["id"], s["where"]) for s in MANIFEST["ui"]["slots"]],
[("conv-checks", "conversation.details")])
self.assertIs(MANIFEST["actions"]["checks"].get("readOnly"), True)
for f in ("README.md", "icon.svg", "illustration.webp", MANIFEST["actions"]["checks"]["script"],
*(s["html"] for s in MANIFEST["ui"]["slots"])):
self.assertTrue((ROOT / f).is_file(), f)
self.assertTrue(os.access(ROOT / MANIFEST["actions"]["checks"]["script"], os.X_OK))
def test_icon_is_a_plain_24px_glyph(self):
svg = (ROOT / "icon.svg").read_text()
self.assertIn('viewBox="0 0 24 24"', svg)
self.assertIn('stroke="currentColor"', svg)
for bad in ("<script", "foreignObject", "href", "data:", " on"):
self.assertNotIn(bad, svg)
def test_the_slot_calls_no_network_itself(self):
html = (ROOT / "ui" / "conv-checks.html").read_text()
for bad in ("fetch(", "XMLHttpRequest", "http://", "https://", "<script src"):
self.assertNotIn(bad, html)
if __name__ == "__main__":
unittest.main()