#!/usr/bin/env python3 """tests/e2e.py - viewport checks for the plugin_claudecode_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 status pill, the countdown card and the account list render * the pill text matches the fixture state (Logged In) * "Start Claude Login" drives the flow: the auth link appears, the paste box is shown, and Cancel returns to step one * a bad code shows the inline error instead of a silent nothing * 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 The login and refresh CLIs are replaced by tests/mock_login.sh and tests/mock_refresh.sh, so nothing here touches Claude 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_claudecode_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") exp = int((time.time() + 7200) * 1000) with open(creds, "w", encoding="utf-8") as f: f.write('{\n "claudeAiOauth": {\n' ' "accessToken": "sk-ant-oat01-MOCK-ACCESS-MUST-NOT-LEAK",\n' ' "refreshToken": "sk-ant-ort01-MOCK-REFRESH-MUST-NOT-LEAK",\n' ' "expiresAt": %d,\n' ' "scopes": ["user:profile","user:inference",' '"user:sessions:claude_code"],\n' ' "subscriptionType": "pro"\n }\n}\n' % exp) envdir = os.path.join(work, "scorpiox-env") os.makedirs(envdir, exist_ok=True) with open(os.path.join(envdir, "claude_code.txt"), "w", encoding="utf-8") as f: f.write("PROVIDER=claude_code\nCLAUDE_CODE_TOKEN_SOURCE=local\n" "MODEL=claude-opus-4-6\n") for d in ("accounts", "pending"): os.makedirs(os.path.join(work, d), exist_ok=True) # one second named account so the account card is not empty with open(os.path.join(work, "accounts", "work.json"), "w", encoding="utf-8") as f: f.write('{"claudeAiOauth":{"accessToken":"a","refreshToken":"b",' '"expiresAt":%d}}\n' % exp) 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_claudecode_login not built - run make first") return 1 work = tempfile.mkdtemp(prefix="cclogin-e2e-") creds = seed(work) Handler.env_extra = { "CLAUDE_CREDS_PATH": creds, "CLAUDE_ACCOUNTS_DIR": os.path.join(work, "accounts"), "CLAUDE_PENDING_DIR": os.path.join(work, "pending"), "CLAUDE_ENV_DIR": os.path.join(work, "scorpiox-env"), "CLAUDE_LOGIN_BIN": os.path.join(ROOT, "tests", "mock_login.sh"), "CLAUDE_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") == "Logged In", "pill reads Logged In @%dx%d" % (w, h)) ok(page.text_content("#count").strip() != "-", "countdown 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