Files

139 lines
6.1 KiB
Python

#!/usr/bin/env python3
"""Unit tests for the Context editor live plugin (stdlib only).
A fake hub stands in for the ai-agent's ``context.read`` / ``context.write``
bridges; the handlers run as subprocesses with the stripped env the hub
gives them and a throwaway data dir for the drafts.
python3 plugins/context-editor/tests/test_context_editor.py
"""
from __future__ import annotations
import json
import os
import pathlib
import subprocess
import sys
import tempfile
import threading
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
HERE = pathlib.Path(__file__).resolve().parent.parent
TOKEN = "aiah1.owner.context-editor.1.sig"
DISK = {"CLAUDE.md": "# Root\n", "data/log.md": "# log\n"}
WRITES: list[dict] = []
class Hub(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def _send(self, code, body):
b = json.dumps(body).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def _entry(self, path):
return {"path": path, "name": path.split("/")[-1], "kind": "claude-md", "tokens": 3, "cost": 0.00001,
"estimated": False, "editable": not path.startswith("data/"), "content": DISK[path]}
def do_GET(self):
u = urlparse(self.path)
q = {k: v[0] for k, v in parse_qs(u.query).items()}
if self.headers.get("Authorization") != f"Bearer {TOKEN}":
return self._send(401, {"error": {"message": "no token", "kind": "auth"}})
if u.path.endswith("/hub/context/bundle"):
files = [{k: v for k, v in self._entry(p).items() if k != "content"} for p in DISK]
files[1]["estimated"] = True
return self._send(200, {"workspace": "/w", "files": files, "totals": {"files": 2, "tokens": 6, "cost": 0.00002}})
if u.path.endswith("/hub/context/file"):
p = q.get("path", "")
return self._send(200, self._entry(p)) if p in DISK else self._send(404, {"error": {"message": "not found", "kind": "not_found"}})
return self._send(404, {})
def do_PUT(self):
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}")
WRITES.append(body)
if body["path"].startswith("data/"):
return self._send(403, {"error": {"message": "not editable", "kind": "forbidden"}})
DISK[body["path"]] = body["content"]
return self._send(200, self._entry(body["path"]))
class ContextEditor(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]}"
cls.data = tempfile.mkdtemp()
@classmethod
def tearDownClass(cls):
cls.srv.shutdown()
def run_action(self, name, payload=None):
e = {"PATH": os.environ.get("PATH", ""), "AIA_TOOLS_URL": self.url, "AIA_TOOLS_TOKEN": TOKEN,
"AIA_PLUGIN_ID": "context-editor", "AIA_PLUGIN_DATA_DIR": self.data}
p = subprocess.run([sys.executable, "-I", str(HERE / "handlers" / f"{name}.py")],
input=json.dumps(payload or {}), capture_output=True, text=True, env=e, timeout=30)
self.assertEqual(p.returncode, 0, p.stderr)
return json.loads(p.stdout)
def test_manifest(self):
mf = json.loads((HERE / "plugin.json").read_text())
for name, a in mf["actions"].items():
self.assertTrue((HERE / a["script"]).is_file(), name)
self.assertTrue(a.get("ownerOnly"), name)
self.assertEqual(mf["ui"]["pages"][0]["opens"], ["context-file"])
self.assertTrue(mf["ui"]["pages"][0]["fill"])
self.assertNotIn("managed", mf) # the operator's only: no guest grant
for c in mf["commands"].values():
self.assertIn(c["action"], mf["actions"])
def test_bundle_rows_for_the_cli(self):
b = self.run_action("bundle")
rows = {f["path"]: f for f in b["files"]}
self.assertEqual(rows["CLAUDE.md"]["tok"], "3")
self.assertEqual(rows["data/log.md"]["tok"], "~3")
self.assertEqual(rows["CLAUDE.md"]["usd"], "0.0000")
def test_show_reads_the_text(self):
self.assertEqual(self.run_action("file", {"path": "CLAUDE.md"})["text"], DISK["CLAUDE.md"])
self.assertEqual(self.run_action("file", {"path": "nope.md"})["_error"]["status"], 404)
def test_paths_must_be_workspace_relative(self):
for bad in ("", "/etc/passwd", "../x", ".claude/../../x"):
self.assertEqual(self.run_action("file", {"path": bad})["_error"]["status"], 400, bad)
def test_drafts_follow_and_a_save_drops_its_draft(self):
self.run_action("draft", {"path": "CLAUDE.md", "content": "# Draft\n"})
self.run_action("draft", {"path": ".claude/skills/x/SKILL.md", "content": "x"})
self.assertEqual(self.run_action("drafts")["drafts"]["CLAUDE.md"], "# Draft\n")
saved = self.run_action("save", {"path": "CLAUDE.md", "content": "# Draft\n"})
self.assertEqual(saved["content"], "# Draft\n")
ds = self.run_action("drafts")["drafts"]
self.assertNotIn("CLAUDE.md", ds)
self.assertIn(".claude/skills/x/SKILL.md", ds)
self.run_action("draft", {"path": ".claude/skills/x/SKILL.md", "content": None})
self.assertEqual(self.run_action("drafts")["drafts"], {})
def test_a_refused_save_keeps_the_draft(self):
self.run_action("draft", {"path": "data/log.md", "content": "hacked"})
r = self.run_action("save", {"path": "data/log.md", "content": "hacked"})
self.assertEqual(r["_error"]["status"], 403)
self.assertIn("data/log.md", self.run_action("drafts")["drafts"])
self.run_action("draft", {"path": "data/log.md", "content": None})
def test_bad_draft(self):
self.assertEqual(self.run_action("draft", {"path": "CLAUDE.md", "content": 3})["_error"]["status"], 400)
if __name__ == "__main__":
unittest.main()