265 lines
11 KiB
Python
265 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Unit tests for the Plan usage live plugin (stdlib only).
|
|
|
|
A fake hub (``http.server`` on 127.0.0.1) stands in for the ai-agent's
|
|
``usage.read`` / ``usage.calibrate`` bridges; each handler runs as a
|
|
subprocess with the stripped env the hub gives it.
|
|
|
|
python3 tests/test_plugin.py
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
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.plan-usage.123.sig"
|
|
|
|
OVERVIEW = {
|
|
"scope": "profile:personal", "days": 14,
|
|
"accounts": [{"id": "personal", "label": "Personal", "harness": "claude", "planWindows": ["week"],
|
|
"subscription": {"plan": "max20", "monthlyCost": 200, "startDate": "2026-09-01"}}],
|
|
"limits": {"personal": {"windows": {"seven_day": {"pct": 42.0, "resetsAt": 1795500000}},
|
|
"updatedAt": 1795168800, "stale": False, "calibration": None, "plan": None,
|
|
"billing": None}},
|
|
"history": {"personal": {"series": {"seven_day": [{"t": 1795168800, "pct": 40, "resetsAt": 1795500000}]},
|
|
"daily": [{"day": "2026-11-25", "cost": 12.5, "observedWeek": 3.1,
|
|
"predictedWeek": 2.8, "untrackedWeek": 0.3}]}},
|
|
"plans": {"personal": {"account": "personal", "current": None, "history": []}},
|
|
"calibration": {"personal": {"account": "personal", "current": None, "history": []}},
|
|
"profiles": [{"id": "personal", "label": "Personal"}, {"id": "work", "label": "Work"}],
|
|
}
|
|
CALIBRATED = {"calibrations": {"personal": {"account": "personal", "source": "fit", "trusted": True,
|
|
"week": {"unitsPerPct": 12.3, "usdPerPct": 9.8, "r2": 0.7, "n": 60}}},
|
|
"shifted": ["personal"]}
|
|
|
|
|
|
class _Hub(BaseHTTPRequestHandler):
|
|
status = 200
|
|
get_body: dict = OVERVIEW
|
|
post_body: dict = CALIBRATED
|
|
seen: list[tuple[str, str, object]] = []
|
|
|
|
def _auth_ok(self):
|
|
if self.headers.get("Authorization") != f"Bearer {TOKEN}":
|
|
self._send(401, {"error": {"message": "unknown token", "kind": "auth"}})
|
|
return False
|
|
if _Hub.status != 200:
|
|
self._send(_Hub.status, {"error": {"message": "usage.read is owner-only", "kind": "capability"}})
|
|
return False
|
|
return True
|
|
|
|
def do_GET(self):
|
|
_Hub.seen.append(("GET", self.path, None))
|
|
if not self._auth_ok():
|
|
return
|
|
if urllib.parse.urlsplit(self.path).path != "/plugins/plan-usage/hub/usage/overview":
|
|
return self._send(404, {"error": {"message": "no", "kind": "x"}})
|
|
self._send(200, _Hub.get_body)
|
|
|
|
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_ok():
|
|
return
|
|
if self.path != "/plugins/plan-usage/hub/usage/calibrate":
|
|
return self._send(404, {"error": {"message": "no", "kind": "x"}})
|
|
self._send(200, _Hub.post_body)
|
|
|
|
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 TestHandlers(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.get_body = OVERVIEW
|
|
_Hub.post_body = CALIBRATED
|
|
_Hub.seen = []
|
|
|
|
def run_action(self, name, payload=None, token=TOKEN, url=None):
|
|
script = ROOT / MANIFEST["actions"][name]["script"]
|
|
with tempfile.TemporaryDirectory() as td:
|
|
env = {"PATH": "/usr/bin:/bin", "AIA_TOOLS_URL": url or self.url, "AIA_TOOLS_TOKEN": token,
|
|
"AIA_PLUGIN_ID": "plan-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][1]).query)
|
|
|
|
# overview
|
|
def test_overview_passes_through(self):
|
|
p = self.run_action("overview", {"scope": "profile:work", "days": 30})
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
self.assertEqual(json.loads(p.stdout), OVERVIEW)
|
|
self.assertEqual(self._query(), {"scope": ["profile:work"], "days": ["30"]})
|
|
|
|
def test_overview_all_scope(self):
|
|
p = self.run_action("overview", {"scope": "all", "days": 90})
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
self.assertEqual(self._query(), {"scope": ["all"], "days": ["90"]})
|
|
|
|
def test_overview_odd_input_is_dropped(self):
|
|
p = self.run_action("overview", {"scope": "profile:x&admin=1", "days": 999})
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
self.assertEqual(self._query(), {"days": ["14"]})
|
|
self.run_action("overview", {"days": "lots"})
|
|
self.assertEqual(self._query(), {"days": ["14"]})
|
|
self.run_action("overview")
|
|
self.assertEqual(self._query(), {"days": ["14"]})
|
|
|
|
def test_overview_without_the_shape_fails(self):
|
|
_Hub.get_body = {"days": []}
|
|
p = self.run_action("overview")
|
|
self.assertNotEqual(p.returncode, 0)
|
|
self.assertIn("without a plan usage overview", p.stderr)
|
|
|
|
def test_hub_refusal_is_reported(self):
|
|
_Hub.status = 403
|
|
p = self.run_action("overview")
|
|
self.assertNotEqual(p.returncode, 0)
|
|
self.assertIn("owner-only", p.stderr)
|
|
|
|
def test_bad_token(self):
|
|
p = self.run_action("overview", token="nope")
|
|
self.assertNotEqual(p.returncode, 0)
|
|
self.assertIn("unknown token", p.stderr)
|
|
|
|
def test_unreachable_hub(self):
|
|
p = self.run_action("overview", url="http://127.0.0.1:9")
|
|
self.assertNotEqual(p.returncode, 0)
|
|
self.assertIn("didn't answer", p.stderr)
|
|
|
|
# calibrate
|
|
def test_calibrate_posts_backfill(self):
|
|
p = self.run_action("calibrate", {"backfill": True})
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
self.assertEqual(json.loads(p.stdout), CALIBRATED)
|
|
self.assertEqual(_Hub.seen[-1][0], "POST")
|
|
self.assertEqual(_Hub.seen[-1][2], {"backfill": True})
|
|
|
|
def test_calibrate_backfill_must_be_true(self):
|
|
self.run_action("calibrate", {"backfill": "yes"})
|
|
self.assertEqual(_Hub.seen[-1][2], {"backfill": False})
|
|
self.run_action("calibrate")
|
|
self.assertEqual(_Hub.seen[-1][2], {"backfill": False})
|
|
|
|
def test_calibrate_fills_shifted(self):
|
|
_Hub.post_body = {"calibrations": {}}
|
|
p = self.run_action("calibrate")
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
self.assertEqual(json.loads(p.stdout), {"calibrations": {}, "shifted": []})
|
|
|
|
def test_calibrate_without_calibrations_fails(self):
|
|
_Hub.post_body = {"ok": True}
|
|
p = self.run_action("calibrate")
|
|
self.assertNotEqual(p.returncode, 0)
|
|
self.assertIn("without calibrations", p.stderr)
|
|
|
|
|
|
class TestPackage(unittest.TestCase):
|
|
def html(self):
|
|
return (ROOT / MANIFEST["ui"]["pages"][0]["html"]).read_text()
|
|
|
|
def test_manifest(self):
|
|
self.assertEqual(MANIFEST["id"], "plan-usage")
|
|
self.assertEqual(MANIFEST["name"], "Plan usage")
|
|
self.assertEqual(MANIFEST["capabilities"], ["usage.read", "usage.calibrate"])
|
|
self.assertNotIn("managed", MANIFEST)
|
|
self.assertRegex(MANIFEST["color"], r"^#[0-9a-f]{6}$")
|
|
page = MANIFEST["ui"]["pages"][0]
|
|
self.assertEqual((page["id"], page["label"], page["nav"], page["html"]),
|
|
("board", "Plan usage", "dashboards", "ui/board.html"))
|
|
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_overview_is_read_only_calibrate_is_not(self):
|
|
# a read-only account (the screenshot bot) sends page actions as GETs;
|
|
# the page reads through read() (the host's query) and writes with action()
|
|
html = self.html()
|
|
reads = set(re.findall(r'\bread\("([a-z-]+)"', html))
|
|
writes = set(re.findall(r'\.action\("([a-z-]+)"', html))
|
|
self.assertEqual(reads, {"overview"})
|
|
self.assertEqual(writes, {"calibrate"})
|
|
self.assertIs(MANIFEST["actions"]["overview"].get("readOnly"), True)
|
|
self.assertNotIn("readOnly", MANIFEST["actions"]["calibrate"])
|
|
|
|
def test_page_needs_no_network(self):
|
|
self.assertNotRegex(self.html(), r"<script[^>]+src=|<link[^>]+href=|@import|fetch\(|XMLHttpRequest|innerHTML")
|
|
|
|
def test_page_uses_the_app_theme_and_scope(self):
|
|
html = self.html()
|
|
for token in ("--card", "--foreground", "--muted-foreground", "--border", "--primary", "html.dark",
|
|
"onTheme", "init.scope", "Recalibrate", "backfill"):
|
|
self.assertIn(token, html)
|
|
for d in ("7", "14", "30", "90"):
|
|
self.assertIn(d, re.search(r"DAY_OPTIONS = \[([^\]]+)\]", html).group(1))
|
|
|
|
def test_page_is_native(self):
|
|
# the app's header carries the title, the scope line and Recalibrate; the
|
|
# host's skeleton replaces a first-paint "Loading…"; reads go through query
|
|
html = self.html()
|
|
for token in ("api.query(name, payload, cb)", "setHeader", "onHeaderAction", 'id === "recal"',
|
|
"aia-page", "aia-card", "aia-seg", "aia-error", "aia-empty"):
|
|
self.assertIn(token, html)
|
|
self.assertNotIn("Loading", html)
|
|
self.assertNotRegex(html, r"<h1|id=\"refresh\"")
|
|
|
|
def test_page_has_every_panel(self):
|
|
html = self.html()
|
|
for title in ("Where the limits stand", "Which plan", "Billing cycle", "How the windows filled",
|
|
"Does the archive explain the meter?", "The exchange rate in force",
|
|
"What 1% of the week costs over time"):
|
|
self.assertIn(title, html)
|
|
|
|
def test_icon_is_plain(self):
|
|
svg = (ROOT / "icon.svg").read_text()
|
|
self.assertIn('stroke="currentColor"', svg)
|
|
self.assertIn('stroke-width="1.75"', svg)
|
|
self.assertIn('viewBox="0 0 24 24"', 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"])
|
|
|
|
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)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|