#!/usr/bin/env python3 """tests/e2e.py - viewport checks for the plugin_ntfy panel. Serves the plugin through a small CGI-ish HTTP shim on a loopback port, starts tests/mockd.py so the panel has a real ntfy server and a real /inbox to talk to, 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 status KPI grid renders and the daemon pill reads running once the supervised daemon is up * the pairing tab lists an injected unapproved sender and the Approve button actually approves it (state round-trips through the plugin) * action=send publishes and the message lands in the mock ntfy capture * the log tab shows the daemon's own lines * 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 json import os import socketserver import subprocess import sys import threading import time import urllib.parse import urllib.request from http.server import BaseHTTPRequestHandler ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_ntfy") DOCS = os.path.join(ROOT, "docs") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] PORT = int(os.environ.get("NTFY_E2E_PORT", "18280")) # mockd SHIM_PORT = int(os.environ.get("NTFY_E2E_SHIM", "18281")) # CGI shim CONN = "/tmp/sx-ntfy-e2e-connectors" MOCKROOT = "/tmp/sx-ntfy-e2e-mock" def http_json(url, body=None, timeout=5): data = json.dumps(body).encode() if body is not None else None req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode()) class CgiHandler(BaseHTTPRequestHandler): """Runs the plugin as a CGI with the suite's state dir.""" def _run(self, method): u = urllib.parse.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_CONNECTORS_DIR"] = CONN env["CONTENT_LENGTH"] = str(len(body)) env.pop("BOT_PASSWORD", None) 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 main(): ap = argparse.ArgumentParser() ap.add_argument("--strict", action="store_true") args = ap.parse_args() if not os.path.exists(BIN): print("plugin_ntfy is not built; run make first", file=sys.stderr) return 1 try: from playwright.sync_api import sync_playwright except Exception: if args.strict: print("playwright is not installed", file=sys.stderr) return 2 print("playwright not available - skipping e2e (offline suite still runs)") return 0 os.makedirs(DOCS, exist_ok=True) subprocess.run(["pkill", "-f", "mockd[.]py"], capture_output=True) subprocess.run(["pkill", "-f", "plugin_ntfy --daemo[n]"], capture_output=True) time.sleep(0.4) for p in (CONN, MOCKROOT): subprocess.run(["rm", "-rf", p]) mockd = subprocess.Popen( [sys.executable, os.path.join(ROOT, "tests", "mockd.py"), "--port", str(PORT), "--root", MOCKROOT], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) ready = False deadline = time.time() + 10 while time.time() < deadline and not ready: line = mockd.stdout.readline().decode(errors="replace") if "listening" in line: ready = True if not ready: print("mockd never came up", file=sys.stderr) mockd.kill() return 1 rc = 1 daemon_proc = None try: # configure + start the daemon through the very API the UI uses cfg = { "server_url": "http://127.0.0.1:%d" % PORT, "topic": "tin", "publish_topic": "tout", "bot_api_url": "http://127.0.0.1:%d" % PORT, "target_session": "mock-session", "pairing_code_enabled": 1, "reply_poll_ms": 300, "idle_timeout_ms": 2500, } env = dict(os.environ, SX_CONNECTORS_DIR=CONN, REQUEST_METHOD="POST", CONTENT_LENGTH="0", QUERY_STRING="action=save") body = json.dumps(cfg).encode() env["CONTENT_LENGTH"] = str(len(body)) out = subprocess.run([BIN], input=body, capture_output=True, env=env, timeout=30).stdout if b'"valid":true' not in out: print("could not save a valid config: %s" % out[-300:], file=sys.stderr) return 1 daemon_proc = subprocess.Popen( [BIN, "--daemon"], env=dict(os.environ, SX_CONNECTORS_DIR=CONN), stdout=open("/tmp/sx-ntfy-e2e-daemon.log", "wb"), stderr=subprocess.STDOUT) # wait for the subscription for _ in range(60): try: st = http_json("http://127.0.0.1:%d/__stats" % PORT) if st.get("ok"): break except Exception: pass time.sleep(0.2) # an unapproved sender waiting in the pairing queue http_json("http://127.0.0.1:%d/__inject" % PORT, {"topic": "tin", "message": "e2e pairing request", "user": "e2euser", "tags": ["demo"]}) time.sleep(2.0) socketserver.TCPServer.allow_reuse_address = True try: httpd = socketserver.TCPServer(("127.0.0.1", SHIM_PORT), CgiHandler) except OSError as exc: print("could not bind %d: %s" % (SHIM_PORT, exc), file=sys.stderr) return 1 threading.Thread(target=httpd.serve_forever, daemon=True).start() base = "http://127.0.0.1:%d/" % SHIM_PORT errors = [] with sync_playwright() as p: browser = p.chromium.launch() for w, h in VIEWPORTS: for theme in THEMES: tag = "%dx%d %s" % (w, h, theme) page = browser.new_page(viewport={"width": w, "height": h}) console = [] page.on("console", lambda m: console.append(m.type + ": " + m.text) if m.type == "error" else None) page.on("pageerror", lambda e: console.append("pageerror: %s" % e)) page.goto(base + "?theme=" + theme, wait_until="networkidle") page.wait_for_selector("#kpis .kpi", timeout=15000) kpis = page.eval_on_selector_all("#kpis .kpi", "els => els.length") if kpis < 8: errors.append("%s: only %d KPIs" % (tag, kpis)) over = page.evaluate("document.documentElement.scrollWidth - window.innerWidth") if over > 1: errors.append("%s: horizontal overflow %spx" % (tag, over)) # daemon pill pill = page.text_content("#runPill") or "" if "running" not in pill: errors.append("%s: daemon pill says %r" % (tag, pill)) # pairing tab shows the held sender (re-injected per # viewport: the first Approve click drains the queue) uniq = "e2euser-%d-%s" % (w, theme) def cgi_pending(): env2 = dict(os.environ, SX_CONNECTORS_DIR=CONN) out = subprocess.run( [BIN], capture_output=True, env=env2, timeout=30, ).stdout return out.decode("utf-8", "replace") seen = False for _try in range(6): http_json("http://127.0.0.1:%d/__inject" % PORT, {"topic": "tin", "message": "e2e pairing request %s" % uniq, "user": uniq, "tags": ["demo"]}) # Refresh (status tab) reloads the pending queue; # then switch to the pairing tab. page.click("#tabStatus") page.click("#refreshBtn") page.click("#tabPair") page.click("#tabPair") try: page.wait_for_function( "u => (document.getElementById('pendBody')" ".textContent||'').indexOf(u) >= 0", arg=uniq, timeout=4000) seen = True break except Exception: time.sleep(1.5) if not seen: errors.append("%s: pending list lacks %s (plugin says: %s)" % (tag, uniq, cgi_pending()[-400:].replace("\n", " "))) # approve through the UI (asserted once; state is shared) if (w, theme) == (1440, "dark"): row = page.locator("#pendBody tr", has_text=uniq) row.locator("[data-approve]").first.click() page.wait_for_timeout(1200) page.click("#tabStatus") # force reload of the tab page.click("#tabPair") page.wait_for_timeout(1200) pend2 = page.text_content("#pendBody") or "" if uniq in pend2: errors.append("approve did not drain the queue") # send-test tab publishes for real page.click("#tabSend") page.fill("#s_msg", "hello from playwright %dx%d" % (w, h)) page.click("#sendBtn") page.wait_for_timeout(1500) pubs = http_json("http://127.0.0.1:%d/__publishes" % PORT) if not any("hello from playwright" in str(p.get("message", "")) for p in pubs.get("published", [])): errors.append("%s: UI send never reached the mock ntfy" % tag) # log tab shows daemon lines page.click("#tabLog") page.wait_for_selector("#logBox", timeout=15000) page.click("#logBtn") page.wait_for_timeout(1000) logt = page.text_content("#logBox") or "" if "daemon start" not in logt and "subscribed" not in logt: errors.append("%s: log tab has no daemon lines" % tag) if console: errors.append("%s: console: %s" % (tag, console[:3])) page.screenshot(path=os.path.join( DOCS, "ui-%d-%s.png" % (w, theme)), full_page=(w != 1440)) page.close() browser.close() httpd.shutdown() if errors: print("FAILURES:", file=sys.stderr) for e in errors: print(" -", e, file=sys.stderr) rc = 1 else: print("e2e ok - %d viewport/theme combinations, screenshots in docs/" % (len(VIEWPORTS) * len(THEMES))) rc = 0 finally: try: if daemon_proc and daemon_proc.poll() is None: pidf = os.path.join(CONN, "plugin_ntfy", "daemon.pid") if os.path.exists(pidf): os.kill(int(open(pidf).read().strip()), 15) daemon_proc.terminate() except Exception: pass mockd.kill() return rc if __name__ == "__main__": sys.exit(main())