scorpiox-bot-plugin-antigravity-login
←e2e.pypython
264 lines · 10 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport checks for the plugin_antigravity_login page.
3
4Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens it
5with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts:
6
7 * no console error and no page error at any viewport
8 * scrollWidth <= innerWidth (no horizontal overflow)
9 * the status pill, the session card and the project card render
10 * "Start Google Login" drives the flow: the auth link appears, the paste box
11 is shown, and Cancel returns to step one
12 * a bad code shows the inline error instead of a silent nothing
13 * embed mode hides the theme toggle
14 * screenshots land in docs/ for the README
15
16The login and token CLIs are replaced by tests/mock_login.sh and
17tests/mock_token.sh, so nothing here touches Google and no network is used.
18
19Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays
20dependency-free.
21
22 python3 tests/e2e.py # run if Playwright is available
23 python3 tests/e2e.py --strict # exit 2 when Playwright is missing
24"""
25
26import argparse
27import http.server
28import json
29import os
30import shutil
31import socketserver
32import subprocess
33import sys
34import tempfile
35import threading
36from urllib.parse import urlparse
37
38ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
39BIN = os.path.join(ROOT, "plugin_antigravity_login")
40DOCS = os.path.join(ROOT, "docs")
41VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
42THEMES = ["dark", "light"]
43
44
45class Handler(http.server.BaseHTTPRequestHandler):
46 env_extra = {}
47
48 def _run(self, method):
49 u = urlparse(self.path)
50 length = int(self.headers.get("Content-Length") or 0)
51 body = self.rfile.read(length) if length else b""
52 env = dict(os.environ)
53 env["QUERY_STRING"] = u.query
54 env["REQUEST_METHOD"] = method
55 env.pop("BOT_PASSWORD", None)
56 env["CONTENT_LENGTH"] = str(len(body))
57 env.update(self.env_extra)
58 out = subprocess.run([BIN], input=body, capture_output=True,
59 env=env, timeout=60).stdout
60 sep = out.find(b"\r\n\r\n")
61 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
62 payload = out[sep + 4:] if sep >= 0 else out
63 status = 200
64 ctype = "application/json; charset=utf-8"
65 for line in headers.splitlines():
66 low = line.lower()
67 if low.startswith("content-type:"):
68 ctype = line.split(":", 1)[1].strip()
69 elif low.startswith("status:"):
70 try:
71 status = int(line.split(":", 1)[1].strip().split()[0])
72 except (IndexError, ValueError):
73 status = 200
74 self.send_response(status)
75 self.send_header("Content-Type", ctype)
76 self.send_header("Cache-Control", "no-store")
77 self.send_header("Content-Length", str(len(payload)))
78 self.end_headers()
79 self.wfile.write(payload)
80
81 def do_GET(self): # noqa: N802
82 self._run("GET")
83
84 def do_POST(self): # noqa: N802
85 self._run("POST")
86
87 def log_message(self, *_a):
88 pass
89
90
91def seed(work):
92 """A signed-in fixture written the way the login CLI writes it."""
93 acct = os.path.join(work, "antigravity_accounts.json")
94 with open(acct, "w", encoding="utf-8") as f:
95 f.write('[{"email":"pico@example.com","refresh_token":"1//mock-refresh"}]\n')
96 with open(os.path.join(work, "selected_account.txt"), "w", encoding="utf-8") as f:
97 f.write("pico@example.com\n")
98 envdir = os.path.join(work, "scorpiox-env")
99 os.makedirs(envdir, exist_ok=True)
100 with open(os.path.join(envdir, "antigravity.txt"), "w", encoding="utf-8") as f:
101 f.write("PROVIDER=google_gemini\n"
102 "GOOGLE_ACCOUNT=pico@example.com\n"
103 "GOOGLE_PROJECT_ID=proj-mock-42\n")
104 return acct
105
106
107def main():
108 ap = argparse.ArgumentParser()
109 ap.add_argument("--strict", action="store_true",
110 help="exit 2 when Playwright is not installed")
111 args = ap.parse_args()
112
113 try:
114 from playwright.sync_api import sync_playwright
115 except Exception:
116 print("playwright not installed - skipping e2e (offline suite is unaffected)")
117 return 2 if args.strict else 0
118
119 if not os.path.exists(BIN):
120 print("plugin_antigravity_login not built - run make first")
121 return 1
122
123 work = tempfile.mkdtemp(prefix="agylogin-e2e-")
124 acct = seed(work)
125 Handler.env_extra = {
126 "ANTIGRAVITY_CREDS_PATH": acct,
127 "ANTIGRAVITY_LOGIN_BIN": os.path.join(ROOT, "tests", "mock_login.sh"),
128 "ANTIGRAVITY_TOKEN_BIN": os.path.join(ROOT, "tests", "mock_token.sh"),
129 "ANTIGRAVITY_PENDING_PATH": os.path.join(work, "pending.json"),
130 "MOCK_WRITE_DIR": work,
131 "MOCK_STATUS_JSON":
132 '{"ok":true,"provider":"antigravity","logged_in":true,'
133 '"has_refresh":true,"pending":false,"identity":"pico@example.com",'
134 '"expires_at":4102444800000,"expired":false}',
135 }
136
137 httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler)
138 port = httpd.server_address[1]
139 threading.Thread(target=httpd.serve_forever, daemon=True).start()
140 base = "http://127.0.0.1:%d/" % port
141
142 os.makedirs(DOCS, exist_ok=True)
143 failures = []
144 checks = 0
145
146 def ok(cond, label):
147 nonlocal checks
148 checks += 1
149 if not cond:
150 failures.append(label)
151 print(" FAIL %s" % label)
152
153 try:
154 with sync_playwright() as pw:
155 browser = pw.chromium.launch()
156 for w, h in VIEWPORTS:
157 for theme in THEMES:
158 page = browser.new_page(viewport={"width": w, "height": h},
159 color_scheme=theme)
160 errors = []
161 page.on("console", lambda m: errors.append(m.text)
162 if m.type == "error" else None)
163 page.on("pageerror", lambda e: errors.append(str(e)))
164
165 page.goto(base + "?theme=%s" % theme, wait_until="load")
166 page.wait_for_function(
167 "document.getElementById('pillText').textContent"
168 " !== 'Checking'", timeout=8000)
169
170 ok(page.text_content("#pillText") == "Connected",
171 "status pill says Connected @%dx%d %s" % (w, h, theme))
172 ok("pico@example.com" in page.text_content("#sub"),
173 "account shown in the header @%dx%d %s" % (w, h, theme))
174 ok("pico@example.com" in page.text_content("#session"),
175 "session card lists the account @%dx%d %s" % (w, h, theme))
176 ok("proj-mock-42" in page.text_content("#project"),
177 "companion project card @%dx%d %s" % (w, h, theme))
178
179 sw = page.evaluate("document.documentElement.scrollWidth")
180 iw = page.evaluate("window.innerWidth")
181 ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s"
182 % (sw, iw, w, h, theme))
183
184 # the theme actually applied (the CSS variables resolved)
185 bg = page.evaluate(
186 "getComputedStyle(document.body).backgroundColor")
187 if theme == "light":
188 ok(bg.startswith("rgb(245") or bg.startswith("rgb(255"),
189 "light theme background @%dx%d" % (w, h))
190 else:
191 ok(bg.startswith("rgb(0"), "dark theme background @%dx%d"
192 % (w, h))
193
194 ok(not errors, "no console error @%dx%d %s (%s)"
195 % (w, h, theme, "; ".join(errors[:2])))
196
197 shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme))
198 page.screenshot(path=shot)
199 page.close()
200
201 # the login flow, at one viewport
202 page = browser.new_page(viewport={"width": 1024, "height": 768})
203 errors = []
204 page.on("pageerror", lambda e: errors.append(str(e)))
205 page.goto(base + "?theme=dark", wait_until="load")
206 page.wait_for_function(
207 "document.getElementById('pillText').textContent !== 'Checking'",
208 timeout=8000)
209
210 page.click("#btnStart")
211 page.wait_for_selector("#step2.on", timeout=8000)
212 url = page.text_content("#authUrl")
213 ok(url.startswith("https://accounts.google.com/"),
214 "start produced an authorization URL")
215 ok("code_challenge=" in url, "the URL carries the PKCE challenge")
216 ok(page.get_attribute("#linkOpen", "href").startswith(
217 "https://accounts.google.com/"), "the open link is wired")
218
219 page.click("#btnCancel")
220 page.wait_for_selector("#step1.on", timeout=8000)
221 ok(not page.is_visible("#step2.on"), "cancel returns to step one")
222
223 # a rejected exchange shows the inline error, not silence
224 page.click("#btnStart")
225 page.wait_for_selector("#step2.on", timeout=8000)
226 page.fill("#codeInput", "not a code ' with quote")
227 page.click("#btnFinish")
228 page.wait_for_function(
229 "document.getElementById('loginNote').classList.contains('show')",
230 timeout=8000)
231 note = page.text_content("#loginNote")
232 ok("code" in note.lower(), "an invalid code explains itself (%r)" % note[:60])
233 ok(not errors, "no page error during the flow (%s)"
234 % "; ".join(errors[:2]))
235 page.screenshot(path=os.path.join(DOCS, "ui-flow-dark.png"))
236 page.close()
237
238 # embed mode hides the theme toggle
239 page = browser.new_page(viewport={"width": 1024, "height": 768})
240 page.goto(base + "?embed=1&theme=dark", wait_until="load")
241 page.wait_for_function(
242 "document.getElementById('pillText').textContent !== 'Checking'",
243 timeout=8000)
244 ok(not page.is_visible("#themeToggle"), "embed hides the theme toggle")
245 ok(page.evaluate(
246 "document.documentElement.classList.contains('embedded')"),
247 "embed marks html.embedded")
248 page.close()
249 browser.close()
250 finally:
251 httpd.shutdown()
252 shutil.rmtree(work, ignore_errors=True)
253
254 print("\n%d checks, %d failure(s)" % (checks, len(failures)))
255 if failures:
256 for f in failures:
257 print(" - %s" % f)
258 return 1
259 print("RESULT: OK")
260 return 0
261
262
263if __name__ == "__main__":
264 sys.exit(main())