scorpiox-bot-plugin-claudecode-login
←e2e.pypython
304 lines · 12 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport checks for the plugin_claudecode_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 countdown card and the account list render
10 * the pill text matches the fixture state (Logged In)
11 * "Start Claude Login" drives the flow: the auth link appears, the paste box
12 is shown, and Cancel returns to step one
13 * a bad code shows the inline error instead of a silent nothing
14 * the Theme button actually flips html[data-theme] in a standalone tab
15 * embed mode hides the theme toggle
16 * screenshots land in docs/ for the README
17
18The login and refresh CLIs are replaced by tests/mock_login.sh and
19tests/mock_refresh.sh, so nothing here touches Claude and no network is used.
20
21Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays
22dependency-free.
23
24 python3 tests/e2e.py # run if Playwright is available
25 python3 tests/e2e.py --strict # exit 2 when Playwright is missing
26"""
27
28import argparse
29import http.server
30import json
31import os
32import shutil
33import socketserver
34import subprocess
35import sys
36import tempfile
37import threading
38import time
39from urllib.parse import urlparse
40
41ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
42BIN = os.path.join(ROOT, "plugin_claudecode_login")
43DOCS = os.path.join(ROOT, "docs")
44VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
45THEMES = ["dark", "light"]
46
47
48class Handler(http.server.BaseHTTPRequestHandler):
49 env_extra = {}
50
51 def _run(self, method):
52 u = urlparse(self.path)
53 length = int(self.headers.get("Content-Length") or 0)
54 body = self.rfile.read(length) if length else b""
55 env = dict(os.environ)
56 env["QUERY_STRING"] = u.query
57 env["REQUEST_METHOD"] = method
58 env.pop("BOT_PASSWORD", None)
59 env["CONTENT_LENGTH"] = str(len(body))
60 env.update(self.env_extra)
61 out = subprocess.run([BIN], input=body, capture_output=True,
62 env=env, timeout=60).stdout
63 sep = out.find(b"\r\n\r\n")
64 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
65 payload = out[sep + 4:] if sep >= 0 else out
66 status = 200
67 ctype = "application/json; charset=utf-8"
68 for line in headers.splitlines():
69 low = line.lower()
70 if low.startswith("content-type:"):
71 ctype = line.split(":", 1)[1].strip()
72 elif low.startswith("status:"):
73 try:
74 status = int(line.split(":", 1)[1].strip().split()[0])
75 except (IndexError, ValueError):
76 status = 200
77 self.send_response(status)
78 self.send_header("Content-Type", ctype)
79 self.send_header("Cache-Control", "no-store")
80 self.send_header("Content-Length", str(len(payload)))
81 self.end_headers()
82 self.wfile.write(payload)
83
84 def do_GET(self): # noqa: N802
85 self._run("GET")
86
87 def do_POST(self): # noqa: N802
88 self._run("POST")
89
90 def log_message(self, *_a):
91 pass
92
93
94def seed(work):
95 """A signed-in fixture written the way the login CLI writes it."""
96 creds = os.path.join(work, ".credentials.json")
97 exp = int((time.time() + 7200) * 1000)
98 with open(creds, "w", encoding="utf-8") as f:
99 f.write('{\n "claudeAiOauth": {\n'
100 ' "accessToken": "sk-ant-oat01-MOCK-ACCESS-MUST-NOT-LEAK",\n'
101 ' "refreshToken": "sk-ant-ort01-MOCK-REFRESH-MUST-NOT-LEAK",\n'
102 ' "expiresAt": %d,\n'
103 ' "scopes": ["user:profile","user:inference",'
104 '"user:sessions:claude_code"],\n'
105 ' "subscriptionType": "pro"\n }\n}\n' % exp)
106 envdir = os.path.join(work, "scorpiox-env")
107 os.makedirs(envdir, exist_ok=True)
108 with open(os.path.join(envdir, "claude_code.txt"), "w", encoding="utf-8") as f:
109 f.write("PROVIDER=claude_code\nCLAUDE_CODE_TOKEN_SOURCE=local\n"
110 "MODEL=claude-opus-4-6\n")
111 for d in ("accounts", "pending"):
112 os.makedirs(os.path.join(work, d), exist_ok=True)
113 # one second named account so the account card is not empty
114 with open(os.path.join(work, "accounts", "work.json"), "w", encoding="utf-8") as f:
115 f.write('{"claudeAiOauth":{"accessToken":"a","refreshToken":"b",'
116 '"expiresAt":%d}}\n' % exp)
117 return creds
118
119
120def main():
121 ap = argparse.ArgumentParser()
122 ap.add_argument("--strict", action="store_true",
123 help="exit 2 when Playwright is not installed")
124 args = ap.parse_args()
125
126 try:
127 from playwright.sync_api import sync_playwright
128 except Exception:
129 print("playwright not installed - skipping e2e (offline suite is unaffected)")
130 return 2 if args.strict else 0
131
132 if not os.path.exists(BIN):
133 print("plugin_claudecode_login not built - run make first")
134 return 1
135
136 work = tempfile.mkdtemp(prefix="cclogin-e2e-")
137 creds = seed(work)
138 Handler.env_extra = {
139 "CLAUDE_CREDS_PATH": creds,
140 "CLAUDE_ACCOUNTS_DIR": os.path.join(work, "accounts"),
141 "CLAUDE_PENDING_DIR": os.path.join(work, "pending"),
142 "CLAUDE_ENV_DIR": os.path.join(work, "scorpiox-env"),
143 "CLAUDE_LOGIN_BIN": os.path.join(ROOT, "tests", "mock_login.sh"),
144 "CLAUDE_REFRESH_BIN": os.path.join(ROOT, "tests", "mock_refresh.sh"),
145 }
146
147 httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler)
148 port = httpd.server_address[1]
149 threading.Thread(target=httpd.serve_forever, daemon=True).start()
150 base = "http://127.0.0.1:%d/" % port
151
152 os.makedirs(DOCS, exist_ok=True)
153 failures = []
154 checks = 0
155
156 def ok(cond, label):
157 nonlocal checks
158 checks += 1
159 if not cond:
160 failures.append(label)
161 print(" FAIL %s" % label)
162
163 try:
164 with sync_playwright() as pw:
165 browser = pw.chromium.launch()
166 for w, h in VIEWPORTS:
167 for theme in THEMES:
168 page = browser.new_page(viewport={"width": w, "height": h},
169 color_scheme=theme)
170 errors = []
171 page.on("console", lambda m: errors.append(m.text)
172 if m.type == "error" else None)
173 page.on("pageerror", lambda e: errors.append(str(e)))
174
175 page.goto(base + "?theme=%s" % theme, wait_until="load")
176 page.wait_for_function(
177 "document.getElementById('pillText').textContent"
178 " !== 'Checking'", timeout=8000)
179
180 ok(page.text_content("#pillText") == "Logged In",
181 "pill reads Logged In @%dx%d" % (w, h))
182 ok(page.text_content("#count").strip() != "-",
183 "countdown renders @%dx%d" % (w, h))
184 ok(page.locator(".acct").count() >= 1,
185 "named account row renders @%dx%d" % (w, h))
186 ok(page.evaluate(
187 "document.documentElement.getAttribute('data-theme')")
188 == theme, "theme applied from ?theme= @%dx%d%s"
189 % (w, h, theme))
190
191 sw = page.evaluate("document.documentElement.scrollWidth")
192 iw = page.evaluate("window.innerWidth")
193 ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s"
194 % (sw, iw, w, h, theme))
195
196 # the CSS actually parsed: an unparsed stylesheet leaves
197 # document.styleSheets empty and every rule inert
198 # Two <style> blocks: the bot token block and the page's
199 # own rules. Count BOTH - asserting only stylesheets[0]
200 # measured the token block and said nothing about the page.
201 rules = page.evaluate(
202 "Array.from(document.styleSheets)"
203 ".reduce((n,s)=>n+s.cssRules.length,0)")
204 ok(rules > 40, "both stylesheets parsed (%d rules) @%dx%d"
205 % (rules, w, h))
206
207 bg = page.evaluate(
208 "getComputedStyle(document.body).backgroundColor")
209 if theme == "light":
210 ok(bg.startswith("rgb(245") or bg.startswith("rgb(255"),
211 "light theme background @%dx%d" % (w, h))
212 else:
213 ok(bg.startswith("rgb(0"), "dark theme background @%dx%d"
214 % (w, h))
215
216 ok(not errors, "no console error @%dx%d %s (%s)"
217 % (w, h, theme, "; ".join(errors[:2])))
218
219 shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme))
220 page.screenshot(path=shot)
221 page.close()
222
223 # the login flow, at one viewport
224 page = browser.new_page(viewport={"width": 1024, "height": 768})
225 errors = []
226 page.on("pageerror", lambda e: errors.append(str(e)))
227 page.goto(base + "?theme=dark", wait_until="load")
228 page.wait_for_function(
229 "document.getElementById('pillText').textContent"
230 " !== 'Checking'", timeout=8000)
231
232 page.click("#btnStart")
233 page.wait_for_selector("#step2.on", timeout=8000)
234 url = page.text_content("#authUrl")
235 ok(url.startswith("https://claude.com/cai/oauth/authorize"),
236 "start produced an authorization URL")
237 ok("code_challenge" in url or "state=" in url,
238 "the URL carries the PKCE state")
239 ok(page.get_attribute("#linkOpen", "href").startswith(
240 "https://claude.com/"), "the open link is wired")
241
242 page.click("#btnCancel")
243 page.wait_for_selector("#step1.on", timeout=8000)
244 ok(not page.is_visible("#step2.on"), "cancel returns to step one")
245
246 # a rejected exchange shows the inline error, not silence
247 page.click("#btnStart")
248 page.wait_for_selector("#step2.on", timeout=8000)
249 page.fill("#codeInput", "not a code ' with quote")
250 page.click("#btnFinish")
251 page.wait_for_function(
252 "document.getElementById('loginNote').classList.contains('show')",
253 timeout=8000)
254 note = page.text_content("#loginNote")
255 ok("code" in note.lower(),
256 "an invalid code explains itself (%r)" % note[:60])
257 ok(not errors, "no page error during the flow (%s)"
258 % "; ".join(errors[:2]))
259 page.screenshot(path=os.path.join(DOCS, "ui-flow-dark.png"))
260 page.close()
261
262 # the standalone Theme button must actually flip the attribute
263 page = browser.new_page(viewport={"width": 1024, "height": 768},
264 color_scheme="dark")
265 page.goto(base, wait_until="load")
266 page.wait_for_function(
267 "document.getElementById('pillText').textContent"
268 " !== 'Checking'", timeout=8000)
269 before = page.evaluate(
270 "document.documentElement.getAttribute('data-theme')")
271 page.click("#themeToggle")
272 after = page.evaluate(
273 "document.documentElement.getAttribute('data-theme')")
274 ok(before != after and after in ("dark", "light"),
275 "theme toggle flips the theme (%s->%s)" % (before, after))
276 page.close()
277
278 # embed mode hides the theme toggle
279 page = browser.new_page(viewport={"width": 1024, "height": 768})
280 page.goto(base + "?embed=1&theme=dark", wait_until="load")
281 page.wait_for_function(
282 "document.getElementById('pillText').textContent"
283 " !== 'Checking'", timeout=8000)
284 ok(not page.is_visible("#themeToggle"), "embed hides the theme toggle")
285 ok(page.evaluate(
286 "document.documentElement.classList.contains('embedded')"),
287 "embed marks html.embedded")
288 page.close()
289 browser.close()
290 finally:
291 httpd.shutdown()
292 shutil.rmtree(work, ignore_errors=True)
293
294 print("\n%d checks, %d failure(s)" % (checks, len(failures)))
295 if failures:
296 for f in failures:
297 print(" - %s" % f)
298 return 1
299 print("RESULT: OK")
300 return 0
301
302
303if __name__ == "__main__":
304 sys.exit(main())