Files

164 lines
6.6 KiB
Python

"""Unit tests for the ``background-shells`` plugin: manifest, handlers (mocking
the hub's ``conversations.tasks`` bridge), and UI assets."""
from __future__ import annotations
import http.server
import json
import os
import pathlib
import subprocess
import sys
import threading
import unittest
ROOT = pathlib.Path(__file__).resolve().parent.parent
HANDLERS = ROOT / "handlers"
class FakeHub:
def __init__(self):
self.requests: list[tuple[str, str]] = []
self.routes: dict[tuple[str, str], tuple[int, dict]] = {}
parent = self
class Handler(http.server.BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def _handle(self, method: str):
parent.requests.append((method, self.path))
length = int(self.headers.get("Content-Length") or 0)
if length:
self.rfile.read(length)
key = (method, self.path)
status, body = parent.routes.get(key, (404, {"error": {"message": "not found"}}))
raw = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def do_GET(self):
self._handle("GET")
def do_POST(self):
self._handle("POST")
self.srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self.url = f"http://127.0.0.1:{self.srv.server_address[1]}"
self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True)
self.thread.start()
def close(self):
self.srv.shutdown()
self.srv.server_close()
def run_handler(name: str, payload: dict, hub_url: str) -> subprocess.CompletedProcess:
env = {
"PATH": os.environ.get("PATH", ""),
"AIA_TOOLS_URL": hub_url,
"AIA_TOOLS_TOKEN": "aiah1.owner.background-shells.0.sig",
"AIA_PLUGIN_ID": "background-shells",
}
return subprocess.run(
[sys.executable, str(HANDLERS / f"{name}.py")],
input=json.dumps(payload),
text=True,
capture_output=True,
env=env,
timeout=10,
)
class PluginTest(unittest.TestCase):
def setUp(self):
self.hub = FakeHub()
def tearDown(self):
self.hub.close()
def test_manifest_and_assets_present(self):
mf = json.loads((ROOT / "plugin.json").read_text(encoding="utf-8"))
self.assertEqual(mf["id"], "background-shells")
self.assertTrue(mf["seed"])
self.assertTrue(mf["managed"]["defaultForGuests"])
self.assertEqual(mf["capabilities"], ["conversations.tasks"])
self.assertTrue((ROOT / "icon.svg").is_file())
self.assertTrue((ROOT / "illustration.webp").is_file())
self.assertTrue((ROOT / "README.md").is_file())
for sl in mf["ui"]["slots"]:
self.assertTrue((ROOT / sl["html"]).is_file(), sl["html"])
for tc in mf["ui"]["toolCards"]:
self.assertTrue((ROOT / tc["html"]).is_file(), tc["html"])
for act in mf["actions"].values():
self.assertTrue((ROOT / act["script"]).is_file(), act["script"])
def test_agy_schedule_gets_the_wakeup_card(self):
"""agy's ``schedule`` timer (``agy:schedule``, ``{delaySeconds, prompt}``
from the harness-agy mirror) draws like ScheduleWakeup."""
mf = json.loads((ROOT / "plugin.json").read_text(encoding="utf-8"))
cards = {tc["id"]: tc for tc in mf["ui"]["toolCards"]}
self.assertEqual(cards["wakeup-agy"]["match"], {"tool": "agy:schedule"})
same = ("html", "replace", "bare", "inThread", "inThreadWhile", "vis")
self.assertEqual({k: cards["wakeup-agy"][k] for k in same},
{k: cards["wakeup"][k] for k in same})
html = (ROOT / "ui" / "wakeup.html").read_text(encoding="utf-8")
self.assertIn("background task", html) # agy's RUNNING answer isn't "rejected"
self.assertIn("CronExpression", html)
self.assertIn("Status: ", (ROOT / "ui" / "task-output.html").read_text(encoding="utf-8"))
def test_tasks_handler_returns_tasks_and_handles_404(self):
self.hub.routes[("GET", "/plugins/background-shells/hub/conversations/c1234567/tasks")] = (
200,
{
"sessionId": "s1",
"conversationId": "c1234567",
"running": True,
"canStop": True,
"taskStops": {},
"tasks": [{"taskId": "bsh1", "kind": "shell", "label": "Build"}],
},
)
r = run_handler("tasks", {"conversationId": "c1234567"}, self.hub.url)
self.assertEqual(r.returncode, 0, r.stderr)
data = json.loads(r.stdout)
self.assertTrue(data["found"])
self.assertEqual(data["tasks"][0]["taskId"], "bsh1")
r404 = run_handler("tasks", {"conversationId": "missing01"}, self.hub.url)
self.assertEqual(r404.returncode, 0, r404.stderr)
self.assertEqual(json.loads(r404.stdout)["found"], False)
def test_output_handler_clamps_lines_and_passes_through(self):
self.hub.routes[("GET", "/plugins/background-shells/hub/conversations/c1234567/tasks/bsh1/output?lines=200")] = (
200,
{"taskId": "bsh1", "available": True, "lines": ["ok"], "more": False, "end": None},
)
r = run_handler("output", {"conversationId": "c1234567", "taskId": "bsh1", "lines": 999}, self.hub.url)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(json.loads(r.stdout)["lines"], ["ok"])
def test_stop_handler_posts_and_surfaces_errors(self):
self.hub.routes[("POST", "/plugins/background-shells/hub/conversations/c1234567/tasks/bsh1/stop")] = (
200,
{"ok": True, "taskId": "bsh1", "forced": False},
)
r = run_handler("stop", {"conversationId": "c1234567", "taskId": "bsh1"}, self.hub.url)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(json.loads(r.stdout), {"ok": True, "taskId": "bsh1", "forced": False})
self.hub.routes[("POST", "/plugins/background-shells/hub/conversations/c1234567/tasks/bsh2/stop")] = (
403,
{"error": {"message": "read-only"}},
)
r_err = run_handler("stop", {"conversationId": "c1234567", "taskId": "bsh2"}, self.hub.url)
self.assertNotEqual(r_err.returncode, 0)
self.assertIn("read-only", r_err.stderr)
if __name__ == "__main__":
unittest.main()