143 lines
5.7 KiB
Python
143 lines
5.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Unit tests for the Analytics live plugin (stdlib only).
|
|
|
|
A fake hub (``http.server`` on 127.0.0.1) stands in for the ai-agent's
|
|
``/proxy/tools/plugins/analytics/hub/analytics`` bridge; the handler runs
|
|
as a subprocess with the stripped env the hub gives it.
|
|
|
|
python3 tests/test_analytics_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.analytics.123.sig"
|
|
|
|
CONVS = {"scope": "all", "range": "30d", "since": None, "binMinutes": 5, "cron": False, "profiles": [],
|
|
"conversations": [{"id": "c1", "t": 1, "start": 0, "workMin": 25, "wallSec": 1800, "turns": 2, "byDay": {},
|
|
"model": "opus", "harness": "claude", "projects": [], "machine": "Homelab",
|
|
"person": "Olivia", "guest": False, "origin": "app"}]}
|
|
|
|
|
|
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/analytics/hub/analytics":
|
|
return self._send(404, {"error": {"message": "no", "kind": "x"}})
|
|
if _Hub.status != 200:
|
|
return self._send(_Hub.status, {"error": {"message": "analytics.read is owner-only",
|
|
"kind": "capability"}})
|
|
self._send(200, CONVS)
|
|
|
|
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"]["conversations"]["script"]
|
|
with tempfile.TemporaryDirectory() as td:
|
|
env = {"PATH": "/usr/bin:/bin", "AIA_TOOLS_URL": self.url, "AIA_TOOLS_TOKEN": token,
|
|
"AIA_PLUGIN_ID": "analytics", "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_conversations_through(self):
|
|
p = self.run_action({"scope": "profile:work", "range": "7d", "tzOffset": 60, "cron": True})
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
self.assertEqual(json.loads(p.stdout)["conversations"][0]["workMin"], 25)
|
|
self.assertEqual(self._query(), {"account": ["profile:work"], "range": ["7d"], "tzOffset": ["60"], "cron": ["1"]})
|
|
|
|
def test_odd_inputs_are_dropped(self):
|
|
p = self.run_action({"scope": "profile:x&a=1", "range": "1y", "tzOffset": "9999", "cron": "yes"})
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
self.assertEqual(self._query(), {"range": ["30d"], "tzOffset": ["840"], "cron": ["0"]})
|
|
|
|
def test_page_shows_no_cost(self):
|
|
html = (ROOT / MANIFEST["ui"]["pages"][0]["html"]).read_text().lower()
|
|
self.assertNotIn("usd", html)
|
|
self.assertNotIn("$", html.replace("$(", ""))
|
|
self.assertEqual(html.count("cost"), 2) # only "Costs are on the cost dashboards."
|
|
|
|
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"], "analytics")
|
|
self.assertEqual(MANIFEST["capabilities"], ["analytics.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()
|