scorpiox-bot-plugin-ntfy
←e2e.pypython
322 lines · 13 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport checks for the plugin_ntfy panel.
3
4Serves the plugin through a small CGI-ish HTTP shim on a loopback port, starts
5tests/mockd.py so the panel has a real ntfy server and a real /inbox to talk
6to, opens it with Playwright at 1440 / 1024 / 390 CSS pixels in both themes,
7and asserts:
8
9 * no console error and no page error at any viewport
10 * scrollWidth <= innerWidth (no horizontal overflow)
11 * the status KPI grid renders and the daemon pill reads running once the
12 supervised daemon is up
13 * the pairing tab lists an injected unapproved sender and the Approve
14 button actually approves it (state round-trips through the plugin)
15 * action=send publishes and the message lands in the mock ntfy capture
16 * the log tab shows the daemon's own lines
17 * screenshots land in docs/ for the README
18
19Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays
20dependency-free.
21
22 python3 tests/e2e.py # run if Playwright is available
23 python3 tests/e2e.py --strict # exit 2 when Playwright is missing
24"""
25
26import argparse
27import json
28import os
29import socketserver
30import subprocess
31import sys
32import threading
33import time
34import urllib.parse
35import urllib.request
36from http.server import BaseHTTPRequestHandler
37
38ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
39BIN = os.path.join(ROOT, "plugin_ntfy")
40DOCS = os.path.join(ROOT, "docs")
41VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
42THEMES = ["dark", "light"]
43
44PORT = int(os.environ.get("NTFY_E2E_PORT", "18280")) # mockd
45SHIM_PORT = int(os.environ.get("NTFY_E2E_SHIM", "18281")) # CGI shim
46CONN = "/tmp/sx-ntfy-e2e-connectors"
47MOCKROOT = "/tmp/sx-ntfy-e2e-mock"
48
49
50def http_json(url, body=None, timeout=5):
51 data = json.dumps(body).encode() if body is not None else None
52 req = urllib.request.Request(url, data=data,
53 headers={"Content-Type": "application/json"})
54 with urllib.request.urlopen(req, timeout=timeout) as r:
55 return json.loads(r.read().decode())
56
57
58class CgiHandler(BaseHTTPRequestHandler):
59 """Runs the plugin as a CGI with the suite's state dir."""
60
61 def _run(self, method):
62 u = urllib.parse.urlparse(self.path)
63 length = int(self.headers.get("Content-Length") or 0)
64 body = self.rfile.read(length) if length else b""
65 env = dict(os.environ)
66 env["QUERY_STRING"] = u.query
67 env["REQUEST_METHOD"] = method
68 env["SX_CONNECTORS_DIR"] = CONN
69 env["CONTENT_LENGTH"] = str(len(body))
70 env.pop("BOT_PASSWORD", None)
71 out = subprocess.run([BIN], input=body, capture_output=True,
72 env=env, timeout=60).stdout
73 sep = out.find(b"\r\n\r\n")
74 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
75 payload = out[sep + 4:] if sep >= 0 else out
76 status = 200
77 ctype = "application/json; charset=utf-8"
78 for line in headers.splitlines():
79 low = line.lower()
80 if low.startswith("content-type:"):
81 ctype = line.split(":", 1)[1].strip()
82 elif low.startswith("status:"):
83 try:
84 status = int(line.split(":", 1)[1].strip().split()[0])
85 except (IndexError, ValueError):
86 status = 200
87 self.send_response(status)
88 self.send_header("Content-Type", ctype)
89 self.send_header("Cache-Control", "no-store")
90 self.send_header("Content-Length", str(len(payload)))
91 self.end_headers()
92 self.wfile.write(payload)
93
94 def do_GET(self): # noqa: N802
95 self._run("GET")
96
97 def do_POST(self): # noqa: N802
98 self._run("POST")
99
100 def log_message(self, *_a):
101 pass
102
103
104def main():
105 ap = argparse.ArgumentParser()
106 ap.add_argument("--strict", action="store_true")
107 args = ap.parse_args()
108
109 if not os.path.exists(BIN):
110 print("plugin_ntfy is not built; run make first", file=sys.stderr)
111 return 1
112
113 try:
114 from playwright.sync_api import sync_playwright
115 except Exception:
116 if args.strict:
117 print("playwright is not installed", file=sys.stderr)
118 return 2
119 print("playwright not available - skipping e2e (offline suite still runs)")
120 return 0
121
122 os.makedirs(DOCS, exist_ok=True)
123 subprocess.run(["pkill", "-f", "mockd[.]py"], capture_output=True)
124 subprocess.run(["pkill", "-f", "plugin_ntfy --daemo[n]"], capture_output=True)
125 time.sleep(0.4)
126 for p in (CONN, MOCKROOT):
127 subprocess.run(["rm", "-rf", p])
128
129 mockd = subprocess.Popen(
130 [sys.executable, os.path.join(ROOT, "tests", "mockd.py"),
131 "--port", str(PORT), "--root", MOCKROOT],
132 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
133 ready = False
134 deadline = time.time() + 10
135 while time.time() < deadline and not ready:
136 line = mockd.stdout.readline().decode(errors="replace")
137 if "listening" in line:
138 ready = True
139 if not ready:
140 print("mockd never came up", file=sys.stderr)
141 mockd.kill()
142 return 1
143
144 rc = 1
145 daemon_proc = None
146 try:
147 # configure + start the daemon through the very API the UI uses
148 cfg = {
149 "server_url": "http://127.0.0.1:%d" % PORT,
150 "topic": "tin", "publish_topic": "tout",
151 "bot_api_url": "http://127.0.0.1:%d" % PORT,
152 "target_session": "mock-session",
153 "pairing_code_enabled": 1, "reply_poll_ms": 300,
154 "idle_timeout_ms": 2500,
155 }
156 env = dict(os.environ, SX_CONNECTORS_DIR=CONN, REQUEST_METHOD="POST",
157 CONTENT_LENGTH="0", QUERY_STRING="action=save")
158 body = json.dumps(cfg).encode()
159 env["CONTENT_LENGTH"] = str(len(body))
160 out = subprocess.run([BIN], input=body, capture_output=True,
161 env=env, timeout=30).stdout
162 if b'"valid":true' not in out:
163 print("could not save a valid config: %s" % out[-300:], file=sys.stderr)
164 return 1
165 daemon_proc = subprocess.Popen(
166 [BIN, "--daemon"], env=dict(os.environ, SX_CONNECTORS_DIR=CONN),
167 stdout=open("/tmp/sx-ntfy-e2e-daemon.log", "wb"),
168 stderr=subprocess.STDOUT)
169 # wait for the subscription
170 for _ in range(60):
171 try:
172 st = http_json("http://127.0.0.1:%d/__stats" % PORT)
173 if st.get("ok"):
174 break
175 except Exception:
176 pass
177 time.sleep(0.2)
178
179 # an unapproved sender waiting in the pairing queue
180 http_json("http://127.0.0.1:%d/__inject" % PORT,
181 {"topic": "tin", "message": "e2e pairing request",
182 "user": "e2euser", "tags": ["demo"]})
183 time.sleep(2.0)
184
185 socketserver.TCPServer.allow_reuse_address = True
186 try:
187 httpd = socketserver.TCPServer(("127.0.0.1", SHIM_PORT), CgiHandler)
188 except OSError as exc:
189 print("could not bind %d: %s" % (SHIM_PORT, exc), file=sys.stderr)
190 return 1
191 threading.Thread(target=httpd.serve_forever, daemon=True).start()
192
193 base = "http://127.0.0.1:%d/" % SHIM_PORT
194 errors = []
195
196 with sync_playwright() as p:
197 browser = p.chromium.launch()
198 for w, h in VIEWPORTS:
199 for theme in THEMES:
200 tag = "%dx%d %s" % (w, h, theme)
201 page = browser.new_page(viewport={"width": w, "height": h})
202 console = []
203 page.on("console", lambda m: console.append(m.type + ": " + m.text)
204 if m.type == "error" else None)
205 page.on("pageerror", lambda e: console.append("pageerror: %s" % e))
206 page.goto(base + "?theme=" + theme, wait_until="networkidle")
207 page.wait_for_selector("#kpis .kpi", timeout=15000)
208
209 kpis = page.eval_on_selector_all("#kpis .kpi", "els => els.length")
210 if kpis < 8:
211 errors.append("%s: only %d KPIs" % (tag, kpis))
212 over = page.evaluate("document.documentElement.scrollWidth - window.innerWidth")
213 if over > 1:
214 errors.append("%s: horizontal overflow %spx" % (tag, over))
215
216 # daemon pill
217 pill = page.text_content("#runPill") or ""
218 if "running" not in pill:
219 errors.append("%s: daemon pill says %r" % (tag, pill))
220
221 # pairing tab shows the held sender (re-injected per
222 # viewport: the first Approve click drains the queue)
223 uniq = "e2euser-%d-%s" % (w, theme)
224
225 def cgi_pending():
226 env2 = dict(os.environ, SX_CONNECTORS_DIR=CONN)
227 out = subprocess.run(
228 [BIN], capture_output=True, env=env2, timeout=30,
229 ).stdout
230 return out.decode("utf-8", "replace")
231
232 seen = False
233 for _try in range(6):
234 http_json("http://127.0.0.1:%d/__inject" % PORT,
235 {"topic": "tin",
236 "message": "e2e pairing request %s" % uniq,
237 "user": uniq, "tags": ["demo"]})
238 # Refresh (status tab) reloads the pending queue;
239 # then switch to the pairing tab.
240 page.click("#tabStatus")
241 page.click("#refreshBtn")
242 page.click("#tabPair")
243 page.click("#tabPair")
244 try:
245 page.wait_for_function(
246 "u => (document.getElementById('pendBody')"
247 ".textContent||'').indexOf(u) >= 0",
248 arg=uniq, timeout=4000)
249 seen = True
250 break
251 except Exception:
252 time.sleep(1.5)
253 if not seen:
254 errors.append("%s: pending list lacks %s (plugin says: %s)"
255 % (tag, uniq,
256 cgi_pending()[-400:].replace("\n", " ")))
257
258 # approve through the UI (asserted once; state is shared)
259 if (w, theme) == (1440, "dark"):
260 row = page.locator("#pendBody tr", has_text=uniq)
261 row.locator("[data-approve]").first.click()
262 page.wait_for_timeout(1200)
263 page.click("#tabStatus") # force reload of the tab
264 page.click("#tabPair")
265 page.wait_for_timeout(1200)
266 pend2 = page.text_content("#pendBody") or ""
267 if uniq in pend2:
268 errors.append("approve did not drain the queue")
269
270 # send-test tab publishes for real
271 page.click("#tabSend")
272 page.fill("#s_msg", "hello from playwright %dx%d" % (w, h))
273 page.click("#sendBtn")
274 page.wait_for_timeout(1500)
275 pubs = http_json("http://127.0.0.1:%d/__publishes" % PORT)
276 if not any("hello from playwright" in str(p.get("message", ""))
277 for p in pubs.get("published", [])):
278 errors.append("%s: UI send never reached the mock ntfy" % tag)
279
280 # log tab shows daemon lines
281 page.click("#tabLog")
282 page.wait_for_selector("#logBox", timeout=15000)
283 page.click("#logBtn")
284 page.wait_for_timeout(1000)
285 logt = page.text_content("#logBox") or ""
286 if "daemon start" not in logt and "subscribed" not in logt:
287 errors.append("%s: log tab has no daemon lines" % tag)
288
289 if console:
290 errors.append("%s: console: %s" % (tag, console[:3]))
291
292 page.screenshot(path=os.path.join(
293 DOCS, "ui-%d-%s.png" % (w, theme)), full_page=(w != 1440))
294 page.close()
295 browser.close()
296
297 httpd.shutdown()
298 if errors:
299 print("FAILURES:", file=sys.stderr)
300 for e in errors:
301 print(" -", e, file=sys.stderr)
302 rc = 1
303 else:
304 print("e2e ok - %d viewport/theme combinations, screenshots in docs/"
305 % (len(VIEWPORTS) * len(THEMES)))
306 rc = 0
307 finally:
308 try:
309 if daemon_proc and daemon_proc.poll() is None:
310 pidf = os.path.join(CONN, "plugin_ntfy", "daemon.pid")
311 if os.path.exists(pidf):
312 os.kill(int(open(pidf).read().strip()), 15)
313 daemon_proc.terminate()
314 except Exception:
315 pass
316 mockd.kill()
317
318 return rc
319
320
321if __name__ == "__main__":
322 sys.exit(main())