Files

344 lines
17 KiB
Python

#!/usr/bin/env python3
"""Unit tests for the Diff viewer live plugin (stdlib only).
A fake hub (``http.server`` on 127.0.0.1) stands in for the ai-agent's
``diff.read`` bridges and for the ``commits`` plugin's exports; each handler
runs as a subprocess with the stripped env the hub gives it. Also: the
manifest through the hub's own validator (``AI_AGENT_DIR``/backend, default
~/projects/ai-agent; ``AI_AGENT_PYTHON`` = a python with its requirements —
skipped when it can't import it), the frames' scripts through ``node --check``
and a DOM-free smoke test of ``ui/src/diff-render.js``.
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
sys.dont_write_bytecode = True
ROOT = pathlib.Path(__file__).resolve().parent.parent
MANIFEST = json.loads((ROOT / "plugin.json").read_text())
TOKEN = "aiah1.owner.diff-viewer.123.sig"
CONV = "0193a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b"
def _file(path, add=1, dele=0, hunks=True):
return {"path": path, "oldPath": None, "status": "modified", "additions": add, "deletions": dele,
"binary": False, "truncated": False, "repo": "project:demo",
"hunks": [{"header": "@@ -1 +1 @@", "oldStart": 1, "oldLines": 1, "newStart": 1, "newLines": 1,
"lines": [{"type": "add", "text": "x", "oldNo": None, "newNo": 1}]}] if hunks else []}
CORE_COMMITS = { # newest first, as the core answers
"id": CONV, "repos": ["project:demo"], "filesChanged": 3, "additions": 5, "deletions": 1, "exact": True, "worker": None,
"commits": [
{"sha": "b" * 40, "short": "bbbbbbb", "subject": "second", "additions": 3, "deletions": 1, "files": 2, "source": "hook"},
{"sha": "a" * 40, "short": "aaaaaaa", "subject": "first", "additions": 2, "deletions": 0, "files": 1, "source": "output"},
]}
PEER_LIST = {"worker": "mac", "commits": [
{"sha": "c" * 40, "short": "ccccccc", "subject": "one", "additions": 4, "deletions": 2, "files": 1, "source": "shim", "root": "/w/r"},
{"sha": "d" * 40, "short": "ddddddd", "subject": "Merge branch 'x'", "additions": 50, "deletions": 9, "files": 9, "merge": True},
{"sha": "e" * 40, "short": "eeeeeee", "subject": "two", "additions": 1, "deletions": 0, "files": 1, "source": "shim"},
]}
DIFF = {"title": "t", "files": [_file("a.py", 2, 1), _file("b.py")], "additions": 3, "deletions": 1}
class _Hub(BaseHTTPRequestHandler):
seen: list = []
peer_status = 200
core_status = 200
def _auth(self) -> bool:
if self.headers.get("Authorization") != f"Bearer {TOKEN}":
self._send(401, {"error": {"message": "unknown token", "kind": "auth"}})
return False
return True
def do_GET(self):
_Hub.seen.append(("GET", self.path))
if not self._auth():
return
u = urllib.parse.urlparse(self.path)
q = dict(urllib.parse.parse_qsl(u.query))
base = f"/plugins/diff-viewer/hub/diff/conversations/{CONV}"
if _Hub.core_status != 200:
return self._send(_Hub.core_status, {"error": {"message": "conversation not found", "kind": "not_found"}})
if u.path == base + "/commits":
return self._send(200, CORE_COMMITS)
if u.path == base + "/commit":
return self._send(200, {**DIFF, "title": f"core {q.get('sha')} {q.get('root')}"})
if u.path == base + "/uncommitted":
return self._send(200, {**DIFF, "title": f"unc stats={q.get('stats')}",
"worktrees": [{"dir": "wt", "branch": "feat", "repo": "project:demo"}]})
if u.path == base + "/aggregate":
return self._send(200, {**DIFF, "title": "aggregate", "approx": True})
if u.path == "/plugins/diff-viewer/hub/diff/commit":
return self._send(200, {**DIFF, "title": f"repo {q.get('repo')} {q.get('sha')}"})
self._send(404, {"error": {"message": "no route", "kind": "not_found"}})
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
body = json.loads(self.rfile.read(n) or b"{}")
_Hub.seen.append(("POST", self.path, body))
if not self._auth():
return
if _Hub.peer_status != 200:
return self._send(_Hub.peer_status, {"error": {"message": "peer broke", "kind": "error"}})
if self.path == "/plugins/commits/actions/list":
return self._send(200, PEER_LIST)
if self.path == "/plugins/commits/actions/diff":
return self._send(200, {**DIFF, "title": f"peer {body.get('sha')}"})
self._send(404, {"error": {"message": "no action", "kind": "not_found"}})
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 Base(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.seen, _Hub.peer_status, _Hub.core_status = [], 200, 200
self.data = tempfile.mkdtemp(prefix="dv-data-")
self.addCleanup(shutil.rmtree, self.data, True)
def act(self, name, payload, active=()):
script = ROOT / MANIFEST["actions"][name]["script"]
env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "AIA_TOOLS_URL": self.url, "AIA_TOOLS_TOKEN": TOKEN,
"AIA_PLUGIN_ID": "diff-viewer", "AIA_PLUGIN_DIR": str(ROOT), "AIA_PLUGIN_DATA_DIR": self.data,
"AIA_PLUGIN_CONFIG": "{}", "AIA_ACTIVE_PLUGINS": json.dumps(list(active)),
"AIA_USER_CONTEXT": json.dumps({"uid": "owner", "isOwner": True})}
r = subprocess.run([sys.executable, "-I", str(script)], input=json.dumps(payload), capture_output=True,
text=True, env=env, timeout=30)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertFalse((ROOT / "handlers" / "__pycache__").exists(), "no bytecode written into the plugin")
return json.loads(r.stdout)
class TestDiffActions(Base):
def test_commits_from_core_oldest_first_with_uncommitted(self):
out = self.act("commits", {"conversationId": CONV, "uncommitted": True})
self.assertEqual([c["subject"] for c in out["commits"]], ["first", "second"])
self.assertEqual(out["via"], "core")
self.assertEqual((out["additions"], out["deletions"]), (5, 1))
self.assertEqual(len(out["uncommitted"]["files"]), 2)
self.assertNotIn("hunks", out["uncommitted"]["files"][0])
self.assertEqual(out["uncommitted"]["worktrees"][0]["branch"], "feat")
self.assertIn(("GET", f"/plugins/diff-viewer/hub/diff/conversations/{CONV}/uncommitted?stats=1"), _Hub.seen)
def test_commits_without_uncommitted_asks_once(self):
out = self.act("commits", {"conversationId": CONV})
self.assertNotIn("uncommitted", out)
self.assertEqual(len(_Hub.seen), 1)
def test_commits_from_the_commits_plugin(self):
out = self.act("commits", {"conversationId": CONV}, active=["commits"])
self.assertEqual(out["via"], "commits")
self.assertEqual([c["short"] for c in out["commits"]], ["ccccccc", "ddddddd", "eeeeeee"])
self.assertEqual((out["additions"], out["deletions"], out["filesChanged"]), (5, 2, 2)) # the merge left out
self.assertEqual(out["worker"], "mac")
post = [s for s in _Hub.seen if s[0] == "POST"]
self.assertEqual(post[0][2], {"conversationId": CONV})
def test_commits_plugin_failing_falls_back_to_core(self):
_Hub.peer_status = 500
out = self.act("commits", {"conversationId": CONV}, active=["commits"])
self.assertEqual(out["via"], "core")
self.assertEqual(len(out["commits"]), 2)
def test_commit_diff_core_with_root(self):
out = self.act("commit", {"conversationId": CONV, "sha": "a" * 7, "root": "/w/r"})
self.assertEqual(out["title"], "core aaaaaaa /w/r")
def test_commit_diff_from_the_commits_plugin(self):
out = self.act("commit", {"conversationId": CONV, "sha": "c" * 40}, active=["commits"])
self.assertEqual(out["title"], "peer " + "c" * 40)
_Hub.peer_status = 404
out = self.act("commit", {"conversationId": CONV, "sha": "c" * 40}, active=["commits"])
self.assertTrue(out["title"].startswith("core "))
def test_uncommitted_full_and_stats(self):
full = self.act("uncommitted", {"conversationId": CONV})
self.assertEqual(full["title"], "unc stats=0")
self.assertTrue(full["files"][0]["hunks"])
stats = self.act("uncommitted", {"conversationId": CONV, "stats": True})
self.assertNotIn("hunks", stats["files"][0])
self.assertEqual(stats["additions"], 3)
def test_aggregate_and_repo_commit(self):
self.assertEqual(self.act("aggregate", {"conversationId": CONV})["title"], "aggregate")
out = self.act("repo-commit", {"repo": "project:demo", "sha": "abc1234"})
self.assertEqual(out["title"], "repo project:demo abc1234")
self.assertEqual(self.act("repo-commit", {"repo": "super:_", "sha": "abc1234"})["title"], "repo super:_ abc1234")
def test_bad_input_is_a_400(self):
for name, p in (("commits", {}), ("commits", {"conversationId": "../x"}),
("commit", {"conversationId": CONV, "sha": "zz"}),
("repo-commit", {"repo": "file:/etc", "sha": "abc1234"}),
("repo-commit", {"repo": "project:demo", "sha": "HEAD"})):
out = self.act(name, p)
self.assertEqual(out["_error"]["status"], 400, (name, p, out))
self.assertEqual(_Hub.seen, [])
def test_hub_404_passes_through(self):
_Hub.core_status = 404
out = self.act("aggregate", {"conversationId": CONV})
self.assertEqual(out["_error"]["status"], 404)
self.assertEqual(out["_error"]["kind"], "not_found")
self.assertIn("not found", out["_error"]["message"])
def test_no_hub(self):
script = ROOT / MANIFEST["actions"]["aggregate"]["script"]
r = subprocess.run([sys.executable, "-I", str(script)], input=json.dumps({"conversationId": CONV}),
capture_output=True, text=True, env={"PATH": "/usr/bin:/bin"}, timeout=30)
self.assertEqual(json.loads(r.stdout)["_error"]["kind"], "config")
class TestReview(Base):
def save(self, **op):
return self.act("review-save", {"conversationId": CONV, **op})
def test_empty(self):
self.assertEqual(self.act("review", {"conversationId": CONV}), {"viewed": {}, "comments": [], "touched": 0})
def test_viewed_ticks(self):
r = self.save(op="viewed", file="project:demo|a.py", sig="2/1/1/abc")
self.assertEqual(r["viewed"], {"project:demo|a.py": "2/1/1/abc"})
self.save(op="viewed", file="project:demo|b.py", sig="1/0/1/x")
r = self.save(op="viewed", file="project:demo|a.py", sig=None)
self.assertEqual(r["viewed"], {"project:demo|b.py": "1/0/1/x"})
self.assertEqual(self.act("review", {"conversationId": CONV})["viewed"], r["viewed"])
def test_comments(self):
line = {"side": "new", "no": 12, "text": "x = 1", "type": "add"}
r = self.save(op="add", comment={"id": "cabc123", "file": "project:demo|a.py", "path": "a.py", "view": "all",
"body": "why?", "line": line})
self.assertEqual(r["comments"][0]["line"], line)
r = self.save(op="add", comment={"file": "project:demo|a.py", "path": "a.py", "view": "aaaaaaa", "body": "whole"})
self.assertEqual(len(r["comments"]), 2)
self.assertRegex(r["comments"][1]["id"], r"^c[0-9a-f]+$")
self.assertNotIn("line", r["comments"][1])
r = self.save(op="edit", id="cabc123", body="why not?")
self.assertEqual(r["comments"][0]["body"], "why not?")
r = self.save(op="delete", id="cabc123")
self.assertEqual([c["body"] for c in r["comments"]], ["whole"])
self.save(op="viewed", file="k", sig="s")
r = self.save(op="clear")
self.assertEqual((r["comments"], r["viewed"]), ([], {"k": "s"}))
r = self.save(op="reset")
self.assertEqual((r["comments"], r["viewed"]), ([], {}))
def test_bad_ops(self):
for op in ({"op": "nope"}, {"op": "add", "comment": {"file": "f", "path": "p", "body": " "}},
{"op": "add", "comment": "x"}, {"op": "viewed", "file": 3, "sig": "s"},
{"op": "add", "comment": {"file": "f", "path": "p", "body": "x" * 9000}}):
self.assertEqual(self.save(**op)["_error"]["status"], 400, op)
def test_one_file_per_conversation_and_pruning(self):
script = ROOT / MANIFEST["actions"]["review-save"]["script"]
sys.path.insert(0, str(script.parent))
try:
import _lib # noqa: PLC0415
finally:
sys.path.pop(0)
os.environ["AIA_PLUGIN_DATA_DIR"] = self.data
try:
for i in range(_lib.MAX_CONVS + 5):
_lib.save_review(f"conv-{i:03d}", {"op": "viewed", "file": "f", "sig": "s"})
p = pathlib.Path(self.data, "reviews", f"conv-{i:03d}.json")
os.utime(p, (1_000_000 + i, 1_000_000 + i))
finally:
del os.environ["AIA_PLUGIN_DATA_DIR"]
names = sorted(p.name for p in pathlib.Path(self.data, "reviews").glob("*.json"))
self.assertEqual(len(names), _lib.MAX_CONVS)
self.assertEqual(names[0], "conv-005.json")
class TestManifest(unittest.TestCase):
def test_shape(self):
m = MANIFEST
self.assertEqual(m["id"], "diff-viewer")
self.assertTrue(m["seed"])
self.assertTrue(m["managed"]["defaultForGuests"])
self.assertEqual(m["capabilities"], ["diff.read"])
self.assertEqual(m["optionalRequires"], ["commits"])
tab = next(s for s in m["ui"]["slots"] if s["where"] == "conversation.tab")
self.assertEqual((tab["id"], tab["label"], tab["legacyView"]), ("changes", "Changes", "changes"))
page = m["ui"]["pages"][0]
self.assertEqual((page["nav"], page["opens"]), ("none", ["commit", "conversation-diff"]))
for name, a in m["actions"].items():
self.assertTrue((ROOT / a["script"]).is_file(), name)
self.assertEqual(bool(a.get("readOnly")), name != "review-save", name)
for s in [*m["ui"]["slots"], *m["ui"]["pages"]]:
self.assertTrue((ROOT / s["html"]).is_file(), s["html"])
def test_hub_validator(self):
backend = pathlib.Path(os.path.expanduser(os.environ.get("AI_AGENT_DIR", "~/projects/ai-agent"))) / "backend"
py = os.environ.get("AI_AGENT_PYTHON", sys.executable)
if not (backend / "plugins" / "manifest.py").is_file():
self.skipTest(f"no ai-agent backend at {backend}")
code = ("import json, pathlib, sys; from plugins.manifest import validate_manifest; "
"print(json.dumps(validate_manifest(pathlib.Path(sys.argv[1]))))")
r = subprocess.run([py, "-c", code, str(ROOT)], cwd=backend, capture_output=True, text=True, timeout=60)
if r.returncode and ("ModuleNotFoundError" in r.stderr or "ImportError" in r.stderr):
self.skipTest("the hub's requirements aren't importable here (set AI_AGENT_PYTHON)")
self.assertEqual(r.returncode, 0, r.stderr[-2000:])
out = json.loads(r.stdout)
self.assertTrue(out.get("seed"))
self.assertEqual(out.get("optionalRequires"), ["commits"])
self.assertEqual(out["ui"]["pages"][0].get("opens"), ["commit", "conversation-diff"])
tab = next(s for s in out["ui"]["slots"] if s["id"] == "changes")
self.assertEqual((tab["where"], tab.get("legacyView")), ("conversation.tab", "changes"))
@unittest.skipUnless(shutil.which("node"), "node is not installed")
class TestFrames(unittest.TestCase):
def test_scripts_parse(self):
for js in sorted((ROOT / "ui" / "src").glob("*.js")):
r = subprocess.run(["node", "--check", str(js)], capture_output=True, text=True)
self.assertEqual(r.returncode, 0, f"{js.name}: {r.stderr}")
def test_renderer_smoke(self):
r = subprocess.run(["node", str(ROOT / "tests" / "smoke_render.js")], capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stderr)
def test_frames_are_built_from_src(self):
srcs = {p.name: p.read_text() for p in (ROOT / "ui" / "src").iterdir()}
for html, own in (("changes.html", "changes.js"), ("uncommitted.html", "uncommitted.js"), ("diff.html", "page.js")):
doc = (ROOT / "ui" / html).read_text()
for part in ("frames.css", "diff-render.js", "common.js", own):
self.assertIn(srcs[part], doc, f"ui/{html} is stale ({part}) — run ./build.sh")
self.assertNotRegex(doc, r"<script[^>]+src=|<link[^>]+href=", "a frame has no network")
if __name__ == "__main__":
unittest.main()