136 lines
5.2 KiB
Python
136 lines
5.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Unit tests for the App usage live plugin (stdlib only).
|
|
|
|
A fake hub (``http.server`` on 127.0.0.1) stands in for the ai-agent's
|
|
``/proxy/tools/plugins/app-usage/hub/telemetry/usage`` bridge; the handler runs
|
|
as a subprocess with the stripped env the hub gives it.
|
|
|
|
python3 tests/test_app-usage_plugin.py
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
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
|
|
MANIFEST = json.loads((ROOT / "plugin.json").read_text())
|
|
TOKEN = "aiah1.owner.app-usage.123.sig"
|
|
|
|
USAGE = {"features": [{"kind": "view", "name": "page.home", "n": 3, "byUser": {"owner": 3}, "byDevice": {"phone": 3}}],
|
|
"devices": {"phone": 3}, "people": [], "whatsNew": [], "runs": [], "trackedSince": "2026-11-24",
|
|
"registry": [{"id": "page.home", "label": "Home", "area": "Conversations", "kind": "view"}]}
|
|
|
|
|
|
class _Hub(BaseHTTPRequestHandler):
|
|
status = 200
|
|
seen: list[str] = []
|
|
|
|
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 urllib.parse.urlsplit(self.path).path != "/plugins/app-usage/hub/telemetry/usage":
|
|
return self._send(404, {"error": {"message": "no", "kind": "x"}})
|
|
if _Hub.status != 200:
|
|
return self._send(_Hub.status, {"error": {"message": "telemetry.read is owner-only",
|
|
"kind": "capability"}})
|
|
self._send(200, USAGE)
|
|
|
|
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 = 200
|
|
_Hub.seen = []
|
|
|
|
def run_action(self, payload=None, token=TOKEN):
|
|
script = ROOT / MANIFEST["actions"]["usage"]["script"]
|
|
with tempfile.TemporaryDirectory() as td:
|
|
env = {"PATH": "/usr/bin:/bin", "AIA_TOOLS_URL": self.url, "AIA_TOOLS_TOKEN": token,
|
|
"AIA_PLUGIN_ID": "app-usage", "AIA_PLUGIN_DATA_DIR": td}
|
|
return subprocess.run([sys.executable, "-I", str(script)], input=json.dumps(payload or {}),
|
|
capture_output=True, text=True, env=env, timeout=30)
|
|
|
|
def _query(self):
|
|
return urllib.parse.parse_qs(urllib.parse.urlsplit(_Hub.seen[-1]).query)
|
|
|
|
def test_passes_the_usage_through(self):
|
|
p = self.run_action({"range": "7d", "who": "guest:carol"})
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
self.assertEqual(json.loads(p.stdout)["registry"][0]["id"], "page.home")
|
|
self.assertEqual(self._query(), {"range": ["7d"], "who": ["guest:carol"]})
|
|
|
|
def test_odd_who_and_range_are_dropped(self):
|
|
p = self.run_action({"who": "guest:x&admin=1", "range": "1y"})
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
self.assertEqual(self._query(), {"range": ["30d"], "who": ["all"]})
|
|
|
|
def test_hub_refusal_is_reported(self):
|
|
_Hub.status = 403
|
|
p = self.run_action()
|
|
self.assertNotEqual(p.returncode, 0)
|
|
self.assertIn("owner-only", p.stderr)
|
|
|
|
def test_bad_token(self):
|
|
p = self.run_action(token="nope")
|
|
self.assertNotEqual(p.returncode, 0)
|
|
self.assertIn("unknown token", p.stderr)
|
|
|
|
|
|
class TestPackage(unittest.TestCase):
|
|
def test_manifest(self):
|
|
self.assertEqual(MANIFEST["id"], "app-usage")
|
|
self.assertEqual(MANIFEST["capabilities"], ["telemetry.read"])
|
|
page = MANIFEST["ui"]["pages"][0]
|
|
self.assertEqual(page["nav"], "dashboards")
|
|
self.assertRegex(MANIFEST["color"], r"^#[0-9a-f]{6}$")
|
|
for f in ("README.md", "icon.svg", "illustration.webp", page["html"],
|
|
*(a["script"] for a in MANIFEST["actions"].values())):
|
|
self.assertTrue((ROOT / f).is_file(), f)
|
|
|
|
def test_page_needs_no_network(self):
|
|
html = (ROOT / MANIFEST["ui"]["pages"][0]["html"]).read_text()
|
|
self.assertNotRegex(html, r"<script[^>]+src=|<link[^>]+href=|@import|fetch\(|XMLHttpRequest")
|
|
|
|
def test_icon_is_plain(self):
|
|
svg = (ROOT / "icon.svg").read_text()
|
|
self.assertIn('stroke="currentColor"', svg)
|
|
self.assertNotRegex(svg, r"<script|\son\w+=|foreignObject|href=|data:")
|
|
|
|
def test_handlers_are_executable(self):
|
|
for a in MANIFEST["actions"].values():
|
|
self.assertTrue(os.access(ROOT / a["script"], os.X_OK), a["script"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|