#!/usr/bin/env python3 """tests/e2e.py - viewport checks for the plugin_copilot_login page. Serves the plugin through a small CGI-ish HTTP shim on a loopback port, 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 connection pill, the session table and the account list render * the pill text matches the fixture state (Connected) and the GitHub badge carries the login read from config.json * "Start GitHub Copilot Login" drives the device flow: the large user code appears, the polling indicator is visible, and Cancel returns to step one * a poll that succeeds flips the page to the signed-in state without a reload * the Theme button actually flips html[data-theme] in a standalone tab * embed mode hides the theme toggle * screenshots land in docs/ for the README Both CLIs are replaced by tests/mock_login.sh and tests/mock_refresh.sh, so nothing here touches GitHub and no network is used. 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 json import os import shutil import socketserver import subprocess import sys import tempfile import threading import time from urllib.parse import urlparse ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_copilot_login") DOCS = os.path.join(ROOT, "docs") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] class Handler(http.server.BaseHTTPRequestHandler): env_extra = {} 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.update(self.env_extra) 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 = "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 seed(work): """A signed-in fixture written the way the login CLI writes it.""" creds = os.path.join(work, ".credentials.json") with open(creds, "w", encoding="utf-8") as f: f.write('{\n "github_token": "gho_MOCK-TOKEN-MUST-NOT-LEAK",\n' ' "token_type": "bearer",\n "scope": "read:user",\n' ' "timestamp": "2026-01-01T00:00:00Z"\n}\n') with open(os.path.join(work, "config.json"), "w", encoding="utf-8") as f: f.write('{\n "copilotTokens": {"https://github.com:octocat": "gho_MOCK"},\n' ' "lastLoggedInUser": {"host": "https://github.com",' ' "login": "octocat"}\n}\n') exp = int(time.time()) + 1800 with open(os.path.join(work, ".copilot-token-cache.json"), "w", encoding="utf-8") as f: f.write('{"access_token": "MOCK-JWT-MUST-NOT-LEAK", "expires_at": %d}\n' % exp) envdir = os.path.join(work, "scorpiox-env") os.makedirs(envdir, exist_ok=True) with open(os.path.join(envdir, "copilot.txt"), "w", encoding="utf-8") as f: f.write("PROVIDER=copilot\nCOPILOT_TOKEN_SOURCE=local\n" "MODEL=claude-sonnet-5\n") for d in ("accounts", "pending", "mock"): os.makedirs(os.path.join(work, d), exist_ok=True) with open(os.path.join(work, "accounts", "work.json"), "w", encoding="utf-8") as f: f.write('{"github_token": "gho_MOCK-ACCOUNT", "scope": "read:user"}\n') return creds 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_copilot_login not built - run make first") return 1 work = tempfile.mkdtemp(prefix="cplogin-e2e-") creds = seed(work) Handler.env_extra = { "COPILOT_CREDS_PATH": creds, "COPILOT_ACCOUNTS_DIR": os.path.join(work, "accounts"), "COPILOT_PENDING_DIR": os.path.join(work, "pending"), "COPILOT_ENV_DIR": os.path.join(work, "scorpiox-env"), "COPILOT_MOCK_DIR": os.path.join(work, "mock"), "COPILOT_LOGIN_BIN": os.path.join(ROOT, "tests", "mock_login.sh"), "COPILOT_REFRESH_BIN": os.path.join(ROOT, "tests", "mock_refresh.sh"), } httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler) port = httpd.server_address[1] threading.Thread(target=httpd.serve_forever, daemon=True).start() base = "http://127.0.0.1:%d/" % port 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) try: with sync_playwright() as pw: browser = pw.chromium.launch() for w, h in VIEWPORTS: for theme in THEMES: page = browser.new_page(viewport={"width": w, "height": h}, color_scheme=theme) 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=%s" % theme, wait_until="load") page.wait_for_function( "document.getElementById('pillText').textContent" " !== 'Checking'", timeout=8000) ok(page.text_content("#pillText") == "Connected", "pill reads Connected @%dx%d" % (w, h)) ok(page.text_content("#userBadge").strip() == "@octocat", "GitHub user badge renders @%dx%d" % (w, h)) ok(page.locator("#session .k").count() >= 8, "session table renders @%dx%d" % (w, h)) ok(page.locator(".acct").count() >= 1, "named account row renders @%dx%d" % (w, h)) ok(page.evaluate( "document.documentElement.getAttribute('data-theme')") == theme, "theme applied from ?theme= @%dx%d%s" % (w, h, theme)) sw = page.evaluate("document.documentElement.scrollWidth") iw = page.evaluate("window.innerWidth") ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s" % (sw, iw, w, h, theme)) # the CSS actually parsed: an unparsed stylesheet leaves # document.styleSheets empty and every rule inert. # Two