| 1 | #!/usr/bin/env python3 |
| 2 | """tests/e2e.py - viewport checks for the plugin_netcheck panel. |
| 3 | |
| 4 | Serves the plugin through a small CGI-ish HTTP shim on a loopback port, starts |
| 5 | the throwaway TCP/HTTP listeners from tests/mockd.py so the panel has something |
| 6 | real to talk to, opens it with Playwright at 1440 / 1024 / 390 CSS pixels in |
| 7 | both themes, and asserts: |
| 8 | |
| 9 | * no console error and no page error at any viewport |
| 10 | * scrollWidth <= innerWidth (no horizontal overflow) |
| 11 | * the interface table renders from the fixture and the DNS row appears |
| 12 | * a DNS / TCP / HTTP check each produce a result and land in the history |
| 13 | * the TCP sparkline appears once there are two or more samples |
| 14 | * screenshots land in docs/ for the README |
| 15 | |
| 16 | Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays |
| 17 | dependency-free. |
| 18 | |
| 19 | python3 tests/e2e.py # run if Playwright is available |
| 20 | python3 tests/e2e.py --strict # exit 2 when Playwright is missing |
| 21 | """ |
| 22 | |
| 23 | import argparse |
| 24 | import http.server |
| 25 | import os |
| 26 | import socketserver |
| 27 | import subprocess |
| 28 | import sys |
| 29 | import threading |
| 30 | import time |
| 31 | from urllib.parse import urlparse |
| 32 | |
| 33 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 34 | BIN = os.path.join(ROOT, "plugin_netcheck") |
| 35 | DOCS = os.path.join(ROOT, "docs") |
| 36 | VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] |
| 37 | THEMES = ["dark", "light"] |
| 38 | |
| 39 | IF_FIX = ("lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1," |
| 40 | "lo|::1|||6|1," |
| 41 | "tap0|198.51.100.7|255.255.255.0|198.51.100.255|4|1," |
| 42 | "wlan9|203.0.113.42|255.255.255.0|203.0.113.255|4|0") |
| 43 | DNS_FIX = "example.com=93.184.216.34,2606:2800:220:1::34;target=127.0.0.1" |
| 44 | |
| 45 | MOCK_BASE = 18090 |
| 46 | |
| 47 | |
| 48 | class Handler(http.server.BaseHTTPRequestHandler): |
| 49 | def _run(self, method): |
| 50 | u = urlparse(self.path) |
| 51 | length = int(self.headers.get("Content-Length") or 0) |
| 52 | body = self.rfile.read(length) if length else b"" |
| 53 | env = dict(os.environ) |
| 54 | env["QUERY_STRING"] = u.query |
| 55 | env["REQUEST_METHOD"] = method |
| 56 | env["NETCHECK_MOCK_IFACES"] = IF_FIX |
| 57 | env["NETCHECK_MOCK_DNS"] = DNS_FIX |
| 58 | env.pop("BOT_PASSWORD", None) |
| 59 | env["CONTENT_LENGTH"] = str(len(body)) |
| 60 | out = subprocess.run( |
| 61 | [BIN], input=body, capture_output=True, env=env, timeout=60 |
| 62 | ).stdout |
| 63 | sep = out.find(b"\r\n\r\n") |
| 64 | headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" |
| 65 | payload = out[sep + 4:] if sep >= 0 else out |
| 66 | status = 200 |
| 67 | ctype = "application/json; charset=utf-8" |
| 68 | for line in headers.splitlines(): |
| 69 | low = line.lower() |
| 70 | if low.startswith("content-type:"): |
| 71 | ctype = line.split(":", 1)[1].strip() |
| 72 | elif low.startswith("status:"): |
| 73 | try: |
| 74 | status = int(line.split(":", 1)[1].strip().split()[0]) |
| 75 | except (IndexError, ValueError): |
| 76 | status = 200 |
| 77 | self.send_response(status) |
| 78 | self.send_header("Content-Type", ctype) |
| 79 | self.send_header("Cache-Control", "no-store") |
| 80 | self.send_header("Content-Length", str(len(payload))) |
| 81 | self.end_headers() |
| 82 | self.wfile.write(payload) |
| 83 | |
| 84 | def do_GET(self): # noqa: N802 |
| 85 | self._run("GET") |
| 86 | |
| 87 | def do_POST(self): # noqa: N802 |
| 88 | self._run("POST") |
| 89 | |
| 90 | def log_message(self, *_a): |
| 91 | pass |
| 92 | |
| 93 | |
| 94 | def main(): |
| 95 | ap = argparse.ArgumentParser() |
| 96 | ap.add_argument("--strict", action="store_true") |
| 97 | args = ap.parse_args() |
| 98 | |
| 99 | if not os.path.exists(BIN): |
| 100 | print("plugin_netcheck is not built; run make first", file=sys.stderr) |
| 101 | return 1 |
| 102 | |
| 103 | try: |
| 104 | from playwright.sync_api import sync_playwright |
| 105 | except Exception: |
| 106 | if args.strict: |
| 107 | print("playwright is not installed", file=sys.stderr) |
| 108 | return 2 |
| 109 | print("playwright not available - skipping e2e (offline suite still runs)") |
| 110 | return 0 |
| 111 | |
| 112 | os.makedirs(DOCS, exist_ok=True) |
| 113 | |
| 114 | # the listeners the panel will probe |
| 115 | mock = subprocess.Popen( |
| 116 | [sys.executable, os.path.join(ROOT, "tests", "mockd.py"), str(MOCK_BASE)], |
| 117 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 118 | ) |
| 119 | ready = False |
| 120 | for _ in range(60): |
| 121 | line = mock.stdout.readline() |
| 122 | if b"READY" in line: |
| 123 | ready = True |
| 124 | break |
| 125 | time.sleep(0.05) |
| 126 | if not ready: |
| 127 | print("mock listeners never came up", file=sys.stderr) |
| 128 | mock.kill() |
| 129 | return 1 |
| 130 | |
| 131 | open_port = MOCK_BASE + 1 |
| 132 | |
| 133 | socketserver.TCPServer.allow_reuse_address = True |
| 134 | try: |
| 135 | httpd = socketserver.TCPServer(("127.0.0.1", 8099), Handler) |
| 136 | except OSError as exc: |
| 137 | print("could not bind 8099: %s" % exc, file=sys.stderr) |
| 138 | mock.kill() |
| 139 | return 1 |
| 140 | th = threading.Thread(target=httpd.serve_forever, daemon=True) |
| 141 | th.start() |
| 142 | |
| 143 | base = "http://127.0.0.1:8099/" |
| 144 | errors = [] |
| 145 | shots = 0 |
| 146 | |
| 147 | with sync_playwright() as p: |
| 148 | browser = p.chromium.launch() |
| 149 | for w, h in VIEWPORTS: |
| 150 | for theme in THEMES: |
| 151 | page = browser.new_page(viewport={"width": w, "height": h}) |
| 152 | console = [] |
| 153 | page.on("console", lambda m: console.append(m.type + ": " + m.text) |
| 154 | if m.type in ("error",) else None) |
| 155 | page.on("pageerror", lambda e: console.append("pageerror: %s" % e)) |
| 156 | page.goto(base + "?theme=" + theme, wait_until="networkidle") |
| 157 | page.wait_for_selector("#ifrows tr", timeout=15000) |
| 158 | |
| 159 | # the fixture must render four interface rows and one nameserver |
| 160 | rows = page.eval_on_selector_all("#ifrows tr", "els => els.length") |
| 161 | if rows != 4: |
| 162 | errors.append("%dx%d %s: expected 4 iface rows, got %s" |
| 163 | % (w, h, theme, rows)) |
| 164 | ns = page.eval_on_selector_all("#nsList .tag", "els => els.length") |
| 165 | if ns < 1: |
| 166 | errors.append("%dx%d %s: no nameserver chips" % (w, h, theme)) |
| 167 | |
| 168 | # --- DNS tab --- |
| 169 | page.fill("#inp", "example.com") |
| 170 | page.click("#goBtn") |
| 171 | page.wait_for_selector("#resKv .v", timeout=15000) |
| 172 | state = page.text_content("#resState") or "" |
| 173 | if "resolved" not in state: |
| 174 | errors.append("%dx%d %s: dns did not resolve (%s)" |
| 175 | % (w, h, theme, state.strip())) |
| 176 | |
| 177 | # --- TCP tab, three times so the sparkline has samples --- |
| 178 | page.click("#tabTcp") |
| 179 | page.fill("#inp", "target") |
| 180 | page.fill("#port", str(open_port)) |
| 181 | for _ in range(3): |
| 182 | page.click("#goBtn") |
| 183 | page.wait_for_selector("#resKv .v", timeout=15000) |
| 184 | disp = page.evaluate( |
| 185 | "() => getComputedStyle(document.getElementById('spark')).display") |
| 186 | if disp == "none": |
| 187 | errors.append("%dx%d %s: sparkline stayed hidden after 3 samples" |
| 188 | % (w, h, theme)) |
| 189 | dots = page.eval_on_selector_all("#spark circle", "els => els.length") |
| 190 | if dots < 2: |
| 191 | errors.append("%dx%d %s: sparkline has %s points" % (w, h, theme, dots)) |
| 192 | hist = page.eval_on_selector_all("#hist li", "els => els.length") |
| 193 | if hist < 4: |
| 194 | errors.append("%dx%d %s: history has %s entries, want >=4" |
| 195 | % (w, h, theme, hist)) |
| 196 | |
| 197 | # --- HTTP tab --- |
| 198 | page.click("#tabHttp") |
| 199 | page.fill("#inp", "http://target:%d/index.html" % open_port) |
| 200 | page.click("#goBtn") |
| 201 | page.wait_for_selector("#resKv .v", timeout=15000) |
| 202 | state = (page.text_content("#resState") or "").strip() |
| 203 | if "200" not in state: |
| 204 | errors.append("%dx%d %s: http did not report 200 (%s)" |
| 205 | % (w, h, theme, state)) |
| 206 | |
| 207 | # land on the TCP tab so the screenshot shows the sparkline with |
| 208 | # samples in it - a chart nobody can see proves nothing. One of |
| 209 | # the samples is taken against a closed port so the series is not |
| 210 | # perfectly flat: a flat line on a chart is ambiguous, and a |
| 211 | # screenshot that cannot be read is not evidence. |
| 212 | page.click("#tabTcp") |
| 213 | page.fill("#inp", "127.0.0.1") |
| 214 | page.fill("#port", "1") |
| 215 | page.click("#goBtn") |
| 216 | page.wait_for_selector("#resKv .v", timeout=15000) |
| 217 | page.fill("#inp", "target") |
| 218 | page.fill("#port", str(open_port)) |
| 219 | page.click("#goBtn") |
| 220 | page.wait_for_selector("#resKv .v", timeout=15000) |
| 221 | spark_disp = page.evaluate( |
| 222 | "() => getComputedStyle(document.getElementById('spark')).display") |
| 223 | if spark_disp == "none": |
| 224 | errors.append("%dx%d %s: sparkline hidden on the tcp tab" |
| 225 | % (w, h, theme)) |
| 226 | svg_h = page.evaluate( |
| 227 | "() => document.getElementById('spark').getBoundingClientRect().height") |
| 228 | if svg_h < 20: |
| 229 | errors.append("%dx%d %s: sparkline renders only %s px tall" |
| 230 | % (w, h, theme, svg_h)) |
| 231 | |
| 232 | # --- layout: no horizontal overflow anywhere --- |
| 233 | overflow = page.evaluate( |
| 234 | "() => document.documentElement.scrollWidth - window.innerWidth") |
| 235 | if overflow > 0: |
| 236 | errors.append("%dx%d %s: horizontal overflow %spx" |
| 237 | % (w, h, theme, overflow)) |
| 238 | body_over = page.evaluate( |
| 239 | "() => document.body.scrollWidth - window.innerWidth") |
| 240 | if body_over > 0: |
| 241 | errors.append("%dx%d %s: body overflow %spx" |
| 242 | % (w, h, theme, body_over)) |
| 243 | |
| 244 | # the theme really applied |
| 245 | applied = page.evaluate( |
| 246 | "() => document.documentElement.getAttribute('data-theme')") |
| 247 | if applied != theme: |
| 248 | errors.append("%dx%d %s: data-theme is %s" % (w, h, theme, applied)) |
| 249 | bg = page.evaluate( |
| 250 | "() => getComputedStyle(document.body).backgroundColor") |
| 251 | if theme == "dark" and bg not in ("rgb(0, 0, 0)", "rgba(0, 0, 0, 1)"): |
| 252 | errors.append("%dx%d %s: dark body background is %s" |
| 253 | % (w, h, theme, bg)) |
| 254 | if theme == "light" and bg not in ("rgb(245, 245, 247)", |
| 255 | "rgba(245, 245, 247, 1)"): |
| 256 | errors.append("%dx%d %s: light body background is %s" |
| 257 | % (w, h, theme, bg)) |
| 258 | |
| 259 | if console: |
| 260 | errors.append("%dx%d %s: console %s" |
| 261 | % (w, h, theme, "; ".join(console[:4]))) |
| 262 | |
| 263 | # bring the sparkline into the frame before shooting |
| 264 | page.evaluate( |
| 265 | "() => document.getElementById('spark')" |
| 266 | ".scrollIntoView({block:'center'})") |
| 267 | page.wait_for_timeout(120) |
| 268 | |
| 269 | tag = "%d" % w |
| 270 | path = os.path.join(DOCS, "ui-%s-%s.png" % (tag, theme)) |
| 271 | page.screenshot(path=path, full_page=False) |
| 272 | shots += 1 |
| 273 | page.close() |
| 274 | |
| 275 | # embed mode hides the bot-owned chrome |
| 276 | page = browser.new_page(viewport={"width": 390, "height": 500}) |
| 277 | page.goto(base + "?embed=1&theme=dark", wait_until="networkidle") |
| 278 | page.wait_for_selector("#ifrows tr", timeout=15000) |
| 279 | vis = page.evaluate( |
| 280 | "() => document.getElementById('thBtn').offsetWidth") |
| 281 | if vis: |
| 282 | errors.append("embed: the theme toggle is still visible (%spx)" % vis) |
| 283 | vis2 = page.evaluate( |
| 284 | "() => document.querySelector('.embed-hide') !== null && " |
| 285 | "getComputedStyle(document.querySelector('.embed-hide')).display") |
| 286 | if vis2 != "none": |
| 287 | errors.append("embed: back link not hidden (%s)" % vis2) |
| 288 | page.screenshot(path=os.path.join(DOCS, "ui-390-embed-dark.png")) |
| 289 | shots += 1 |
| 290 | page.close() |
| 291 | |
| 292 | # a short floating window: the panel must not overflow vertically either |
| 293 | page = browser.new_page(viewport={"width": 420, "height": 320}) |
| 294 | page.goto(base + "?embed=1&theme=light", wait_until="networkidle") |
| 295 | page.wait_for_selector("#ifrows tr", timeout=15000) |
| 296 | ov = page.evaluate( |
| 297 | "() => document.documentElement.scrollWidth - window.innerWidth") |
| 298 | if ov > 0: |
| 299 | errors.append("floating window: horizontal overflow %spx" % ov) |
| 300 | shots += 1 |
| 301 | page.close() |
| 302 | |
| 303 | browser.close() |
| 304 | |
| 305 | httpd.shutdown() |
| 306 | mock.kill() |
| 307 | |
| 308 | print("screenshots written: %d -> %s" % (shots, DOCS)) |
| 309 | if errors: |
| 310 | for e in errors[:20]: |
| 311 | print("FAIL: %s" % e) |
| 312 | print("e2e FAILED (%d problems)" % len(errors)) |
| 313 | return 1 |
| 314 | print("e2e OK - %d viewports x 2 themes, no console errors, no overflow" |
| 315 | % len(VIEWPORTS)) |
| 316 | return 0 |
| 317 | |
| 318 | |
| 319 | if __name__ == "__main__": |
| 320 | sys.exit(main()) |