#!/usr/bin/env python3 """tests/e2e.py - viewport checks for the plugin_time World Clock page. Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens it with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts: * no console error and no page error at any viewport * scrollWidth <= innerWidth (no horizontal overflow) * the clock, converter, world-clock table and time-ago panel all render * every value on the page agrees with the tool (the page calls it) * the fall-back note appears for a repeated hour * screenshots land in docs/ for the README Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays dependency-free. python3 tests/e2e.py # run if Playwright is available python3 tests/e2e.py --strict # exit 2 when Playwright is missing """ import argparse import http.server import json import os import subprocess import sys import threading from urllib.parse import urlparse ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_time") DOCS = os.path.join(ROOT, "docs") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] # The instant every screenshot and assertion is taken at, so the PNGs do not # change on every run and a DST verdict never depends on today's date. PINNED_NOW = "2026-11-14T00:00:00Z" FAILS = [] def ok(desc): print(" ok %s" % desc) def bad(desc, detail=""): FAILS.append(desc) print(" FAIL %s%s" % (desc, (" (" + str(detail)[:300] + ")") if detail else "")) def cgi_call(query, method="GET", payload=None): env = dict(os.environ) env["QUERY_STRING"] = query env["REQUEST_METHOD"] = method env["SX_TIME_NOW"] = PINNED_NOW env.pop("BOT_PASSWORD", None) data = json.dumps(payload).encode() if payload is not None else b"" env["CONTENT_LENGTH"] = str(len(data)) out = subprocess.run([BIN], input=data, capture_output=True, env=env, timeout=60).stdout return json.loads(out.split(b"\r\n\r\n", 1)[-1]) class Handler(http.server.BaseHTTPRequestHandler): def _run(self, method): u = urlparse(self.path) length = int(self.headers.get("Content-Length") or 0) body = self.rfile.read(length) if length else b"" env = dict(os.environ) env["QUERY_STRING"] = u.query env["REQUEST_METHOD"] = method env["SX_TIME_NOW"] = PINNED_NOW env.pop("BOT_PASSWORD", None) env["CONTENT_LENGTH"] = str(len(body)) out = subprocess.run([BIN], input=body, capture_output=True, env=env, timeout=60).stdout sep = out.find(b"\r\n\r\n") headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" payload = out[sep + 4:] if sep >= 0 else out status = 200 ctype = "application/json; charset=utf-8" for line in headers.splitlines(): low = line.lower() if low.startswith("content-type:"): ctype = line.split(":", 1)[1].strip() elif low.startswith("status:"): try: status = int(line.split(":", 1)[1].strip().split()[0]) except (IndexError, ValueError): status = 200 self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", str(len(payload))) self.end_headers() self.wfile.write(payload) def do_GET(self): # noqa: N802 self._run("GET") def do_POST(self): # noqa: N802 self._run("POST") def log_message(self, *_a): pass def tool(name, args, now=None): out = subprocess.run( [BIN, "--mcp"], input=(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}}) + "\n").encode(), capture_output=True, env=dict(os.environ, SX_TIME_NOW=now or PINNED_NOW), timeout=60, ).stdout d = json.loads(out.decode().splitlines()[0]) r = d["result"] if r.get("isError"): return {"error": r["content"][0]["text"]} return r["structuredContent"] def main(): ap = argparse.ArgumentParser() ap.add_argument("--strict", action="store_true") args = ap.parse_args() try: from playwright.sync_api import sync_playwright except ImportError: print("playwright not installed - skipping the viewport suite") return 2 if args.strict else 0 if not os.access(BIN, os.X_OK): bad("plugin_time binary is missing (run make first)") return 1 os.makedirs(DOCS, exist_ok=True) srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) port = srv.server_address[1] threading.Thread(target=srv.serve_forever, daemon=True).start() base = "http://127.0.0.1:%d/plugin_time" % port # What the page must agree with. The page opens on the NODE's own zone for # both the clock and the left-hand side of the converter, so the reference # values are asked for that zone - asserting against a hard-coded # Pacific/Auckland would be asserting the page is wrong on a UTC host. info = cgi_call("action=info") local = info["local"] local_now = tool("get_current_time", {"timezone": local}) conv = tool("convert_time", {"source_timezone": local, "time": "09:00", "target_timezone": "UTC" if local != "UTC" else local}) try: with sync_playwright() as p: browser = p.chromium.launch() for theme in THEMES: for w, h in VIEWPORTS: tag = "%dx%d-%s" % (w, h, theme) page = browser.new_page(viewport={"width": w, "height": h}) errors = [] page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None) page.on("pageerror", lambda e: errors.append(str(e))) page.goto("%s?theme=%s" % (base, theme), wait_until="networkidle") page.wait_for_function( "document.getElementById('clock').textContent !== '--:--:--'", timeout=15000) # No overflow, no errors. sw = page.evaluate("document.documentElement.scrollWidth") iw = page.evaluate("window.innerWidth") if sw <= iw: ok("%s: no horizontal overflow (%d <= %d)" % (tag, sw, iw)) else: bad("%s: horizontal overflow %d > %d" % (tag, sw, iw)) if not errors: ok("%s: no console or page error" % tag) else: bad("%s: page errors" % tag, errors) # Theme applied. dt = page.evaluate( "document.documentElement.getAttribute('data-theme')") if dt == theme: ok("%s: data-theme is %s" % (tag, theme)) else: bad("%s: data-theme is %r" % (tag, dt)) # The clock shows the tool's answer, not the browser's. clock = page.inner_text("#clock") if clock == local_now["datetime"][11:19]: ok("%s: the clock shows the tool's time (%s)" % (tag, clock)) else: bad("%s: clock %r != tool %r" % (tag, clock, local_now["datetime"][11:19])) zone = page.inner_text("#clockZone") if local in zone: ok("%s: the clock names the node's own zone (%s)" % (tag, local)) else: bad("%s: clock zone text %r" % (tag, zone)) badge = page.inner_text("#clockBadge") if badge in ("DST", "Standard"): ok("%s: the DST badge rendered (%s)" % (tag, badge)) else: bad("%s: DST badge is %r" % (tag, badge)) # The converter ran once on load. src = page.inner_text("#convSrc") dst = page.inner_text("#convDst") if src == conv["source"]["datetime"][11:19] and \ dst == conv["target"]["datetime"][11:19]: ok("%s: converter matches the tool (%s -> %s)" % (tag, src, dst)) else: bad("%s: converter %r -> %r, tool %r -> %r" % (tag, src, dst, conv["source"]["datetime"][11:19], conv["target"]["datetime"][11:19])) diff = page.inner_text("#convDiff") if conv["time_difference"] in diff: ok("%s: the difference is shown (%s)" % (tag, diff)) else: bad("%s: difference text %r" % (tag, diff)) # The world clock rendered rows and they are filled in. rows = page.eval_on_selector_all( "#grid tr", "els => els.length") if rows >= 5: ok("%s: world clock has %d rows" % (tag, rows)) else: bad("%s: world clock rendered %d rows" % (tag, rows)) filled = page.eval_on_selector_all( "#grid tr td.t", "els => els.filter(e => /\\d\\d:\\d\\d:\\d\\d/.test(e.textContent)).length") if filled >= 3: ok("%s: world clock rows carry live times (%d)" % (tag, filled)) else: bad("%s: only %d world-clock cells carry a time" % (tag, filled)) # Time-ago panel. page.fill("#agoD", "2") page.click("#agoBtn") page.wait_for_function( "document.getElementById('agoOut').classList.contains('on')", timeout=10000) ago = page.inner_text("#agoOut") if "T" in ago and ("UTC" in ago or "/" in ago): ok("%s: time-ago rendered (%s)" % (tag, ago.splitlines()[0])) else: bad("%s: time-ago output %r" % (tag, ago)) # Tools list. tools = page.inner_text("#toolsOut") if "get_current_time" in tools and "convert_time" in tools: ok("%s: the tool list rendered" % tag) else: bad("%s: tool list %r" % (tag, tools[:120])) # Screenshot for the README. shot = os.path.join(DOCS, "ui-%s.png" % tag) page.screenshot(path=shot, full_page=True) size = os.path.getsize(shot) if size < 900 * 1024: ok("%s: screenshot written (%d bytes)" % (tag, size)) else: bad("%s: screenshot is %d bytes" % (tag, size)) page.close() browser.close() finally: srv.shutdown() # The repeated-hour note, at the instant a London fall-back repeats 01:30. # Passed explicitly: tool() defaults to PINNED_NOW, so changing os.environ # here would silently be ignored. r = tool("convert_time", {"source_timezone": "Europe/London", "time": "01:30", "target_timezone": "UTC"}, now="2026-10-25T00:00:00Z") if r.get("later_occurrence"): ok("the repeated-hour path returns a later_occurrence") else: bad("the repeated-hour path did not return a later_occurrence", r) print("") if FAILS: print("FAILED %d check(s)" % len(FAILS)) return 1 print("all viewport checks passed") return 0 if __name__ == "__main__": sys.exit(main())