#!/usr/bin/env python3 """tests/e2e.py - viewport checks for the plugin_netcheck panel. Serves the plugin through a small CGI-ish HTTP shim on a loopback port, starts the throwaway TCP/HTTP listeners from tests/mockd.py so the panel has something real 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 interface table renders from the fixture and the DNS row appears * a DNS / TCP / HTTP check each produce a result and land in the history * the TCP sparkline appears once there are two or more samples * 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 os import socketserver import subprocess import sys import threading import time from urllib.parse import urlparse ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_netcheck") DOCS = os.path.join(ROOT, "docs") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] IF_FIX = ("lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1," "lo|::1|||6|1," "tap0|198.51.100.7|255.255.255.0|198.51.100.255|4|1," "wlan9|203.0.113.42|255.255.255.0|203.0.113.255|4|0") DNS_FIX = "example.com=93.184.216.34,2606:2800:220:1::34;target=127.0.0.1" MOCK_BASE = 18090 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["NETCHECK_MOCK_IFACES"] = IF_FIX env["NETCHECK_MOCK_DNS"] = DNS_FIX 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 main(): ap = argparse.ArgumentParser() ap.add_argument("--strict", action="store_true") args = ap.parse_args() if not os.path.exists(BIN): print("plugin_netcheck 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) # the listeners the panel will probe mock = subprocess.Popen( [sys.executable, os.path.join(ROOT, "tests", "mockd.py"), str(MOCK_BASE)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) ready = False for _ in range(60): line = mock.stdout.readline() if b"READY" in line: ready = True break time.sleep(0.05) if not ready: print("mock listeners never came up", file=sys.stderr) mock.kill() return 1 open_port = MOCK_BASE + 1 socketserver.TCPServer.allow_reuse_address = True try: httpd = socketserver.TCPServer(("127.0.0.1", 8099), Handler) except OSError as exc: print("could not bind 8099: %s" % exc, file=sys.stderr) mock.kill() return 1 th = threading.Thread(target=httpd.serve_forever, daemon=True) th.start() base = "http://127.0.0.1:8099/" errors = [] shots = 0 with sync_playwright() as p: browser = p.chromium.launch() for w, h in VIEWPORTS: for theme in THEMES: page = browser.new_page(viewport={"width": w, "height": h}) console = [] page.on("console", lambda m: console.append(m.type + ": " + m.text) if m.type in ("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("#ifrows tr", timeout=15000) # the fixture must render four interface rows and one nameserver rows = page.eval_on_selector_all("#ifrows tr", "els => els.length") if rows != 4: errors.append("%dx%d %s: expected 4 iface rows, got %s" % (w, h, theme, rows)) ns = page.eval_on_selector_all("#nsList .tag", "els => els.length") if ns < 1: errors.append("%dx%d %s: no nameserver chips" % (w, h, theme)) # --- DNS tab --- page.fill("#inp", "example.com") page.click("#goBtn") page.wait_for_selector("#resKv .v", timeout=15000) state = page.text_content("#resState") or "" if "resolved" not in state: errors.append("%dx%d %s: dns did not resolve (%s)" % (w, h, theme, state.strip())) # --- TCP tab, three times so the sparkline has samples --- page.click("#tabTcp") page.fill("#inp", "target") page.fill("#port", str(open_port)) for _ in range(3): page.click("#goBtn") page.wait_for_selector("#resKv .v", timeout=15000) disp = page.evaluate( "() => getComputedStyle(document.getElementById('spark')).display") if disp == "none": errors.append("%dx%d %s: sparkline stayed hidden after 3 samples" % (w, h, theme)) dots = page.eval_on_selector_all("#spark circle", "els => els.length") if dots < 2: errors.append("%dx%d %s: sparkline has %s points" % (w, h, theme, dots)) hist = page.eval_on_selector_all("#hist li", "els => els.length") if hist < 4: errors.append("%dx%d %s: history has %s entries, want >=4" % (w, h, theme, hist)) # --- HTTP tab --- page.click("#tabHttp") page.fill("#inp", "http://target:%d/index.html" % open_port) page.click("#goBtn") page.wait_for_selector("#resKv .v", timeout=15000) state = (page.text_content("#resState") or "").strip() if "200" not in state: errors.append("%dx%d %s: http did not report 200 (%s)" % (w, h, theme, state)) # land on the TCP tab so the screenshot shows the sparkline with # samples in it - a chart nobody can see proves nothing. One of # the samples is taken against a closed port so the series is not # perfectly flat: a flat line on a chart is ambiguous, and a # screenshot that cannot be read is not evidence. page.click("#tabTcp") page.fill("#inp", "127.0.0.1") page.fill("#port", "1") page.click("#goBtn") page.wait_for_selector("#resKv .v", timeout=15000) page.fill("#inp", "target") page.fill("#port", str(open_port)) page.click("#goBtn") page.wait_for_selector("#resKv .v", timeout=15000) spark_disp = page.evaluate( "() => getComputedStyle(document.getElementById('spark')).display") if spark_disp == "none": errors.append("%dx%d %s: sparkline hidden on the tcp tab" % (w, h, theme)) svg_h = page.evaluate( "() => document.getElementById('spark').getBoundingClientRect().height") if svg_h < 20: errors.append("%dx%d %s: sparkline renders only %s px tall" % (w, h, theme, svg_h)) # --- layout: no horizontal overflow anywhere --- overflow = page.evaluate( "() => document.documentElement.scrollWidth - window.innerWidth") if overflow > 0: errors.append("%dx%d %s: horizontal overflow %spx" % (w, h, theme, overflow)) body_over = page.evaluate( "() => document.body.scrollWidth - window.innerWidth") if body_over > 0: errors.append("%dx%d %s: body overflow %spx" % (w, h, theme, body_over)) # the theme really applied applied = page.evaluate( "() => document.documentElement.getAttribute('data-theme')") if applied != theme: errors.append("%dx%d %s: data-theme is %s" % (w, h, theme, applied)) bg = page.evaluate( "() => getComputedStyle(document.body).backgroundColor") if theme == "dark" and bg not in ("rgb(0, 0, 0)", "rgba(0, 0, 0, 1)"): errors.append("%dx%d %s: dark body background is %s" % (w, h, theme, bg)) if theme == "light" and bg not in ("rgb(245, 245, 247)", "rgba(245, 245, 247, 1)"): errors.append("%dx%d %s: light body background is %s" % (w, h, theme, bg)) if console: errors.append("%dx%d %s: console %s" % (w, h, theme, "; ".join(console[:4]))) # bring the sparkline into the frame before shooting page.evaluate( "() => document.getElementById('spark')" ".scrollIntoView({block:'center'})") page.wait_for_timeout(120) tag = "%d" % w path = os.path.join(DOCS, "ui-%s-%s.png" % (tag, theme)) page.screenshot(path=path, full_page=False) shots += 1 page.close() # embed mode hides the bot-owned chrome page = browser.new_page(viewport={"width": 390, "height": 500}) page.goto(base + "?embed=1&theme=dark", wait_until="networkidle") page.wait_for_selector("#ifrows tr", timeout=15000) vis = page.evaluate( "() => document.getElementById('thBtn').offsetWidth") if vis: errors.append("embed: the theme toggle is still visible (%spx)" % vis) vis2 = page.evaluate( "() => document.querySelector('.embed-hide') !== null && " "getComputedStyle(document.querySelector('.embed-hide')).display") if vis2 != "none": errors.append("embed: back link not hidden (%s)" % vis2) page.screenshot(path=os.path.join(DOCS, "ui-390-embed-dark.png")) shots += 1 page.close() # a short floating window: the panel must not overflow vertically either page = browser.new_page(viewport={"width": 420, "height": 320}) page.goto(base + "?embed=1&theme=light", wait_until="networkidle") page.wait_for_selector("#ifrows tr", timeout=15000) ov = page.evaluate( "() => document.documentElement.scrollWidth - window.innerWidth") if ov > 0: errors.append("floating window: horizontal overflow %spx" % ov) shots += 1 page.close() browser.close() httpd.shutdown() mock.kill() print("screenshots written: %d -> %s" % (shots, DOCS)) if errors: for e in errors[:20]: print("FAIL: %s" % e) print("e2e FAILED (%d problems)" % len(errors)) return 1 print("e2e OK - %d viewports x 2 themes, no console errors, no overflow" % len(VIEWPORTS)) return 0 if __name__ == "__main__": sys.exit(main())