#!/usr/bin/env python3 """tests/e2e.py - viewport + behaviour checks for the plugin_github page. Serves the plugin through a small CGI shim on a loopback port, points the API base 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) * the status card resolves: API base, token pill, state dir * action=tools renders the five real tools with their required args * Test connection reaches the mock and reports the account * saving a token flips the pill, clears the password field, and never echoes the token back into the DOM * a bad api base surfaces the server's 400 message, not a silent no-op * screenshots land in docs/ and are byte-stable: the state card's ephemeral port and tmp work dir are neutralised before the shutter, so re-running the suite never dirties the git tree (a dirty tree fails `scorpiox-cli-botplugin audit`, which is the publish gate) 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 ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_github") MOCKAPI = os.path.join(ROOT, "tests", "mockapi.py") DOCS = os.path.join(ROOT, "docs") WORK = os.path.join("/tmp", "gh-e2e") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] TOKEN = "GHPAT-E2E-SAVED-1" FAILS = [] def ok(desc, *a): print(" ok %s" % desc) def bad(desc, detail=""): FAILS.append(desc) print(" FAIL %s%s" % (desc, (" (" + str(detail)[:300] + ")") if detail else "")) def check(cond, desc, detail=""): (ok if cond else bad)(desc, detail) def start_mock(): os.makedirs(WORK, exist_ok=True) portfile = os.path.join(WORK, "port") log = os.path.join(WORK, "req.jsonl") for p in (portfile, log): if os.path.exists(p): os.unlink(p) 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 def stabilise(page): """Make the page's volatile facts constant so the committed PNGs are reproducible. Only the display is touched; nothing the assertions read is changed, and this runs after every assertion at its viewport.""" page.evaluate( """() => { const base = document.getElementById('sBase'); if (base) base.textContent = 'http://127.0.0.1:PORT'; const dir = document.getElementById('sDir'); if (dir) dir.textContent = '/home/user/.scorpiox/connectors/plugin_github'; const meta = document.getElementById('saveMeta'); if (meta) meta.textContent = ''; }""") class Handler(http.server.BaseHTTPRequestHandler): """Runs the binary as a CGI: env from the request, stdin from the body. BOT_PASSWORD stays removed from the environment: this shim stands up an open single-user node, which is the configuration a browser reaches with no password juggling (the 401 gate itself is asserted in tests/cgi.py).""" 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.pop("HTTP_X_BOT_PASSWORD", None) env.pop("GITHUB_TOKEN", None) env.pop("GITHUB_API_BASE", None) env["SX_CONNECTOR_DIR"] = os.path.join(WORK, "cfg") env["CONTENT_LENGTH"] = str(len(body)) 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 = "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") 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_github binary is missing (run make first)") return 1 shots = args.shots os.makedirs(shots, exist_ok=True) mock, base, mocklog = start_mock() # a clean install: no token stored yet cfg = os.path.join(WORK, "cfg") os.makedirs(cfg, exist_ok=True) # Seed the base pointing at the mock WITHOUT a token: this is a clean # install, and the suite must never touch the real api.github.com. with open(os.path.join(cfg, "config.json"), "w") as f: json.dump({"api_base": base, "token": ""}, f) os.chmod(os.path.join(cfg, "config.json"), 0o600) srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) port = srv.server_address[1] threading.Thread(target=srv.serve_forever, daemon=True).start() url = "http://127.0.0.1:%d/" % port try: with sync_playwright() as pw: browser = pw.chromium.launch() for w, h in VIEWPORTS: for theme in THEMES: # per-context: the deliberate bad-api-base save below # logs one 400 ON PURPOSE; a shared list would blame every # later viewport for it console_errors = [] ctx = browser.new_context(viewport={"width": w, "height": h}, color_scheme=theme) page = ctx.new_page() page.on("console", lambda m: console_errors.append(m.text) if m.type == "error" else None) page.on("pageerror", lambda e: console_errors.append(str(e))) page.goto(url + "?theme=" + theme, wait_until="networkidle") tag = "%dx%d-%s" % (w, h, theme) if console_errors: bad("no console errors @ " + tag, console_errors[:2]) else: ok("no console errors @ " + tag) ow = page.evaluate("document.documentElement.scrollWidth") iw = page.evaluate("window.innerWidth") check(ow <= iw + 1, "no horizontal overflow @ " + tag, "scrollWidth %d > innerWidth %d" % (ow, iw)) check(page.is_visible("#save") and page.is_visible("#test"), "the controls render @ " + tag) # status resolved from the server page.wait_for_function( "document.getElementById('sBase').textContent.length > 5", timeout=15000) sbase = page.inner_text("#sBase") check(sbase.startswith("http"), "the status card shows the api base @ " + tag, sbase) # the five tools come from action=tools (the MCP schemas) ntools = page.evaluate("document.querySelectorAll('.tool').length") check(ntools == 5, "five agent tools render @ " + tag, ntools) tooltxt = page.inner_text("#tools") check("owner, repo" in tooltxt or "owner" in tooltxt, "required args are shown @ " + tag) # one committed screenshot per viewport + theme (the # README's responsive story is told by these files) stabilise(page) page.screenshot( path=os.path.join(shots, "ui-%dx%d-%s.png" % (w, h, theme)), full_page=True) if (w, h, theme) != (1440, 900, "dark"): ctx.close() continue # ---- deep behaviour, once, at the desktop dark page ---- # Test connection on a tokenless install talks to GitHub # (the mock) unauthenticated -> /user needs auth -> the # page must show the relayed refusal, not spin forever. page.click("#test") page.wait_for_function( "document.getElementById('err').textContent.length > 0 ||" "document.getElementById('okline').textContent.length > 0", timeout=20000) first_err = page.inner_text("#err") check("Bad credentials" in first_err, "an unauthenticated Test connection relays GitHub's message", first_err) # Save: empty password field keeps the (absent) token but # needs the base typed -> use both fields once. page.fill("#token", TOKEN) page.fill("#apiBase", base) page.click("#save") page.wait_for_function( "document.getElementById('okline').textContent.length > 0", timeout=20000) check("Saved" in page.inner_text("#okline"), "save reports success") check(page.input_value("#token") == "", "the password field clears after save") dom = page.content() check(TOKEN not in dom, "the saved token never appears in the DOM") pill = page.inner_text("#statePill") check("ready" in pill.lower(), "the status pill flips to ready", pill) # with the token saved, Test connection now succeeds page.click("#test") page.wait_for_function( "document.getElementById('okline').textContent.indexOf('Connected') >= 0", timeout=20000) check("mockuser" in page.inner_text("#okline"), "Test connection reports the account through the saved token") # a bad base is refused with the server's message page.fill("#apiBase", "ftp://nope.test") page.click("#save") page.wait_for_function( "document.getElementById('err').textContent.length > 0", timeout=20000) check("http" in page.inner_text("#err").lower(), "an ftp api base is refused loudly", page.inner_text("#err")) # restore the good base for the screenshot page.fill("#apiBase", base) page.click("#save") page.wait_for_function( "document.getElementById('okline').textContent.indexOf('Saved') >= 0", timeout=20000) ctx.close() # small viewport screenshot for the responsive story ctx = browser.new_context(viewport={"width": 390, "height": 844}, color_scheme="light") page = ctx.new_page() page.goto(url + "?theme=light&embed=1", wait_until="networkidle") page.wait_for_function( "document.querySelectorAll('.tool').length == 5", timeout=15000) stabilise(page) page.screenshot(path=os.path.join(shots, "ui-embed-390-light.png"), full_page=True) ctx.close() browser.close() finally: mock.terminate() srv.shutdown() print("e2e.py: %d failed" % len(FAILS)) return 1 if FAILS else 0 if __name__ == "__main__": sys.exit(main())