scorpiox-bot-plugin-gitstat
←e2e.pypython
332 lines · 13 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport checks for the plugin_gitstat board.
3
4Builds a small fixture tree of real git repositories in a temp directory, serves
5the plugin through a tiny CGI-ish HTTP shim on a loopback port, and opens it with
6Playwright at 1440 / 1024 / 390 CSS pixels in both themes. It asserts there is
7no horizontal overflow, no console error, that the summary chips and the table
8rendered, and that a row opens the detail drawer. Screenshots land in docs/ for
9the README. Skips cleanly (exit 0) when Playwright is not installed, so the
10offline suite stays dependency-free.
11
12 python3 tests/e2e.py # run if Playwright is available
13 python3 tests/e2e.py --strict # exit 2 when Playwright is missing
14"""
15
16import argparse
17import http.server
18import os
19import shutil
20import socketserver
21import subprocess
22import sys
23import tempfile
24import threading
25from urllib.parse import urlparse
26
27ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
28BIN = os.path.join(ROOT, "plugin_gitstat")
29DOCS = os.path.join(ROOT, "docs")
30VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
31THEMES = ["dark", "light"]
32
33GITENV = {
34 "GIT_AUTHOR_NAME": "Gitstat E2E",
35 "GIT_AUTHOR_EMAIL": "gitstat@example.invalid",
36 "GIT_COMMITTER_NAME": "Gitstat E2E",
37 "GIT_COMMITTER_EMAIL": "gitstat@example.invalid",
38 "GIT_CONFIG_GLOBAL": os.devnull,
39 "GIT_CONFIG_NOSYSTEM": "1",
40 "GIT_TERMINAL_PROMPT": "0",
41}
42
43
44def git(cwd, *args):
45 env = dict(os.environ)
46 env.update(GITENV)
47 return subprocess.run(["git", "-C", cwd] + list(args), env=env,
48 check=True, capture_output=True)
49
50
51def mkrepo(path, branch="main"):
52 os.makedirs(path, exist_ok=True)
53 git(path, "init", "-q", "-b", branch)
54 git(path, "config", "user.name", "Gitstat E2E")
55 git(path, "config", "user.email", "gitstat@example.invalid")
56
57
58def build_fixtures(base):
59 """Four repos, one per interesting visual state."""
60 roots = os.path.join(base, "roots")
61 os.makedirs(roots)
62
63 # clean, in sync with an upstream
64 up = os.path.join(base, "up.git")
65 git(base, "init", "-q", "--bare", up)
66 git(up, "symbolic-ref", "HEAD", "refs/heads/main")
67 seed = os.path.join(base, "seed")
68 mkrepo(seed)
69 with open(os.path.join(seed, "README.md"), "w", encoding="utf-8") as f:
70 f.write("seed\n")
71 git(seed, "add", "README.md")
72 git(seed, "commit", "-q", "-m", "Add the README that everything else builds on")
73 git(seed, "remote", "add", "origin", up)
74 git(seed, "push", "-q", "-u", "origin", "main")
75 git(base, "clone", "-q", up, os.path.join(roots, "portal-web"))
76 c = os.path.join(roots, "portal-web")
77 git(c, "config", "user.name", "Gitstat E2E")
78 git(c, "config", "user.email", "gitstat@example.invalid")
79
80 # dirty working tree
81 d = os.path.join(roots, "billing-service")
82 mkrepo(d)
83 for name in ("main.c", "util.c", "notes.md"):
84 with open(os.path.join(d, name), "w", encoding="utf-8") as f:
85 f.write("x\n")
86 git(d, "add", ".")
87 git(d, "commit", "-q", "-m", "Split the invoice renderer out of the billing loop")
88 with open(os.path.join(d, "main.c"), "a", encoding="utf-8") as f:
89 f.write("patched\n")
90 with open(os.path.join(d, "util.c"), "a", encoding="utf-8") as f:
91 f.write("staged\n")
92 git(d, "add", "util.c")
93 with open(os.path.join(d, "untracked.txt"), "w", encoding="utf-8") as f:
94 f.write("new\n")
95
96 # ahead by two, with a stash
97 a = os.path.join(roots, "fleet-agent")
98 up2 = os.path.join(base, "up2.git")
99 git(base, "init", "-q", "--bare", up2)
100 git(up2, "symbolic-ref", "HEAD", "refs/heads/main")
101 seed2 = os.path.join(base, "seed2")
102 mkrepo(seed2)
103 with open(os.path.join(seed2, "a.txt"), "w", encoding="utf-8") as f:
104 f.write("a\n")
105 git(seed2, "add", "a.txt")
106 git(seed2, "commit", "-q", "-m", "Start the agent loop")
107 git(seed2, "remote", "add", "origin", up2)
108 git(seed2, "push", "-q", "-u", "origin", "main")
109 git(base, "clone", "-q", up2, a)
110 git(a, "config", "user.name", "Gitstat E2E")
111 git(a, "config", "user.email", "gitstat@example.invalid")
112 for msg in ("Teach the agent to retry a dropped socket",
113 "Cap the retry backoff at thirty seconds"):
114 with open(os.path.join(a, "a.txt"), "a", encoding="utf-8") as f:
115 f.write(msg + "\n")
116 git(a, "commit", "-q", "-am", msg)
117 with open(os.path.join(a, "a.txt"), "a", encoding="utf-8") as f:
118 f.write("wip\n")
119 git(a, "stash", "push", "-q", "-m", "half-finished backoff rewrite")
120
121 # detached
122 x = os.path.join(roots, "proto-sandbox")
123 mkrepo(x)
124 with open(os.path.join(x, "p.txt"), "w", encoding="utf-8") as f:
125 f.write("p\n")
126 git(x, "add", "p.txt")
127 git(x, "commit", "-q", "-m", "First prototype of the graph walker")
128 with open(os.path.join(x, "p.txt"), "a", encoding="utf-8") as f:
129 f.write("q\n")
130 git(x, "commit", "-q", "-am", "Walk depth-first instead")
131 git(x, "checkout", "-q", "HEAD~1")
132 return roots
133
134
135class Handler(http.server.BaseHTTPRequestHandler):
136 roots = ""
137 allow_fetch = "0"
138
139 def _run(self, method):
140 u = urlparse(self.path)
141 env = dict(os.environ)
142 env["QUERY_STRING"] = u.query
143 env["REQUEST_METHOD"] = method
144 env.pop("BOT_PASSWORD", None)
145 env["GITSTAT_ONLY_ROOTS"] = "1"
146 env["GITSTAT_ROOTS"] = self.roots
147 env["GITSTAT_ALLOW_FETCH"] = self.allow_fetch
148 out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout
149 sep = out.find(b"\r\n\r\n")
150 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
151 body = out[sep + 4:] if sep >= 0 else out
152 ctype = "text/html; charset=utf-8"
153 status = 200
154 for line in headers.splitlines():
155 low = line.lower()
156 if low.startswith("content-type:"):
157 ctype = line.split(":", 1)[1].strip()
158 if low.startswith("status:"):
159 try:
160 status = int(line.split(":", 1)[1].split()[0])
161 except (IndexError, ValueError):
162 status = 200
163 self.send_response(status)
164 self.send_header("Content-Type", ctype)
165 self.send_header("Cache-Control", "no-store")
166 self.send_header("Content-Length", str(len(body)))
167 self.end_headers()
168 self.wfile.write(body)
169
170 def do_GET(self): # noqa: N802
171 self._run("GET")
172
173 def do_POST(self): # noqa: N802
174 self._run("POST")
175
176 def log_message(self, *_a):
177 pass
178
179
180def main():
181 ap = argparse.ArgumentParser()
182 ap.add_argument("--strict", action="store_true")
183 args = ap.parse_args()
184
185 if not os.path.exists(BIN):
186 print("plugin_gitstat is not built; run make first", file=sys.stderr)
187 return 1
188
189 try:
190 from playwright.sync_api import sync_playwright
191 except Exception:
192 msg = "playwright not installed - skipping viewport e2e"
193 if args.strict:
194 print(msg, file=sys.stderr)
195 return 2
196 print(msg)
197 return 0
198
199 base = tempfile.mkdtemp(prefix="gitstat-e2e-")
200 try:
201 roots = build_fixtures(base)
202 except subprocess.CalledProcessError as exc:
203 print("cannot build the git fixtures: %s" % exc, file=sys.stderr)
204 shutil.rmtree(base, ignore_errors=True)
205 return 1
206
207 Handler.roots = roots
208 os.makedirs(DOCS, exist_ok=True)
209
210 failures = []
211 with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv:
212 port = srv.server_address[1]
213 threading.Thread(target=srv.serve_forever, daemon=True).start()
214 url_base = "http://127.0.0.1:%d/plugin_gitstat" % port
215
216 with sync_playwright() as p:
217 browser = p.chromium.launch()
218 for (w, h) in VIEWPORTS:
219 for theme in THEMES:
220 url = "%s?theme=%s" % (url_base, theme)
221 page = browser.new_page(viewport={"width": w, "height": h})
222 errors = []
223 page.on("console", lambda m: errors.append(m.text)
224 if m.type == "error" else None)
225 page.on("pageerror", lambda e: errors.append(str(e)))
226 page.goto(url, wait_until="load")
227 page.wait_for_timeout(1200)
228
229 sw = page.evaluate("document.documentElement.scrollWidth")
230 iw = page.evaluate("window.innerWidth")
231 if sw > iw + 1:
232 failures.append("%dx%d %s horizontal overflow %d > %d"
233 % (w, h, theme, sw, iw))
234
235 applied = page.evaluate(
236 "document.documentElement.getAttribute('data-theme')")
237 if applied != theme:
238 failures.append("%dx%d %s ?theme= did not apply (%r)"
239 % (w, h, theme, applied))
240
241 total = page.evaluate(
242 "document.getElementById('vAll').textContent")
243 if total.strip() != "4":
244 failures.append("%dx%d %s All chip says %r, want 4"
245 % (w, h, theme, total))
246
247 rows = page.evaluate(
248 "document.querySelectorAll('#rows tr.row').length")
249 if rows != 4:
250 failures.append("%dx%d %s table has %d rows, want 4"
251 % (w, h, theme, rows))
252
253 dirty_v = page.evaluate(
254 "document.getElementById('vDirty').textContent")
255 if dirty_v.strip() != "1":
256 failures.append("%dx%d %s Dirty chip says %r, want 1"
257 % (w, h, theme, dirty_v))
258
259 stash_v = page.evaluate(
260 "document.getElementById('vStash').textContent")
261 if stash_v.strip() != "1":
262 failures.append("%dx%d %s Stash chip says %r, want 1"
263 % (w, h, theme, stash_v))
264
265 # the dirty repo must sort first
266 first = page.evaluate(
267 "document.querySelector('#rows tr.row .name').textContent")
268 if first != "billing-service":
269 failures.append("%dx%d %s first row is %r, want the dirty repo"
270 % (w, h, theme, first))
271
272 # search narrows the list
273 page.fill("#q", "sandbox")
274 page.wait_for_timeout(250)
275 narrowed = page.evaluate(
276 "document.querySelectorAll('#rows tr.row').length")
277 if narrowed != 1:
278 failures.append("%dx%d %s search left %d rows, want 1"
279 % (w, h, theme, narrowed))
280 page.fill("#q", "")
281 page.wait_for_timeout(250)
282
283 # the detail drawer opens with the changed file list
284 page.click("#rows tr.row")
285 page.wait_for_timeout(700)
286 opened = page.evaluate(
287 "document.getElementById('drawer').classList.contains('open')")
288 if not opened:
289 failures.append("%dx%d %s drawer did not open"
290 % (w, h, theme))
291 else:
292 files = page.evaluate(
293 "document.querySelectorAll('#dBody .flist li').length")
294 if files < 1:
295 failures.append("%dx%d %s drawer listed no changed files"
296 % (w, h, theme))
297 commits = page.evaluate(
298 "document.querySelectorAll('#dBody .clist li').length")
299 if commits < 1:
300 failures.append("%dx%d %s drawer listed no commits"
301 % (w, h, theme))
302 dsw = page.evaluate("document.documentElement.scrollWidth")
303 diw = page.evaluate("window.innerWidth")
304 if dsw > diw + 1:
305 failures.append("%dx%d %s drawer overflow %d > %d"
306 % (w, h, theme, dsw, diw))
307 page.click("#dClose")
308 page.wait_for_timeout(350)
309
310 if errors:
311 failures.append("%dx%d %s console errors: %s"
312 % (w, h, theme, errors[:3]))
313
314 shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme))
315 page.screenshot(path=shot, full_page=False)
316 page.close()
317 browser.close()
318
319 shutil.rmtree(base, ignore_errors=True)
320
321 if failures:
322 print("e2e failures:")
323 for f in failures:
324 print(" - %s" % f)
325 return 1
326 print("e2e ok: %d viewports x %d themes, screenshots in docs/"
327 % (len(VIEWPORTS), len(THEMES)))
328 return 0
329
330
331if __name__ == "__main__":
332 sys.exit(main())