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