scorpiox-bot-plugin-time
←e2e.pypython
299 lines · 12 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport checks for the plugin_time World Clock page.
3
4Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens it
5with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts:
6
7 * no console error and no page error at any viewport
8 * scrollWidth <= innerWidth (no horizontal overflow)
9 * the clock, converter, world-clock table and time-ago panel all render
10 * every value on the page agrees with the tool (the page calls it)
11 * the fall-back note appears for a repeated hour
12 * screenshots land in docs/ for the README
13
14Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays
15dependency-free.
16
17 python3 tests/e2e.py # run if Playwright is available
18 python3 tests/e2e.py --strict # exit 2 when Playwright is missing
19"""
20
21import argparse
22import http.server
23import json
24import os
25import subprocess
26import sys
27import threading
28from urllib.parse import urlparse
29
30ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
31BIN = os.path.join(ROOT, "plugin_time")
32DOCS = os.path.join(ROOT, "docs")
33VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
34THEMES = ["dark", "light"]
35
36# The instant every screenshot and assertion is taken at, so the PNGs do not
37# change on every run and a DST verdict never depends on today's date.
38PINNED_NOW = "2026-11-14T00:00:00Z"
39
40FAILS = []
41
42
43def ok(desc):
44 print(" ok %s" % desc)
45
46
47def bad(desc, detail=""):
48 FAILS.append(desc)
49 print(" FAIL %s%s" % (desc, (" (" + str(detail)[:300] + ")") if detail else ""))
50
51
52def cgi_call(query, method="GET", payload=None):
53 env = dict(os.environ)
54 env["QUERY_STRING"] = query
55 env["REQUEST_METHOD"] = method
56 env["SX_TIME_NOW"] = PINNED_NOW
57 env.pop("BOT_PASSWORD", None)
58 data = json.dumps(payload).encode() if payload is not None else b""
59 env["CONTENT_LENGTH"] = str(len(data))
60 out = subprocess.run([BIN], input=data, capture_output=True, env=env,
61 timeout=60).stdout
62 return json.loads(out.split(b"\r\n\r\n", 1)[-1])
63
64
65class Handler(http.server.BaseHTTPRequestHandler):
66 def _run(self, method):
67 u = urlparse(self.path)
68 length = int(self.headers.get("Content-Length") or 0)
69 body = self.rfile.read(length) if length else b""
70 env = dict(os.environ)
71 env["QUERY_STRING"] = u.query
72 env["REQUEST_METHOD"] = method
73 env["SX_TIME_NOW"] = PINNED_NOW
74 env.pop("BOT_PASSWORD", None)
75 env["CONTENT_LENGTH"] = str(len(body))
76 out = subprocess.run([BIN], input=body, capture_output=True, env=env,
77 timeout=60).stdout
78 sep = out.find(b"\r\n\r\n")
79 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
80 payload = out[sep + 4:] if sep >= 0 else out
81 status = 200
82 ctype = "application/json; charset=utf-8"
83 for line in headers.splitlines():
84 low = line.lower()
85 if low.startswith("content-type:"):
86 ctype = line.split(":", 1)[1].strip()
87 elif low.startswith("status:"):
88 try:
89 status = int(line.split(":", 1)[1].strip().split()[0])
90 except (IndexError, ValueError):
91 status = 200
92 self.send_response(status)
93 self.send_header("Content-Type", ctype)
94 self.send_header("Cache-Control", "no-store")
95 self.send_header("Content-Length", str(len(payload)))
96 self.end_headers()
97 self.wfile.write(payload)
98
99 def do_GET(self): # noqa: N802
100 self._run("GET")
101
102 def do_POST(self): # noqa: N802
103 self._run("POST")
104
105 def log_message(self, *_a):
106 pass
107
108
109def tool(name, args, now=None):
110 out = subprocess.run(
111 [BIN, "--mcp"],
112 input=(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call",
113 "params": {"name": name, "arguments": args}}) + "\n").encode(),
114 capture_output=True,
115 env=dict(os.environ, SX_TIME_NOW=now or PINNED_NOW),
116 timeout=60,
117 ).stdout
118 d = json.loads(out.decode().splitlines()[0])
119 r = d["result"]
120 if r.get("isError"):
121 return {"error": r["content"][0]["text"]}
122 return r["structuredContent"]
123
124
125def main():
126 ap = argparse.ArgumentParser()
127 ap.add_argument("--strict", action="store_true")
128 args = ap.parse_args()
129
130 try:
131 from playwright.sync_api import sync_playwright
132 except ImportError:
133 print("playwright not installed - skipping the viewport suite")
134 return 2 if args.strict else 0
135
136 if not os.access(BIN, os.X_OK):
137 bad("plugin_time binary is missing (run make first)")
138 return 1
139
140 os.makedirs(DOCS, exist_ok=True)
141
142 srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
143 port = srv.server_address[1]
144 threading.Thread(target=srv.serve_forever, daemon=True).start()
145 base = "http://127.0.0.1:%d/plugin_time" % port
146
147 # What the page must agree with. The page opens on the NODE's own zone for
148 # both the clock and the left-hand side of the converter, so the reference
149 # values are asked for that zone - asserting against a hard-coded
150 # Pacific/Auckland would be asserting the page is wrong on a UTC host.
151 info = cgi_call("action=info")
152 local = info["local"]
153 local_now = tool("get_current_time", {"timezone": local})
154 conv = tool("convert_time", {"source_timezone": local, "time": "09:00",
155 "target_timezone": "UTC" if local != "UTC" else local})
156
157 try:
158 with sync_playwright() as p:
159 browser = p.chromium.launch()
160 for theme in THEMES:
161 for w, h in VIEWPORTS:
162 tag = "%dx%d-%s" % (w, h, theme)
163 page = browser.new_page(viewport={"width": w, "height": h})
164 errors = []
165 page.on("console", lambda m: errors.append(m.text)
166 if m.type == "error" else None)
167 page.on("pageerror", lambda e: errors.append(str(e)))
168 page.goto("%s?theme=%s" % (base, theme),
169 wait_until="networkidle")
170 page.wait_for_function(
171 "document.getElementById('clock').textContent !== '--:--:--'",
172 timeout=15000)
173
174 # No overflow, no errors.
175 sw = page.evaluate("document.documentElement.scrollWidth")
176 iw = page.evaluate("window.innerWidth")
177 if sw <= iw:
178 ok("%s: no horizontal overflow (%d <= %d)" % (tag, sw, iw))
179 else:
180 bad("%s: horizontal overflow %d > %d" % (tag, sw, iw))
181 if not errors:
182 ok("%s: no console or page error" % tag)
183 else:
184 bad("%s: page errors" % tag, errors)
185
186 # Theme applied.
187 dt = page.evaluate(
188 "document.documentElement.getAttribute('data-theme')")
189 if dt == theme:
190 ok("%s: data-theme is %s" % (tag, theme))
191 else:
192 bad("%s: data-theme is %r" % (tag, dt))
193
194 # The clock shows the tool's answer, not the browser's.
195 clock = page.inner_text("#clock")
196 if clock == local_now["datetime"][11:19]:
197 ok("%s: the clock shows the tool's time (%s)" % (tag, clock))
198 else:
199 bad("%s: clock %r != tool %r"
200 % (tag, clock, local_now["datetime"][11:19]))
201 zone = page.inner_text("#clockZone")
202 if local in zone:
203 ok("%s: the clock names the node's own zone (%s)"
204 % (tag, local))
205 else:
206 bad("%s: clock zone text %r" % (tag, zone))
207 badge = page.inner_text("#clockBadge")
208 if badge in ("DST", "Standard"):
209 ok("%s: the DST badge rendered (%s)" % (tag, badge))
210 else:
211 bad("%s: DST badge is %r" % (tag, badge))
212
213 # The converter ran once on load.
214 src = page.inner_text("#convSrc")
215 dst = page.inner_text("#convDst")
216 if src == conv["source"]["datetime"][11:19] and \
217 dst == conv["target"]["datetime"][11:19]:
218 ok("%s: converter matches the tool (%s -> %s)"
219 % (tag, src, dst))
220 else:
221 bad("%s: converter %r -> %r, tool %r -> %r"
222 % (tag, src, dst,
223 conv["source"]["datetime"][11:19],
224 conv["target"]["datetime"][11:19]))
225 diff = page.inner_text("#convDiff")
226 if conv["time_difference"] in diff:
227 ok("%s: the difference is shown (%s)" % (tag, diff))
228 else:
229 bad("%s: difference text %r" % (tag, diff))
230
231 # The world clock rendered rows and they are filled in.
232 rows = page.eval_on_selector_all(
233 "#grid tr", "els => els.length")
234 if rows >= 5:
235 ok("%s: world clock has %d rows" % (tag, rows))
236 else:
237 bad("%s: world clock rendered %d rows" % (tag, rows))
238 filled = page.eval_on_selector_all(
239 "#grid tr td.t",
240 "els => els.filter(e => /\\d\\d:\\d\\d:\\d\\d/.test(e.textContent)).length")
241 if filled >= 3:
242 ok("%s: world clock rows carry live times (%d)" % (tag, filled))
243 else:
244 bad("%s: only %d world-clock cells carry a time"
245 % (tag, filled))
246
247 # Time-ago panel.
248 page.fill("#agoD", "2")
249 page.click("#agoBtn")
250 page.wait_for_function(
251 "document.getElementById('agoOut').classList.contains('on')",
252 timeout=10000)
253 ago = page.inner_text("#agoOut")
254 if "T" in ago and ("UTC" in ago or "/" in ago):
255 ok("%s: time-ago rendered (%s)" % (tag, ago.splitlines()[0]))
256 else:
257 bad("%s: time-ago output %r" % (tag, ago))
258
259 # Tools list.
260 tools = page.inner_text("#toolsOut")
261 if "get_current_time" in tools and "convert_time" in tools:
262 ok("%s: the tool list rendered" % tag)
263 else:
264 bad("%s: tool list %r" % (tag, tools[:120]))
265
266 # Screenshot for the README.
267 shot = os.path.join(DOCS, "ui-%s.png" % tag)
268 page.screenshot(path=shot, full_page=True)
269 size = os.path.getsize(shot)
270 if size < 900 * 1024:
271 ok("%s: screenshot written (%d bytes)" % (tag, size))
272 else:
273 bad("%s: screenshot is %d bytes" % (tag, size))
274 page.close()
275 browser.close()
276 finally:
277 srv.shutdown()
278
279 # The repeated-hour note, at the instant a London fall-back repeats 01:30.
280 # Passed explicitly: tool() defaults to PINNED_NOW, so changing os.environ
281 # here would silently be ignored.
282 r = tool("convert_time", {"source_timezone": "Europe/London", "time": "01:30",
283 "target_timezone": "UTC"},
284 now="2026-10-25T00:00:00Z")
285 if r.get("later_occurrence"):
286 ok("the repeated-hour path returns a later_occurrence")
287 else:
288 bad("the repeated-hour path did not return a later_occurrence", r)
289
290 print("")
291 if FAILS:
292 print("FAILED %d check(s)" % len(FAILS))
293 return 1
294 print("all viewport checks passed")
295 return 0
296
297
298if __name__ == "__main__":
299 sys.exit(main())