#!/usr/bin/env python3 """tests/e2e.py - viewport + interaction checks for the plugin_fetch page. Serves the plugin through a small CGI-ish HTTP shim on a loopback port, starts tests/mockd.py so the page has something real to fetch, 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 URL box, the fetch button, the tabs and the policy switch render * a real fetch round-trip lands Markdown in the output pane * the metadata strip fills in (status / type / bytes / content length) * Next/Prev pagination walks a long document * the Raw tab shows the untouched HTML * the SSRF policy switch round-trips through the node API * 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, quote ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_fetch") DOCS = os.path.join(ROOT, "docs") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] PW = "e2e-node-password" MOCK_PORT = 18780 MOCK = "http://127.0.0.1:%d" % MOCK_PORT class Handler(http.server.BaseHTTPRequestHandler): conf_dir = "" 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["SX_CONNECTOR_DIR"] = self.conf_dir env["BOT_PASSWORD"] = PW env["CONTENT_LENGTH"] = str(len(body)) # the fixture listeners are loopback; the suite is the only reason # the plugin ever agrees to talk to them env["FETCH_ALLOW_PRIVATE"] = "1" # forward the header the page sets, so the shim behaves like the node if self.headers.get("X-Bot-Password"): env["HTTP_X_BOT_PASSWORD"] = self.headers.get("X-Bot-Password") 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 = "text/html; 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", help="exit 2 when Playwright is not installed") args = ap.parse_args() try: from playwright.sync_api import sync_playwright except Exception: print("playwright not installed - skipping e2e (offline suite is unaffected)") return 2 if args.strict else 0 if not os.path.exists(BIN): print("plugin_fetch not built - run make first") return 1 work = os.path.join("/tmp", "fetch-e2e-%d" % os.getpid()) conf = os.path.join(work, "conf") os.makedirs(conf, exist_ok=True) # the fixture server (plain HTTP only - the page never does TLS) cert = os.path.join(work, "cert.pem") key = os.path.join(work, "key.pem") subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "2", "-keyout", key, "-out", cert, "-subj", "/CN=test.invalid"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) mock = subprocess.Popen([sys.executable, os.path.join(ROOT, "tests", "mockd.py"), "http", str(MOCK_PORT)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) for _ in range(60): try: import urllib.request with urllib.request.urlopen(MOCK + "/plain", timeout=1) as r: if r.status == 200: break except Exception: time.sleep(0.1) Handler.conf_dir = conf httpd = socketserver.ThreadingTCPServer(("127.0.0.1", 0), Handler) httpd.allow_reuse_address = True port = httpd.server_address[1] threading.Thread(target=httpd.serve_forever, daemon=True).start() base = "http://127.0.0.1:%d/?pwd=%s" % (port, quote(PW)) os.makedirs(DOCS, exist_ok=True) failures = [] checks = 0 def ok(cond, label): nonlocal checks checks += 1 if not cond: failures.append(label) print(" FAIL %s" % label) 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}) errors = [] page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None) page.on("pageerror", lambda e: errors.append(str(e))) page.goto(base + "&theme=" + theme, wait_until="load") tag = "%dx%d-%s" % (w, h, theme) ok(page.locator("#url").is_visible(), "%s: url box" % tag) ok(page.locator("#go").is_visible(), "%s: fetch button" % tag) ok(page.locator("#tabmd").is_visible(), "%s: markdown tab" % tag) ok(page.locator("#tabraw").is_visible(), "%s: raw tab" % tag) ok(page.locator("#allowpriv").is_visible(), "%s: policy switch" % tag) ok(page.evaluate("document.documentElement.scrollWidth <= " "document.documentElement.clientWidth + 1"), "%s: no horizontal overflow" % tag) ok(len(errors) == 0, "%s: no console errors (%s)" % (tag, "; ".join(errors[:2]))) # a real round-trip through the CGI page.fill("#url", MOCK + "/article") page.fill("#maxlen", "400") page.click("#go") page.wait_for_selector("#meta", state="visible", timeout=15000) out = page.inner_text("#out") ok("Widgets and Gadgets" in out, "%s: markdown rendered" % tag) ok("##" in out or "-" in out, "%s: structure preserved" % tag) ok("SHOULD_NOT_APPEAR" not in out, "%s: boilerplate stripped" % tag) ok(page.inner_text("#mStatus").strip() == "200", "%s: status pill says 200" % tag) ok(page.inner_text("#mType").startswith("text/html"), "%s: content type shown" % tag) ok(page.inner_text("#mBytes").strip().isdigit() and int(page.inner_text("#mBytes")) > 0, "%s: bytes read shown" % tag) ok(page.inner_text("#mLen").strip().isdigit(), "%s: content length shown" % tag) # pagination across the same document page.fill("#url", MOCK + "/big") page.fill("#maxlen", "1000") page.fill("#start", "0") page.click("#go") page.wait_for_timeout(600) first = page.inner_text("#out") ok("Paragraph number 000" in first, "%s: first chunk" % tag) if page.locator("#pager").is_visible(): page.click("#pager button:has-text('Next')") page.wait_for_timeout(600) second = page.inner_text("#out") ok("Paragraph number 000" not in second or first != second, "%s: next chunk differs" % tag) ok(int(page.input_value("#start")) > 0, "%s: start_index advanced" % tag) page.click("#pager button:has-text('Prev')") page.wait_for_timeout(600) ok(page.input_value("#start") == "0", "%s: prev returned" % tag) else: ok(False, "%s: pager visible on a long document" % tag) # the raw tab page.fill("#url", MOCK + "/article") page.click("#tabraw") page.click("#go") page.wait_for_timeout(700) ok("" in page.inner_text("#out"), "%s: raw tab shows html" % tag) page.click("#tabmd") # the policy switch round-trips through the node API page.click("#allowpriv", force=True) page.wait_for_timeout(400) page.reload(wait_until="load") ok(page.locator("#allowpriv").is_checked(), "%s: policy switch persisted" % tag) page.click("#allowpriv", force=True) page.wait_for_timeout(400) # an error path stays readable page.fill("#url", "ftp://example.invalid/x") page.click("#go") page.wait_for_timeout(600) ok("scheme" in page.inner_text("#out").lower(), "%s: refusal surfaced in the pane" % tag) page.screenshot(path=os.path.join( DOCS, "fetch-%s.png" % tag), full_page=False) page.close() browser.close() httpd.shutdown() mock.terminate() print("%d checks, %d failures" % (checks, len(failures))) for f in failures: print(" - %s" % f) return 1 if failures else 0 if __name__ == "__main__": sys.exit(main())