Files

406 lines
20 KiB
Python

#!/usr/bin/env python3
"""Unit tests for the GitHub resource plugin: a pure-data plugin (no
handlers, no proxy) whose ``resources[]`` the hub's in-process registry
compiles. So the tests run the hub's own code on this manifest:
* ``backend/plugins/manifest.py`` — validation, art, settings;
* ``backend/plugins/resources.py`` — the compiled registry (URL matching,
ids, bare ``#123`` with ``githubRepo``, ``ignoreUrlRegex``, scope);
* ``backend/conversations/resources.py`` — the transcript miner running the
``gh pr`` tool extractors (title / state / draft / head branch).
Needs ``~/projects/ai-agent`` (``AI_AGENT_REPO`` overrides); the backend
parts are skipped when it is missing, the art and shape checks still run.
python3 -m unittest discover -s plugins/github/tests -p "test_*.py"
"""
from __future__ import annotations
import copy
import json
import os
import pathlib
import re
import sys
import types
import unittest
ROOT = pathlib.Path(__file__).resolve().parent.parent
AIA = pathlib.Path(os.environ.get("AI_AGENT_REPO") or pathlib.Path.home() / "projects" / "ai-agent")
BACKEND = AIA / "backend"
FIXTURE = BACKEND / "fixtures" / "resource_plugins" / "github" / "plugin.json"
HAVE_BACKEND = (BACKEND / "plugins" / "manifest.py").is_file()
if HAVE_BACKEND:
sys.path.insert(0, str(BACKEND)) # manifest.py imports cron.scheduler
from plugins import resources as plugin_resources # noqa: E402
from plugins.manifest import ManifestError, svg_problem, validate_manifest # noqa: E402
from conversations.resources import ResourceMiner # noqa: E402
needs_backend = unittest.skipUnless(HAVE_BACKEND, "ai-agent backend not on this machine")
REPO = "acme/widgets"
PR = f"https://github.com/{REPO}/pull/"
def raw() -> dict:
return json.loads((ROOT / "plugin.json").read_text())
_VALID: dict | None = None
def valid() -> dict:
global _VALID
if _VALID is None:
_VALID = validate_manifest(ROOT)
return copy.deepcopy(_VALID)
class FakeStore:
"""What ``plugins.resources.registry`` reads of a ``PluginStore``."""
def __init__(self, config: dict | None = None):
self.version = 1
self.config = dict(config or {})
def active_manifests(self, uid):
return [("github", valid(), dict(self.config))]
def reg(**config):
"""The registry as the hub builds it: settings never saved read as the
fields' defaults."""
return plugin_resources.registry(types.SimpleNamespace(plugin_store=FakeStore(config)))
def mine(*steps, **config):
"""Feed ``(command, result text)`` pairs (``result`` None = no result) to
a miner over this plugin and return its summary."""
m = ResourceMiner(reg(**config))
for i, (cmd, out) in enumerate(steps):
tid = f"t{i}"
m.feed_events([{"t": "tool_call", "tool": "shell", "id": tid,
"at": f"2026-11-26T10:00:{i:02d}Z", "input": {"command": cmd}}])
if out is not None:
m.feed_events([{"t": "tool_result", "toolCall": tid, "ok": True,
"at": f"2026-11-26T10:00:{i:02d}Z",
"text": out if isinstance(out, str) else json.dumps(out)}])
return m.summary()
def ids(summary) -> list[str]:
return sorted(r["id"] for r in summary["resourcesAuto"] if r.get("kind") == "pr")
# ── shape, without the backend ───────────────────────────────────────────────
class ShapeTest(unittest.TestCase):
def test_identity_and_tile(self):
m = raw()
self.assertEqual((m["schema"], m["id"], m["name"]), (1, "github", "GitHub"))
self.assertRegex(m["version"], r"^\d+\.\d+\.\d+$")
self.assertRegex(m["color"], r"^#[0-9a-f]{6}$")
self.assertEqual(m["icon"], "git-pull-request")
def test_pure_data_owner_plugin(self):
# No code, no upstream, no secrets, nothing offered to guests.
m = raw()
for k in ("actions", "proxy", "secrets", "managed", "schedules", "webhooks",
"events", "skill", "capabilities", "ui"):
self.assertNotIn(k, m, k)
self.assertFalse(any(ROOT.glob("handlers/*")))
def test_scope_settings_default_to_every_conversation(self):
f = {x["key"]: x for x in raw()["settings"]["fields"]}
self.assertEqual(set(f), {"githubRepo", "workers", "cwdGlobs", "notifPills"})
self.assertEqual((f["workers"]["type"], f["workers"]["default"]), ("list", []))
self.assertEqual((f["cwdGlobs"]["type"], f["cwdGlobs"]["default"]), ("list", []))
self.assertEqual((f["notifPills"]["type"], f["notifPills"]["default"]), ("checkbox", False))
self.assertEqual((f["githubRepo"]["type"], f["githubRepo"]["default"]), ("text", ""))
for x in f.values():
self.assertTrue(x.get("label") and x.get("help"), x["key"])
self.assertLessEqual(len(x["help"]), 300, x["key"])
def test_pr_resource_declaration(self):
(r,) = raw()["resources"]
self.assertEqual((r["id"], r["label"], r["priority"], r["hueRole"], r["clickAction"]),
("pr", "Pull request", 20, "shade", "open"))
self.assertEqual(r["stateTones"],
{"open": "emerald", "draft": "zinc", "merged": "violet", "closed": "rose"})
tools = [(x["tool"], bool(x.get("tagOnCall")), bool(x.get("titleFields")))
for x in r["toolExtractors"]]
self.assertEqual(tools, [("shell", True, False), ("shell", False, True)])
@unittest.skipUnless(FIXTURE.is_file(), "ai-agent fixture not on this machine")
def test_resources_match_the_validated_reference_fixture(self):
# The hub's own tests run on the fixture: the shipped plugin must not drift.
self.assertEqual(raw()["resources"], json.loads(FIXTURE.read_text())["resources"])
def test_regexes_compile_without_nested_quantifiers(self):
(r,) = raw()["resources"]
pats = [r["urlRegex"], r["idRegex"], r["ignoreUrlRegex"]] + \
[x["commandRegex"] for x in r["toolExtractors"]]
for p in pats:
re.compile(p)
self.assertIsNone(re.search(r"\([^()]*[+*][^()]*\)[+*]", p), p)
# ── art ──────────────────────────────────────────────────────────────────────
class ArtTest(unittest.TestCase):
def test_icon_svg_is_inert_24px_currentcolor(self):
svg = (ROOT / "icon.svg").read_text()
self.assertIn('viewBox="0 0 24 24"', svg)
self.assertIn('stroke="currentColor"', svg)
self.assertIn('fill="none"', svg)
low = svg.lower()
for bad in ("<script", "foreignobject", "href", "data:", "http://", "url(", "<image", "<style"):
self.assertNotIn(bad, low.replace("http://www.w3.org/2000/svg", ""), bad)
self.assertIsNone(re.search(r"\son\w+\s*=", low))
self.assertLess(len(svg.encode()), 4096)
@needs_backend
def test_icon_passes_the_hub_svg_check(self):
self.assertIsNone(svg_problem((ROOT / "icon.svg").read_bytes()))
def test_illustration_is_a_small_webp(self):
p = ROOT / "illustration.webp"
b = p.read_bytes()
self.assertEqual((b[:4], b[8:12]), (b"RIFF", b"WEBP"))
self.assertLess(len(b), 200 * 1024)
def test_readme_is_short(self):
lines = [x for x in (ROOT / "README.md").read_text().splitlines() if x.strip()]
self.assertLessEqual(len(lines), 12)
text = " ".join(lines)
for word in ("githubRepo", "workers", "cwdGlobs", "gh pr view", "polls"):
self.assertIn(word, text)
# ── the hub's validator ──────────────────────────────────────────────────────
@needs_backend
class ManifestTest(unittest.TestCase):
def test_validates_with_its_art(self):
m = valid()
self.assertEqual(m["id"], "github")
self.assertEqual(m["color"], raw()["color"])
self.assertEqual((m["iconSvg"], m["illustration"], m["readme"]),
("icon.svg", "illustration.webp", "README.md"))
self.assertEqual(m["actions"], {})
self.assertEqual(m["secrets"], [])
(r,) = m["resources"]
self.assertEqual((r["id"], r["priority"], r["hueRole"]), ("pr", 20, "shade"))
self.assertEqual(len(r["toolExtractors"]), 2)
def test_a_nested_quantifier_is_refused(self):
import shutil
import tempfile
with tempfile.TemporaryDirectory() as d:
m = raw()
m["resources"][0]["urlRegex"] = "^https://github\\.com/(a+)+$"
(pathlib.Path(d) / "plugin.json").write_text(json.dumps(m))
shutil.copy(ROOT / "icon.svg", d)
with self.assertRaises(ManifestError):
validate_manifest(pathlib.Path(d))
def test_descriptor_for_the_app(self):
(d,) = reg().descriptors()
self.assertEqual(d, {"id": "pr", "label": "Pull request", "icon": "git-pull-request",
"color": "sky", "stateTones": raw()["resources"][0]["stateTones"],
"clickAction": "open", "priority": 20, "hueRole": "shade",
"pluginId": "github"})
# ── links and ids ────────────────────────────────────────────────────────────
@needs_backend
class MatchTest(unittest.TestCase):
def test_pr_urls(self):
r = reg()
for url, want in [
(PR + "42", "acme/widgets#42"),
(PR + "42/files", "acme/widgets#42"),
(PR + "42#issuecomment-1", "acme/widgets#42"),
("https://github.com/acme/widgets/pulls/7", "acme/widgets#7"),
("https://github.com/my.org/my-repo.js/pull/1234567", "my.org/my-repo.js#1234567"),
]:
hit = r.resolve_url(url)
self.assertIsNotNone(hit, url)
self.assertEqual((hit["kind"], hit["id"], hit["label"]), ("pr", want, "#" + want.split("#")[1]), url)
self.assertEqual(r.resolve_url(PR + "42/files")["url"], PR + "42")
def test_not_a_pr(self):
r = reg()
for url in ["https://github.com/acme/widgets",
"https://github.com/acme/widgets/issues/3",
"https://github.com/acme/widgets/pull/abc",
"https://gitlab.com/acme/widgets/pull/1",
"https://example.com/?u=https://github.com/acme/widgets/pull/1"]:
self.assertIsNone(r.resolve_url(url), url)
def test_ignore_url_regex_drops_other_github_links(self):
r = reg()
for url in ["https://github.com/acme/widgets",
"https://github.com/acme/widgets/blob/main/README.md",
"https://github.com/acme/widgets/commit/abc123",
"https://github.com/acme/widgets/actions/runs/1",
"https://github.com/acme"]:
self.assertTrue(r.ignored(url), url)
for url in [PR + "1", "https://github.com/acme/widgets/pulls/1",
"https://github.com/acme/widgets/issues/2",
"https://example.com/acme/widgets"]:
self.assertFalse(r.ignored(url), url)
# A stored raw link to a blob disappears instead of showing as a link.
self.assertIsNone(r.normalize({"kind": "url", "id": "u",
"url": "https://github.com/acme/widgets/blob/main/x"}))
def test_bare_number_without_a_default_repo_stays_partial(self):
hit = reg().parse_ref("#123")
self.assertEqual((hit["kind"], hit["id"], hit["label"]), ("pr", "#123", "#123"))
self.assertIsNone(hit["url"])
def test_bare_number_resolves_with_github_repo(self):
r = reg(githubRepo=REPO)
hit = r.parse_ref("#123")
self.assertEqual((hit["id"], hit["url"], hit["label"]), (REPO + "#123", PR + "123", "#123"))
# A full id keeps its own repo; a link names its repo over the setting.
self.assertEqual(r.parse_ref("other/repo#9")["url"], "https://github.com/other/repo/pull/9")
self.assertEqual(r.resolve_url("https://github.com/other/repo/pull/9")["id"], "other/repo#9")
# A recorded partial `#123` is completed at view time.
self.assertEqual(r.normalize({"kind": "pr", "id": "#123"})["id"], REPO + "#123")
def test_sticky_repo_beats_the_setting(self):
d = reg(githubRepo=REPO).by_kind["pr"]
self.assertEqual(d.from_id("#5", sticky={"repo": "seen/in-transcript"})["id"],
"seen/in-transcript#5")
def test_title_token_and_needles(self):
r = reg(githubRepo=REPO)
d, rec = r.by_kind["pr"], r.parse_ref("#77")
self.assertEqual(d.token(rec), "#77")
self.assertLessEqual({"#77", "pull/77", "pr 77", "pr #77"}, set(d.needle_list(rec)))
# ── gh pr tool calls ─────────────────────────────────────────────────────────
GH_VIEW = {"number": 42, "title": "Add the widget picker", "state": "OPEN", "isDraft": False,
"url": PR + "42", "headRefName": "feat/widget-picker",
"body": "Picker for widgets.\n\nCloses #40 and fixes ACME-12."}
@needs_backend
class ToolExtractorTest(unittest.TestCase):
def test_gh_pr_view_json(self):
s = mine(("gh pr view 42 --json title,state,isDraft,url,headRefName,body", GH_VIEW))
self.assertEqual(ids(s), [REPO + "#42"])
info = s["resourceInfo"][f"pr:{REPO}#42"]
self.assertEqual((info["title"], info["state"]), ("Add the widget picker", "open"))
# Head branch as is, then what the long body closes / fixes.
self.assertEqual(info["xref"], ["feat/widget-picker", "#40", "ACME-12"])
(rec,) = s["resourcesAuto"]
self.assertEqual((rec["title"], rec["state"], rec["url"]),
("Add the widget picker", "open", PR + "42"))
def test_draft_flag_wins_over_state(self):
s = mine(("gh pr view 42 --json title,state,isDraft,url", {**GH_VIEW, "isDraft": True}))
self.assertEqual(s["resourceInfo"][f"pr:{REPO}#42"]["state"], "draft")
def test_merged_and_closed_states(self):
for st in ("MERGED", "CLOSED"):
s = mine(("gh pr view 42 --json title,state,url", {**GH_VIEW, "state": st}))
self.assertEqual(s["resourceInfo"][f"pr:{REPO}#42"]["state"], st.lower())
def test_plain_text_gh_pr_view(self):
out = "title:\tFix the thing\nstate:\tMERGED\nnumber:\t7\nurl:\thttps://github.com/o/r/pull/7\n"
s = mine(("gh pr view 7 --repo o/r", out))
self.assertEqual(s["resourceInfo"]["pr:o/r#7"], {"title": "Fix the thing", "state": "merged"})
def test_repo_flag_forms(self):
for cmd in ("gh pr view 7 --repo o/r", "gh pr view 7 -R o/r", "gh pr view 7 --repo=o/r",
"gh pr view #7 -R o/r --json title"):
self.assertEqual(ids(mine((cmd, None))), ["o/r#7"], cmd)
def test_url_argument(self):
s = mine((f"gh pr view {PR}42 --json title,state", {"title": "T", "state": "OPEN"}))
self.assertEqual(ids(s), [REPO + "#42"])
self.assertEqual(s["resourceInfo"][f"pr:{REPO}#42"]["title"], "T")
def test_other_gh_pr_verbs_tag_on_call(self):
for verb in ("checks", "diff", "checkout", "merge", "review", "comment", "edit", "ready"):
s = mine((f"gh pr {verb} 9 -R o/r", "anything"))
self.assertEqual(ids(s), ["o/r#9"], verb)
self.assertNotIn("pr:o/r#9", s["resourceInfo"], verb) # only `view` is read
def test_not_a_pr_command(self):
for cmd in ("gh pr list", "gh pr create --title x", "gh issue view 3 -R o/r",
"echo gh pr", "ghx pr view 3", "gh pr view"):
self.assertEqual(ids(mine((cmd, None))), [], cmd)
def test_bare_view_without_repo_joins_a_later_link(self):
# `gh pr view 42` before any link: partial, completed by the repo seen later.
m = ResourceMiner(reg())
m.feed_events([{"t": "tool_call", "tool": "shell", "id": "a",
"input": {"command": "gh pr view 42 --json title"}}])
m.feed_events([{"t": "tool_result", "toolCall": "a", "text": json.dumps({"title": "T"})}])
m.feed_events([{"t": "tool_call", "tool": "shell", "id": "b",
"input": {"command": "gh pr checks 1 -R acme/widgets"}}])
s = m.summary()
self.assertIn(REPO + "#42", ids(s))
self.assertEqual(s["resourceInfo"][f"pr:{REPO}#42"]["title"], "T")
def test_miner_ignores_the_github_repo_setting(self):
# What the transcript says is stored; the setting fills in at view time.
self.assertEqual(ids(mine(("gh pr view 42", None), githubRepo=REPO)), ["#42"])
def test_failed_result_is_not_read(self):
m = ResourceMiner(reg())
m.feed_events([{"t": "tool_call", "tool": "shell", "id": "a",
"input": {"command": "gh pr view 7 -R o/r --json title"}}])
m.feed_events([{"t": "tool_result", "toolCall": "a", "ok": False,
"text": json.dumps({"title": "nope"})}])
self.assertNotIn("pr:o/r#7", m.summary()["resourceInfo"])
def test_non_shell_tools_are_ignored(self):
m = ResourceMiner(reg())
m.feed_events([{"t": "tool_call", "tool": "Read", "id": "a",
"input": {"command": "gh pr view 7 -R o/r"}}])
self.assertEqual(ids(m.summary()), [])
# ── scope ────────────────────────────────────────────────────────────────────
@needs_backend
class ScopeTest(unittest.TestCase):
def test_defaults_show_everywhere_without_notif_pills(self):
r = reg()
for worker, cwd in [(None, None), ("local", "/home/x"), ("mac-acme", "/Users/g/WORK/a")]:
self.assertEqual(r.scoped_kinds(worker, cwd), frozenset({"pr"}))
self.assertFalse(r.notif_pills("local", "/x"))
def test_workers(self):
r = reg(workers=["mac-acme"])
self.assertEqual(r.scoped_kinds("mac-acme", "/x"), frozenset({"pr"}))
self.assertEqual(r.scoped_kinds("local", "/x"), frozenset())
self.assertEqual(r.scoped_kinds(None, "/x"), frozenset()) # None = local
self.assertEqual(reg(workers=["local"]).scoped_kinds(None, "/x"), frozenset({"pr"}))
# A textarea-style newline list works too.
self.assertEqual(reg(workers="a\nlocal").scoped_kinds(None, "/x"), frozenset({"pr"}))
def test_cwd_globs(self):
r = reg(cwdGlobs=["/Users/g/WORK/acme*", "~/work/*"])
self.assertEqual(r.scoped_kinds("w", "/Users/g/WORK/acme-api"), frozenset({"pr"}))
self.assertEqual(r.scoped_kinds("w", os.path.expanduser("~/work/x")), frozenset({"pr"}))
self.assertEqual(r.scoped_kinds("w", "/Users/g/play/x"), frozenset())
self.assertEqual(r.scoped_kinds("w", None), frozenset())
def test_workers_and_globs_both_apply(self):
r = reg(workers=["mac"], cwdGlobs=["/w/*"])
self.assertEqual(r.scoped_kinds("mac", "/w/a"), frozenset({"pr"}))
self.assertEqual(r.scoped_kinds("mac", "/x/a"), frozenset())
self.assertEqual(r.scoped_kinds("lab", "/w/a"), frozenset())
def test_notif_pills_follow_the_scope(self):
r = reg(notifPills=True, cwdGlobs=["/w/*"])
self.assertTrue(r.notif_pills("local", "/w/a"))
self.assertFalse(r.notif_pills("local", "/elsewhere"))
if __name__ == "__main__":
unittest.main()