#!/usr/bin/env python3 """tests/e2e.py - viewport checks for the plugin_antigravity_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 session card and the project card render * "Start Google 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 * embed mode hides the theme toggle * screenshots land in docs/ for the README The login and token CLIs are replaced by tests/mock_login.sh and tests/mock_token.sh, so nothing here touches Google 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 from urllib.parse import urlparse ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_antigravity_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.""" acct = os.path.join(work, "antigravity_accounts.json") with open(acct, "w", encoding="utf-8") as f: f.write('[{"email":"pico@example.com","refresh_token":"1//mock-refresh"}]\n') with open(os.path.join(work, "selected_account.txt"), "w", encoding="utf-8") as f: f.write("pico@example.com\n") envdir = os.path.join(work, "scorpiox-env") os.makedirs(envdir, exist_ok=True) with open(os.path.join(envdir, "antigravity.txt"), "w", encoding="utf-8") as f: f.write("PROVIDER=google_gemini\n" "GOOGLE_ACCOUNT=pico@example.com\n" "GOOGLE_PROJECT_ID=proj-mock-42\n") return acct 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_antigravity_login not built - run make first") return 1 work = tempfile.mkdtemp(prefix="agylogin-e2e-") acct = seed(work) Handler.env_extra = { "ANTIGRAVITY_CREDS_PATH": acct, "ANTIGRAVITY_LOGIN_BIN": os.path.join(ROOT, "tests", "mock_login.sh"), "ANTIGRAVITY_TOKEN_BIN": os.path.join(ROOT, "tests", "mock_token.sh"), "ANTIGRAVITY_PENDING_PATH": os.path.join(work, "pending.json"), "MOCK_WRITE_DIR": work, "MOCK_STATUS_JSON": '{"ok":true,"provider":"antigravity","logged_in":true,' '"has_refresh":true,"pending":false,"identity":"pico@example.com",' '"expires_at":4102444800000,"expired":false}', } 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", "status pill says Connected @%dx%d %s" % (w, h, theme)) ok("pico@example.com" in page.text_content("#sub"), "account shown in the header @%dx%d %s" % (w, h, theme)) ok("pico@example.com" in page.text_content("#session"), "session card lists the account @%dx%d %s" % (w, h, theme)) ok("proj-mock-42" in page.text_content("#project"), "companion project card @%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 theme actually applied (the CSS variables resolved) bg = page.evaluate( "getComputedStyle(document.body).backgroundColor") if theme == "light": ok(bg.startswith("rgb(245") or bg.startswith("rgb(255"), "light theme background @%dx%d" % (w, h)) else: ok(bg.startswith("rgb(0"), "dark theme background @%dx%d" % (w, h)) ok(not errors, "no console error @%dx%d %s (%s)" % (w, h, theme, "; ".join(errors[:2]))) shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme)) page.screenshot(path=shot) page.close() # the login flow, at one viewport page = browser.new_page(viewport={"width": 1024, "height": 768}) errors = [] page.on("pageerror", lambda e: errors.append(str(e))) page.goto(base + "?theme=dark", wait_until="load") page.wait_for_function( "document.getElementById('pillText').textContent !== 'Checking'", timeout=8000) page.click("#btnStart") page.wait_for_selector("#step2.on", timeout=8000) url = page.text_content("#authUrl") ok(url.startswith("https://accounts.google.com/"), "start produced an authorization URL") ok("code_challenge=" in url, "the URL carries the PKCE challenge") ok(page.get_attribute("#linkOpen", "href").startswith( "https://accounts.google.com/"), "the open link is wired") page.click("#btnCancel") page.wait_for_selector("#step1.on", timeout=8000) ok(not page.is_visible("#step2.on"), "cancel returns to step one") # a rejected exchange shows the inline error, not silence page.click("#btnStart") page.wait_for_selector("#step2.on", timeout=8000) page.fill("#codeInput", "not a code ' with quote") page.click("#btnFinish") page.wait_for_function( "document.getElementById('loginNote').classList.contains('show')", timeout=8000) note = page.text_content("#loginNote") ok("code" in note.lower(), "an invalid code explains itself (%r)" % note[:60]) ok(not errors, "no page error during the flow (%s)" % "; ".join(errors[:2])) page.screenshot(path=os.path.join(DOCS, "ui-flow-dark.png")) page.close() # embed mode hides the theme toggle page = browser.new_page(viewport={"width": 1024, "height": 768}) page.goto(base + "?embed=1&theme=dark", wait_until="load") page.wait_for_function( "document.getElementById('pillText').textContent !== 'Checking'", timeout=8000) ok(not page.is_visible("#themeToggle"), "embed hides the theme toggle") ok(page.evaluate( "document.documentElement.classList.contains('embedded')"), "embed marks html.embedded") page.close() browser.close() finally: httpd.shutdown() shutil.rmtree(work, ignore_errors=True) print("\n%d checks, %d failure(s)" % (checks, len(failures))) if failures: for f in failures: print(" - %s" % f) return 1 print("RESULT: OK") return 0 if __name__ == "__main__": sys.exit(main())