scorpiox-bot-plugin-github
←e2e.pypython
326 lines · 13 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport + behaviour checks for the plugin_github page.
3
4Serves the plugin through a small CGI shim on a loopback port, points the
5API base at tests/mockapi.py, opens the page with Playwright at 1440 / 1024 /
6390 CSS pixels in both themes, and asserts:
7
8 * no console error and no page error at any viewport
9 * scrollWidth <= innerWidth (no horizontal overflow)
10 * the status card resolves: API base, token pill, state dir
11 * action=tools renders the five real tools with their required args
12 * Test connection reaches the mock and reports the account
13 * saving a token flips the pill, clears the password field, and never
14 echoes the token back into the DOM
15 * a bad api base surfaces the server's 400 message, not a silent no-op
16 * screenshots land in docs/ and are byte-stable: the state card's
17 ephemeral port and tmp work dir are neutralised before the shutter, so
18 re-running the suite never dirties the git tree (a dirty tree fails
19 `scorpiox-cli-botplugin audit`, which is the publish gate)
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 python3 tests/e2e.py --shots /tmp # write the PNGs somewhere other than docs/
27"""
28
29import argparse
30import http.server
31import json
32import os
33import subprocess
34import sys
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_github")
40MOCKAPI = os.path.join(ROOT, "tests", "mockapi.py")
41DOCS = os.path.join(ROOT, "docs")
42WORK = os.path.join("/tmp", "gh-e2e")
43VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
44THEMES = ["dark", "light"]
45TOKEN = "GHPAT-E2E-SAVED-1"
46
47FAILS = []
48
49
50def ok(desc, *a):
51 print(" ok %s" % desc)
52
53
54def bad(desc, detail=""):
55 FAILS.append(desc)
56 print(" FAIL %s%s" % (desc, (" (" + str(detail)[:300] + ")") if detail else ""))
57
58
59def check(cond, desc, detail=""):
60 (ok if cond else bad)(desc, detail)
61
62
63def start_mock():
64 os.makedirs(WORK, exist_ok=True)
65 portfile = os.path.join(WORK, "port")
66 log = os.path.join(WORK, "req.jsonl")
67 for p in (portfile, log):
68 if os.path.exists(p):
69 os.unlink(p)
70 proc = subprocess.Popen(
71 [sys.executable, MOCKAPI, "--portfile", portfile, "--log", log],
72 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
73 for _ in range(200):
74 if os.path.exists(portfile) and os.path.getsize(portfile):
75 break
76 threading.Event().wait(0.05)
77 with open(portfile) as f:
78 port = int(f.read().strip())
79 return proc, "http://127.0.0.1:%d" % port, log
80
81
82def stabilise(page):
83 """Make the page's volatile facts constant so the committed PNGs are
84 reproducible. Only the display is touched; nothing the assertions read is
85 changed, and this runs after every assertion at its viewport."""
86 page.evaluate(
87 """() => {
88 const base = document.getElementById('sBase');
89 if (base) base.textContent = 'http://127.0.0.1:PORT';
90 const dir = document.getElementById('sDir');
91 if (dir) dir.textContent = '/home/user/.scorpiox/connectors/plugin_github';
92 const meta = document.getElementById('saveMeta');
93 if (meta) meta.textContent = '';
94 }""")
95
96
97class Handler(http.server.BaseHTTPRequestHandler):
98 """Runs the binary as a CGI: env from the request, stdin from the body.
99
100 BOT_PASSWORD stays removed from the environment: this shim stands up an
101 open single-user node, which is the configuration a browser reaches with
102 no password juggling (the 401 gate itself is asserted in tests/cgi.py)."""
103
104 def _run(self, method):
105 u = urlparse(self.path)
106 length = int(self.headers.get("Content-Length") or 0)
107 body = self.rfile.read(length) if length else b""
108 env = dict(os.environ)
109 env["QUERY_STRING"] = u.query
110 env["REQUEST_METHOD"] = method
111 env.pop("BOT_PASSWORD", None)
112 env.pop("HTTP_X_BOT_PASSWORD", None)
113 env.pop("GITHUB_TOKEN", None)
114 env.pop("GITHUB_API_BASE", None)
115 env["SX_CONNECTOR_DIR"] = os.path.join(WORK, "cfg")
116 env["CONTENT_LENGTH"] = str(len(body))
117 out = subprocess.run([BIN], input=body, capture_output=True, env=env,
118 timeout=120).stdout
119 sep = out.find(b"\r\n\r\n")
120 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
121 payload = out[sep + 4:] if sep >= 0 else out
122 status = 200
123 ctype = "text/html; charset=utf-8"
124 for line in headers.splitlines():
125 low = line.lower()
126 if low.startswith("content-type:"):
127 ctype = line.split(":", 1)[1].strip()
128 elif low.startswith("status:"):
129 try:
130 status = int(line.split(":", 1)[1].strip().split()[0])
131 except (IndexError, ValueError):
132 status = 200
133 self.send_response(status)
134 self.send_header("Content-Type", ctype)
135 self.send_header("Cache-Control", "no-store")
136 self.send_header("Content-Length", str(len(payload)))
137 self.end_headers()
138 self.wfile.write(payload)
139
140 def do_GET(self): # noqa: N802
141 self._run("GET")
142
143 def do_POST(self): # noqa: N802
144 self._run("POST")
145
146 def log_message(self, *_a):
147 pass
148
149
150def main():
151 ap = argparse.ArgumentParser()
152 ap.add_argument("--strict", action="store_true")
153 ap.add_argument("--shots", default=DOCS,
154 help="where the PNGs go (default docs/, the committed README set)")
155 args = ap.parse_args()
156
157 try:
158 from playwright.sync_api import sync_playwright
159 except ImportError:
160 print("playwright not installed - skipping the viewport suite")
161 return 2 if args.strict else 0
162
163 if not os.access(BIN, os.X_OK):
164 bad("plugin_github binary is missing (run make first)")
165 return 1
166
167 shots = args.shots
168 os.makedirs(shots, exist_ok=True)
169
170 mock, base, mocklog = start_mock()
171 # a clean install: no token stored yet
172 cfg = os.path.join(WORK, "cfg")
173 os.makedirs(cfg, exist_ok=True)
174 # Seed the base pointing at the mock WITHOUT a token: this is a clean
175 # install, and the suite must never touch the real api.github.com.
176 with open(os.path.join(cfg, "config.json"), "w") as f:
177 json.dump({"api_base": base, "token": ""}, f)
178 os.chmod(os.path.join(cfg, "config.json"), 0o600)
179
180 srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
181 port = srv.server_address[1]
182 threading.Thread(target=srv.serve_forever, daemon=True).start()
183 url = "http://127.0.0.1:%d/" % port
184
185 try:
186 with sync_playwright() as pw:
187 browser = pw.chromium.launch()
188 for w, h in VIEWPORTS:
189 for theme in THEMES:
190 # per-context: the deliberate bad-api-base save below
191 # logs one 400 ON PURPOSE; a shared list would blame every
192 # later viewport for it
193 console_errors = []
194 ctx = browser.new_context(viewport={"width": w, "height": h},
195 color_scheme=theme)
196 page = ctx.new_page()
197 page.on("console", lambda m: console_errors.append(m.text)
198 if m.type == "error" else None)
199 page.on("pageerror", lambda e: console_errors.append(str(e)))
200 page.goto(url + "?theme=" + theme, wait_until="networkidle")
201
202 tag = "%dx%d-%s" % (w, h, theme)
203
204 if console_errors:
205 bad("no console errors @ " + tag, console_errors[:2])
206 else:
207 ok("no console errors @ " + tag)
208
209 ow = page.evaluate("document.documentElement.scrollWidth")
210 iw = page.evaluate("window.innerWidth")
211 check(ow <= iw + 1, "no horizontal overflow @ " + tag,
212 "scrollWidth %d > innerWidth %d" % (ow, iw))
213
214 check(page.is_visible("#save") and page.is_visible("#test"),
215 "the controls render @ " + tag)
216
217 # status resolved from the server
218 page.wait_for_function(
219 "document.getElementById('sBase').textContent.length > 5",
220 timeout=15000)
221 sbase = page.inner_text("#sBase")
222 check(sbase.startswith("http"),
223 "the status card shows the api base @ " + tag, sbase)
224
225 # the five tools come from action=tools (the MCP schemas)
226 ntools = page.evaluate("document.querySelectorAll('.tool').length")
227 check(ntools == 5, "five agent tools render @ " + tag, ntools)
228 tooltxt = page.inner_text("#tools")
229 check("owner, repo" in tooltxt or "owner" in tooltxt,
230 "required args are shown @ " + tag)
231
232 # one committed screenshot per viewport + theme (the
233 # README's responsive story is told by these files)
234 stabilise(page)
235 page.screenshot(
236 path=os.path.join(shots, "ui-%dx%d-%s.png" % (w, h, theme)),
237 full_page=True)
238
239 if (w, h, theme) != (1440, 900, "dark"):
240 ctx.close()
241 continue
242
243 # ---- deep behaviour, once, at the desktop dark page ----
244
245 # Test connection on a tokenless install talks to GitHub
246 # (the mock) unauthenticated -> /user needs auth -> the
247 # page must show the relayed refusal, not spin forever.
248 page.click("#test")
249 page.wait_for_function(
250 "document.getElementById('err').textContent.length > 0 ||"
251 "document.getElementById('okline').textContent.length > 0",
252 timeout=20000)
253 first_err = page.inner_text("#err")
254 check("Bad credentials" in first_err,
255 "an unauthenticated Test connection relays GitHub's message",
256 first_err)
257
258 # Save: empty password field keeps the (absent) token but
259 # needs the base typed -> use both fields once.
260 page.fill("#token", TOKEN)
261 page.fill("#apiBase", base)
262 page.click("#save")
263 page.wait_for_function(
264 "document.getElementById('okline').textContent.length > 0",
265 timeout=20000)
266 check("Saved" in page.inner_text("#okline"),
267 "save reports success")
268 check(page.input_value("#token") == "",
269 "the password field clears after save")
270 dom = page.content()
271 check(TOKEN not in dom,
272 "the saved token never appears in the DOM")
273 pill = page.inner_text("#statePill")
274 check("ready" in pill.lower(),
275 "the status pill flips to ready", pill)
276
277 # with the token saved, Test connection now succeeds
278 page.click("#test")
279 page.wait_for_function(
280 "document.getElementById('okline').textContent.indexOf('Connected') >= 0",
281 timeout=20000)
282 check("mockuser" in page.inner_text("#okline"),
283 "Test connection reports the account through the saved token")
284
285 # a bad base is refused with the server's message
286 page.fill("#apiBase", "ftp://nope.test")
287 page.click("#save")
288 page.wait_for_function(
289 "document.getElementById('err').textContent.length > 0",
290 timeout=20000)
291 check("http" in page.inner_text("#err").lower(),
292 "an ftp api base is refused loudly",
293 page.inner_text("#err"))
294
295 # restore the good base for the screenshot
296 page.fill("#apiBase", base)
297 page.click("#save")
298 page.wait_for_function(
299 "document.getElementById('okline').textContent.indexOf('Saved') >= 0",
300 timeout=20000)
301
302 ctx.close()
303
304 # small viewport screenshot for the responsive story
305 ctx = browser.new_context(viewport={"width": 390, "height": 844},
306 color_scheme="light")
307 page = ctx.new_page()
308 page.goto(url + "?theme=light&embed=1", wait_until="networkidle")
309 page.wait_for_function(
310 "document.querySelectorAll('.tool').length == 5", timeout=15000)
311 stabilise(page)
312 page.screenshot(path=os.path.join(shots, "ui-embed-390-light.png"),
313 full_page=True)
314 ctx.close()
315
316 browser.close()
317 finally:
318 mock.terminate()
319 srv.shutdown()
320
321 print("e2e.py: %d failed" % len(FAILS))
322 return 1 if FAILS else 0
323
324
325if __name__ == "__main__":
326 sys.exit(main())