| 1 | #!/usr/bin/env python3 |
| 2 | """tests/e2e.py - viewport + behaviour checks for the plugin_websearch page. |
| 3 | |
| 4 | Serves the plugin through a small CGI shim on a loopback port, points every |
| 5 | provider at tests/mockapi.py, opens the page with Playwright at 1440 / 1024 / |
| 6 | 390 CSS pixels in both themes, and asserts: |
| 7 | |
| 8 | * no console error and no page error at any viewport |
| 9 | * scrollWidth <= innerWidth (no horizontal overflow) |
| 10 | * all six backends render with the right ready / no-key pill |
| 11 | * a live search renders the results, the answer block and the meta line |
| 12 | * the provider switcher changes the default and the next search uses it |
| 13 | * a provider with no key shows the provider's own message, not a blank list |
| 14 | * saving a key updates the pill and never echoes the key back |
| 15 | * screenshots land in docs/ for the README |
| 16 | |
| 17 | Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays |
| 18 | dependency-free. |
| 19 | |
| 20 | python3 tests/e2e.py # run if Playwright is available |
| 21 | python3 tests/e2e.py --strict # exit 2 when Playwright is missing |
| 22 | python3 tests/e2e.py --shots /tmp # write the PNGs somewhere other than docs/ |
| 23 | """ |
| 24 | |
| 25 | import argparse |
| 26 | import http.server |
| 27 | import json |
| 28 | import os |
| 29 | import subprocess |
| 30 | import sys |
| 31 | import threading |
| 32 | from urllib.parse import urlparse, parse_qs |
| 33 | |
| 34 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 35 | BIN = os.path.join(ROOT, "plugin_websearch") |
| 36 | MOCKAPI = os.path.join(ROOT, "tests", "mockapi.py") |
| 37 | DOCS = os.path.join(ROOT, "docs") |
| 38 | WORK = os.path.join("/tmp", "ws-e2e") |
| 39 | VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] |
| 40 | THEMES = ["dark", "light"] |
| 41 | |
| 42 | FAILS = [] |
| 43 | |
| 44 | |
| 45 | def ok(desc): |
| 46 | print(" ok %s" % desc) |
| 47 | |
| 48 | |
| 49 | def bad(desc, detail=""): |
| 50 | FAILS.append(desc) |
| 51 | print(" FAIL %s%s" % (desc, (" (" + str(detail)[:300] + ")") if detail else "")) |
| 52 | |
| 53 | |
| 54 | def start_mock(): |
| 55 | os.makedirs(WORK, exist_ok=True) |
| 56 | portfile = os.path.join(WORK, "port") |
| 57 | log = os.path.join(WORK, "req.jsonl") |
| 58 | if os.path.exists(portfile): |
| 59 | os.unlink(portfile) |
| 60 | if os.path.exists(log): |
| 61 | os.unlink(log) |
| 62 | proc = subprocess.Popen( |
| 63 | [sys.executable, MOCKAPI, "--portfile", portfile, "--log", log], |
| 64 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 65 | for _ in range(200): |
| 66 | if os.path.exists(portfile) and os.path.getsize(portfile): |
| 67 | break |
| 68 | threading.Event().wait(0.05) |
| 69 | with open(portfile) as f: |
| 70 | port = int(f.read().strip()) |
| 71 | return proc, "http://127.0.0.1:%d" % port, log |
| 72 | |
| 73 | |
| 74 | class Handler(http.server.BaseHTTPRequestHandler): |
| 75 | """Runs the binary as a CGI: env from the request, stdin from the body.""" |
| 76 | |
| 77 | def _run(self, method): |
| 78 | u = urlparse(self.path) |
| 79 | length = int(self.headers.get("Content-Length") or 0) |
| 80 | body = self.rfile.read(length) if length else b"" |
| 81 | env = dict(os.environ) |
| 82 | env["QUERY_STRING"] = u.query |
| 83 | env["REQUEST_METHOD"] = method |
| 84 | env.pop("BOT_PASSWORD", None) |
| 85 | env["CONTENT_LENGTH"] = str(len(body)) |
| 86 | env["SWEBSEARCH_CONFIG_DIR"] = os.path.join(WORK, "cfg") |
| 87 | if "action=search" in u.query or method == "POST": |
| 88 | pass |
| 89 | out = subprocess.run([BIN], input=body, capture_output=True, env=env, |
| 90 | timeout=120).stdout |
| 91 | sep = out.find(b"\r\n\r\n") |
| 92 | headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" |
| 93 | payload = out[sep + 4:] if sep >= 0 else out |
| 94 | status = 200 |
| 95 | ctype = "application/json; charset=utf-8" |
| 96 | for line in headers.splitlines(): |
| 97 | low = line.lower() |
| 98 | if low.startswith("content-type:"): |
| 99 | ctype = line.split(":", 1)[1].strip() |
| 100 | elif low.startswith("status:"): |
| 101 | try: |
| 102 | status = int(line.split(":", 1)[1].strip().split()[0]) |
| 103 | except (IndexError, ValueError): |
| 104 | status = 200 |
| 105 | self.send_response(status) |
| 106 | self.send_header("Content-Type", ctype) |
| 107 | self.send_header("Cache-Control", "no-store") |
| 108 | self.send_header("Content-Length", str(len(payload))) |
| 109 | self.end_headers() |
| 110 | self.wfile.write(payload) |
| 111 | |
| 112 | def do_GET(self): # noqa: N802 |
| 113 | self._run("GET") |
| 114 | |
| 115 | def do_POST(self): # noqa: N802 |
| 116 | self._run("POST") |
| 117 | |
| 118 | def log_message(self, *_a): |
| 119 | pass |
| 120 | |
| 121 | |
| 122 | def main(): |
| 123 | ap = argparse.ArgumentParser() |
| 124 | ap.add_argument("--strict", action="store_true") |
| 125 | ap.add_argument("--shots", default=DOCS, |
| 126 | help="where the PNGs go (default docs/, the committed README set)") |
| 127 | args = ap.parse_args() |
| 128 | |
| 129 | try: |
| 130 | from playwright.sync_api import sync_playwright |
| 131 | except ImportError: |
| 132 | print("playwright not installed - skipping the viewport suite") |
| 133 | return 2 if args.strict else 0 |
| 134 | |
| 135 | if not os.access(BIN, os.X_OK): |
| 136 | bad("plugin_websearch binary is missing (run make first)") |
| 137 | return 1 |
| 138 | |
| 139 | shots = args.shots |
| 140 | os.makedirs(shots, exist_ok=True) |
| 141 | mock, mock_base, log = start_mock() |
| 142 | os.environ["WEBSEARCH_MOCK_BASE"] = mock_base |
| 143 | os.environ["WEBSEARCH_SEARXNG_BASE"] = mock_base + "/searxng" |
| 144 | os.environ["BRAVE_API_KEY"] = "BRV-TEST-KEY-1" |
| 145 | os.environ["TAVILY_API_KEY"] = "TVL-TEST-KEY-1" |
| 146 | os.environ["EXA_API_KEY"] = "" |
| 147 | os.environ["PERPLEXITY_API_KEY"] = "" |
| 148 | os.environ["WEBSEARCH_MOCK_BASE"] = mock_base |
| 149 | cfg = os.path.join(WORK, "cfg") |
| 150 | os.makedirs(cfg, exist_ok=True) |
| 151 | for name in ("config.json",): |
| 152 | p = os.path.join(cfg, name) |
| 153 | if os.path.exists(p): |
| 154 | os.unlink(p) |
| 155 | |
| 156 | srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) |
| 157 | port = srv.server_address[1] |
| 158 | threading.Thread(target=srv.serve_forever, daemon=True).start() |
| 159 | base = "http://127.0.0.1:%d/plugin_websearch" % port |
| 160 | |
| 161 | try: |
| 162 | with sync_playwright() as p: |
| 163 | browser = p.chromium.launch() |
| 164 | for theme in THEMES: |
| 165 | for w, h in VIEWPORTS: |
| 166 | tag = "%dx%d-%s" % (w, h, theme) |
| 167 | page = browser.new_page(viewport={"width": w, "height": h}) |
| 168 | errors = [] |
| 169 | page.on("console", lambda m: errors.append(m.text) |
| 170 | if m.type == "error" else None) |
| 171 | page.on("pageerror", lambda e: errors.append(str(e))) |
| 172 | page.goto("%s?theme=%s" % (base, theme), wait_until="networkidle") |
| 173 | page.wait_for_selector(".prov", timeout=15000) |
| 174 | |
| 175 | sw = page.evaluate("document.documentElement.scrollWidth") |
| 176 | iw = page.evaluate("window.innerWidth") |
| 177 | if sw <= iw: |
| 178 | ok("%s: no horizontal overflow (%d <= %d)" % (tag, sw, iw)) |
| 179 | else: |
| 180 | bad("%s: horizontal overflow %d > %d" % (tag, sw, iw)) |
| 181 | if not errors: |
| 182 | ok("%s: no console errors" % tag) |
| 183 | else: |
| 184 | bad("%s: console errors" % tag, errors[:3]) |
| 185 | |
| 186 | n = page.evaluate("document.querySelectorAll('.prov').length") |
| 187 | if n == 6: |
| 188 | ok("%s: all six backends render" % tag) |
| 189 | else: |
| 190 | bad("%s: %d backends rendered, want 6" % (tag, n)) |
| 191 | |
| 192 | applied = page.evaluate( |
| 193 | "document.documentElement.getAttribute('data-theme')") |
| 194 | if applied == theme: |
| 195 | ok("%s: ?theme= applied before paint" % tag) |
| 196 | else: |
| 197 | bad("%s: data-theme is %r, want %r" % (tag, applied, theme)) |
| 198 | |
| 199 | rules = page.evaluate( |
| 200 | "Array.from(document.styleSheets).reduce(function(n,s){" |
| 201 | "try{return n+s.cssRules.length}catch(e){return n}},0)") |
| 202 | if rules > 20: |
| 203 | ok("%s: every stylesheet parsed (%d rules)" % (tag, rules)) |
| 204 | else: |
| 205 | bad("%s: only %d CSS rules survived" % (tag, rules)) |
| 206 | |
| 207 | if theme == "dark" and w == 1440: |
| 208 | # A live search through the page's own POST path. |
| 209 | page.fill("#q", "rust lang") |
| 210 | page.select_option("#providerSel", "brave") |
| 211 | page.click("#go") |
| 212 | page.wait_for_selector(".res", timeout=20000) |
| 213 | rows = page.evaluate("document.querySelectorAll('.res').length") |
| 214 | if rows >= 2: |
| 215 | ok("a live search rendered %d results" % rows) |
| 216 | else: |
| 217 | bad("a live search rendered %d results" % rows) |
| 218 | meta = page.inner_text("#runMeta") |
| 219 | if "brave" in meta and "ms" in meta: |
| 220 | ok("the meta line names the provider and the time") |
| 221 | else: |
| 222 | bad("meta line is %r" % meta) |
| 223 | if not page.inner_text("#err").strip(): |
| 224 | ok("no error banner on a successful search") |
| 225 | else: |
| 226 | bad("error banner: %r" % page.inner_text("#err")) |
| 227 | |
| 228 | # Swap to Tavily (key set) and search again. |
| 229 | page.select_option("#providerSel", "tavily") |
| 230 | page.click("#go") |
| 231 | page.wait_for_function( |
| 232 | "document.querySelectorAll('.res').length > 0 && " |
| 233 | "document.getElementById('runMeta').textContent.indexOf('tavily') >= 0", |
| 234 | timeout=20000) |
| 235 | ok("switching the backend changes the next request") |
| 236 | # The meta line carries the real elapsed time, which is |
| 237 | # 2-7 ms and therefore different on every run. The |
| 238 | # assertion above already proved it says "<n> ms"; the |
| 239 | # PNG pins the wording, not this run's stopwatch. |
| 240 | page.evaluate( |
| 241 | "var m=document.getElementById('runMeta');" |
| 242 | "if(m)m.textContent=m.textContent.replace(/\\d+ ms/,'N ms');" |
| 243 | "var e=document.getElementById('searxng');" |
| 244 | "if(e)e.value='';") |
| 245 | page.screenshot( |
| 246 | path=os.path.join(shots, "ui-search-dark.png"), |
| 247 | full_page=True) |
| 248 | |
| 249 | # Exa has no key: the provider's own message must appear. |
| 250 | page.select_option("#providerSel", "exa") |
| 251 | page.click("#go") |
| 252 | page.wait_for_function( |
| 253 | "document.getElementById('err').textContent.length > 0", |
| 254 | timeout=20000) |
| 255 | err = page.inner_text("#err") |
| 256 | if "Exa needs an API key" in err: |
| 257 | ok("a keyless provider surfaces its own message") |
| 258 | else: |
| 259 | bad("keyless provider message is %r" % err) |
| 260 | if page.evaluate("document.querySelectorAll('.res').length") == 0: |
| 261 | ok("a failed search clears the previous results") |
| 262 | else: |
| 263 | bad("stale results survived a failed search") |
| 264 | |
| 265 | # Save a key -> the pill flips, and the key is not echoed. |
| 266 | page.fill("#k_exa", "EXA-SAVED-E2E") |
| 267 | page.click("#save") |
| 268 | page.wait_for_function( |
| 269 | "document.getElementById('saveMeta').textContent.indexOf('Saved') >= 0", |
| 270 | timeout=15000) |
| 271 | ok("saving a key confirms in the UI") |
| 272 | txt = page.content() |
| 273 | if "EXA-SAVED-E2E" not in txt: |
| 274 | ok("the saved key is never written back into the page") |
| 275 | else: |
| 276 | bad("the page contains the key it just saved") |
| 277 | page.wait_for_function( |
| 278 | "document.querySelector('.prov[data-id=exa] .pill.ok') !== null", |
| 279 | timeout=10000) |
| 280 | ok("the Exa pill flips to key-set after saving") |
| 281 | cfgfile = os.path.join(cfg, "config.json") |
| 282 | if os.path.exists(cfgfile): |
| 283 | mode = oct(os.stat(cfgfile).st_mode & 0o777) |
| 284 | if mode == "0o600": |
| 285 | ok("config.json is mode 0600 on disk") |
| 286 | else: |
| 287 | bad("config.json mode is %s" % mode) |
| 288 | else: |
| 289 | bad("config.json was not written") |
| 290 | |
| 291 | if theme == "dark" and w == 1440: |
| 292 | # The grid images below must be deterministic, and a |
| 293 | # "Saved." pill plus a keyless error banner is a state, |
| 294 | # not the page (lesson from the notes plugin: a suite |
| 295 | # that mutates shared state must put it back before the |
| 296 | # screenshot). |
| 297 | cfgfile = os.path.join(cfg, "config.json") |
| 298 | if os.path.exists(cfgfile): |
| 299 | os.unlink(cfgfile) |
| 300 | page.reload(wait_until="networkidle") |
| 301 | page.wait_for_selector(".prov", timeout=15000) |
| 302 | |
| 303 | # The mock server listens on a fresh port on every run, and |
| 304 | # that port lands in the SearXNG base field - so the PNG |
| 305 | # differed byte-for-byte between two green runs and any |
| 306 | # `git status` after `make e2e` showed seven modified |
| 307 | # screenshots. Blank the harness address so the picture is |
| 308 | # of the page's default state, not of this run's loopback. |
| 309 | page.evaluate("var e=document.getElementById('searxng');" |
| 310 | "if(e)e.value='';") |
| 311 | page.screenshot(path=os.path.join(shots, "ui-%s.png" % tag), |
| 312 | full_page=True) |
| 313 | page.close() |
| 314 | browser.close() |
| 315 | finally: |
| 316 | srv.shutdown() |
| 317 | mock.terminate() |
| 318 | try: |
| 319 | mock.wait(timeout=5) |
| 320 | except Exception: |
| 321 | mock.kill() |
| 322 | |
| 323 | print() |
| 324 | if FAILS: |
| 325 | print("E2E FAIL: %d" % len(FAILS)) |
| 326 | return 1 |
| 327 | print("E2E OK") |
| 328 | return 0 |
| 329 | |
| 330 | |
| 331 | if __name__ == "__main__": |
| 332 | sys.exit(main()) |