#!/usr/bin/env python3 """tests/e2e.py - viewport + behaviour checks for the plugin_websearch page. Serves the plugin through a small CGI shim on a loopback port, points every provider at tests/mockapi.py, opens the page 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) * all six backends render with the right ready / no-key pill * a live search renders the results, the answer block and the meta line * the provider switcher changes the default and the next search uses it * a provider with no key shows the provider's own message, not a blank list * saving a key updates the pill and never echoes the key back * 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 python3 tests/e2e.py --shots /tmp # write the PNGs somewhere other than docs/ """ import argparse import http.server import json import os import subprocess import sys import threading from urllib.parse import urlparse, parse_qs ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_websearch") MOCKAPI = os.path.join(ROOT, "tests", "mockapi.py") DOCS = os.path.join(ROOT, "docs") WORK = os.path.join("/tmp", "ws-e2e") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] FAILS = [] def ok(desc): print(" ok %s" % desc) def bad(desc, detail=""): FAILS.append(desc) print(" FAIL %s%s" % (desc, (" (" + str(detail)[:300] + ")") if detail else "")) def start_mock(): os.makedirs(WORK, exist_ok=True) portfile = os.path.join(WORK, "port") log = os.path.join(WORK, "req.jsonl") if os.path.exists(portfile): os.unlink(portfile) if os.path.exists(log): os.unlink(log) proc = subprocess.Popen( [sys.executable, MOCKAPI, "--portfile", portfile, "--log", log], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) for _ in range(200): if os.path.exists(portfile) and os.path.getsize(portfile): break threading.Event().wait(0.05) with open(portfile) as f: port = int(f.read().strip()) return proc, "http://127.0.0.1:%d" % port, log class Handler(http.server.BaseHTTPRequestHandler): """Runs the binary as a CGI: env from the request, stdin from the body.""" 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.pop("BOT_PASSWORD", None) env["CONTENT_LENGTH"] = str(len(body)) env["SWEBSEARCH_CONFIG_DIR"] = os.path.join(WORK, "cfg") if "action=search" in u.query or method == "POST": pass out = subprocess.run([BIN], input=body, capture_output=True, env=env, timeout=120).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") ap.add_argument("--shots", default=DOCS, help="where the PNGs go (default docs/, the committed README set)") args = ap.parse_args() try: from playwright.sync_api import sync_playwright except ImportError: print("playwright not installed - skipping the viewport suite") return 2 if args.strict else 0 if not os.access(BIN, os.X_OK): bad("plugin_websearch binary is missing (run make first)") return 1 shots = args.shots os.makedirs(shots, exist_ok=True) mock, mock_base, log = start_mock() os.environ["WEBSEARCH_MOCK_BASE"] = mock_base os.environ["WEBSEARCH_SEARXNG_BASE"] = mock_base + "/searxng" os.environ["BRAVE_API_KEY"] = "BRV-TEST-KEY-1" os.environ["TAVILY_API_KEY"] = "TVL-TEST-KEY-1" os.environ["EXA_API_KEY"] = "" os.environ["PERPLEXITY_API_KEY"] = "" os.environ["WEBSEARCH_MOCK_BASE"] = mock_base cfg = os.path.join(WORK, "cfg") os.makedirs(cfg, exist_ok=True) for name in ("config.json",): p = os.path.join(cfg, name) if os.path.exists(p): os.unlink(p) srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) port = srv.server_address[1] threading.Thread(target=srv.serve_forever, daemon=True).start() base = "http://127.0.0.1:%d/plugin_websearch" % port try: with sync_playwright() as p: browser = p.chromium.launch() for theme in THEMES: for w, h in VIEWPORTS: tag = "%dx%d-%s" % (w, h, theme) 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("%s?theme=%s" % (base, theme), wait_until="networkidle") page.wait_for_selector(".prov", timeout=15000) sw = page.evaluate("document.documentElement.scrollWidth") iw = page.evaluate("window.innerWidth") if sw <= iw: ok("%s: no horizontal overflow (%d <= %d)" % (tag, sw, iw)) else: bad("%s: horizontal overflow %d > %d" % (tag, sw, iw)) if not errors: ok("%s: no console errors" % tag) else: bad("%s: console errors" % tag, errors[:3]) n = page.evaluate("document.querySelectorAll('.prov').length") if n == 6: ok("%s: all six backends render" % tag) else: bad("%s: %d backends rendered, want 6" % (tag, n)) applied = page.evaluate( "document.documentElement.getAttribute('data-theme')") if applied == theme: ok("%s: ?theme= applied before paint" % tag) else: bad("%s: data-theme is %r, want %r" % (tag, applied, theme)) rules = page.evaluate( "Array.from(document.styleSheets).reduce(function(n,s){" "try{return n+s.cssRules.length}catch(e){return n}},0)") if rules > 20: ok("%s: every stylesheet parsed (%d rules)" % (tag, rules)) else: bad("%s: only %d CSS rules survived" % (tag, rules)) if theme == "dark" and w == 1440: # A live search through the page's own POST path. page.fill("#q", "rust lang") page.select_option("#providerSel", "brave") page.click("#go") page.wait_for_selector(".res", timeout=20000) rows = page.evaluate("document.querySelectorAll('.res').length") if rows >= 2: ok("a live search rendered %d results" % rows) else: bad("a live search rendered %d results" % rows) meta = page.inner_text("#runMeta") if "brave" in meta and "ms" in meta: ok("the meta line names the provider and the time") else: bad("meta line is %r" % meta) if not page.inner_text("#err").strip(): ok("no error banner on a successful search") else: bad("error banner: %r" % page.inner_text("#err")) # Swap to Tavily (key set) and search again. page.select_option("#providerSel", "tavily") page.click("#go") page.wait_for_function( "document.querySelectorAll('.res').length > 0 && " "document.getElementById('runMeta').textContent.indexOf('tavily') >= 0", timeout=20000) ok("switching the backend changes the next request") # The meta line carries the real elapsed time, which is # 2-7 ms and therefore different on every run. The # assertion above already proved it says " ms"; the # PNG pins the wording, not this run's stopwatch. page.evaluate( "var m=document.getElementById('runMeta');" "if(m)m.textContent=m.textContent.replace(/\\d+ ms/,'N ms');" "var e=document.getElementById('searxng');" "if(e)e.value='';") page.screenshot( path=os.path.join(shots, "ui-search-dark.png"), full_page=True) # Exa has no key: the provider's own message must appear. page.select_option("#providerSel", "exa") page.click("#go") page.wait_for_function( "document.getElementById('err').textContent.length > 0", timeout=20000) err = page.inner_text("#err") if "Exa needs an API key" in err: ok("a keyless provider surfaces its own message") else: bad("keyless provider message is %r" % err) if page.evaluate("document.querySelectorAll('.res').length") == 0: ok("a failed search clears the previous results") else: bad("stale results survived a failed search") # Save a key -> the pill flips, and the key is not echoed. page.fill("#k_exa", "EXA-SAVED-E2E") page.click("#save") page.wait_for_function( "document.getElementById('saveMeta').textContent.indexOf('Saved') >= 0", timeout=15000) ok("saving a key confirms in the UI") txt = page.content() if "EXA-SAVED-E2E" not in txt: ok("the saved key is never written back into the page") else: bad("the page contains the key it just saved") page.wait_for_function( "document.querySelector('.prov[data-id=exa] .pill.ok') !== null", timeout=10000) ok("the Exa pill flips to key-set after saving") cfgfile = os.path.join(cfg, "config.json") if os.path.exists(cfgfile): mode = oct(os.stat(cfgfile).st_mode & 0o777) if mode == "0o600": ok("config.json is mode 0600 on disk") else: bad("config.json mode is %s" % mode) else: bad("config.json was not written") if theme == "dark" and w == 1440: # The grid images below must be deterministic, and a # "Saved." pill plus a keyless error banner is a state, # not the page (lesson from the notes plugin: a suite # that mutates shared state must put it back before the # screenshot). cfgfile = os.path.join(cfg, "config.json") if os.path.exists(cfgfile): os.unlink(cfgfile) page.reload(wait_until="networkidle") page.wait_for_selector(".prov", timeout=15000) # The mock server listens on a fresh port on every run, and # that port lands in the SearXNG base field - so the PNG # differed byte-for-byte between two green runs and any # `git status` after `make e2e` showed seven modified # screenshots. Blank the harness address so the picture is # of the page's default state, not of this run's loopback. page.evaluate("var e=document.getElementById('searxng');" "if(e)e.value='';") page.screenshot(path=os.path.join(shots, "ui-%s.png" % tag), full_page=True) page.close() browser.close() finally: srv.shutdown() mock.terminate() try: mock.wait(timeout=5) except Exception: mock.kill() print() if FAILS: print("E2E FAIL: %d" % len(FAILS)) return 1 print("E2E OK") return 0 if __name__ == "__main__": sys.exit(main())