#!/usr/bin/env python3 """tests/e2e.py - viewport checks for the plugin_gitstat board. Builds a small fixture tree of real git repositories in a temp directory, serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, and opens it with Playwright at 1440 / 1024 / 390 CSS pixels in both themes. It asserts there is no horizontal overflow, no console error, that the summary chips and the table rendered, and that a row opens the detail drawer. Screenshots land in docs/ for the README. Skips cleanly (exit 0) when Playwright is not installed, so the offline suite stays dependency-free. python3 tests/e2e.py # run if Playwright is available python3 tests/e2e.py --strict # exit 2 when Playwright is missing """ import argparse import http.server import os import shutil import socketserver import subprocess import sys import tempfile import threading from urllib.parse import urlparse ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.path.join(ROOT, "plugin_gitstat") DOCS = os.path.join(ROOT, "docs") VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] THEMES = ["dark", "light"] GITENV = { "GIT_AUTHOR_NAME": "Gitstat E2E", "GIT_AUTHOR_EMAIL": "gitstat@example.invalid", "GIT_COMMITTER_NAME": "Gitstat E2E", "GIT_COMMITTER_EMAIL": "gitstat@example.invalid", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "GIT_TERMINAL_PROMPT": "0", } def git(cwd, *args): env = dict(os.environ) env.update(GITENV) return subprocess.run(["git", "-C", cwd] + list(args), env=env, check=True, capture_output=True) def mkrepo(path, branch="main"): os.makedirs(path, exist_ok=True) git(path, "init", "-q", "-b", branch) git(path, "config", "user.name", "Gitstat E2E") git(path, "config", "user.email", "gitstat@example.invalid") def build_fixtures(base): """Four repos, one per interesting visual state.""" roots = os.path.join(base, "roots") os.makedirs(roots) # clean, in sync with an upstream up = os.path.join(base, "up.git") git(base, "init", "-q", "--bare", up) git(up, "symbolic-ref", "HEAD", "refs/heads/main") seed = os.path.join(base, "seed") mkrepo(seed) with open(os.path.join(seed, "README.md"), "w", encoding="utf-8") as f: f.write("seed\n") git(seed, "add", "README.md") git(seed, "commit", "-q", "-m", "Add the README that everything else builds on") git(seed, "remote", "add", "origin", up) git(seed, "push", "-q", "-u", "origin", "main") git(base, "clone", "-q", up, os.path.join(roots, "portal-web")) c = os.path.join(roots, "portal-web") git(c, "config", "user.name", "Gitstat E2E") git(c, "config", "user.email", "gitstat@example.invalid") # dirty working tree d = os.path.join(roots, "billing-service") mkrepo(d) for name in ("main.c", "util.c", "notes.md"): with open(os.path.join(d, name), "w", encoding="utf-8") as f: f.write("x\n") git(d, "add", ".") git(d, "commit", "-q", "-m", "Split the invoice renderer out of the billing loop") with open(os.path.join(d, "main.c"), "a", encoding="utf-8") as f: f.write("patched\n") with open(os.path.join(d, "util.c"), "a", encoding="utf-8") as f: f.write("staged\n") git(d, "add", "util.c") with open(os.path.join(d, "untracked.txt"), "w", encoding="utf-8") as f: f.write("new\n") # ahead by two, with a stash a = os.path.join(roots, "fleet-agent") up2 = os.path.join(base, "up2.git") git(base, "init", "-q", "--bare", up2) git(up2, "symbolic-ref", "HEAD", "refs/heads/main") seed2 = os.path.join(base, "seed2") mkrepo(seed2) with open(os.path.join(seed2, "a.txt"), "w", encoding="utf-8") as f: f.write("a\n") git(seed2, "add", "a.txt") git(seed2, "commit", "-q", "-m", "Start the agent loop") git(seed2, "remote", "add", "origin", up2) git(seed2, "push", "-q", "-u", "origin", "main") git(base, "clone", "-q", up2, a) git(a, "config", "user.name", "Gitstat E2E") git(a, "config", "user.email", "gitstat@example.invalid") for msg in ("Teach the agent to retry a dropped socket", "Cap the retry backoff at thirty seconds"): with open(os.path.join(a, "a.txt"), "a", encoding="utf-8") as f: f.write(msg + "\n") git(a, "commit", "-q", "-am", msg) with open(os.path.join(a, "a.txt"), "a", encoding="utf-8") as f: f.write("wip\n") git(a, "stash", "push", "-q", "-m", "half-finished backoff rewrite") # detached x = os.path.join(roots, "proto-sandbox") mkrepo(x) with open(os.path.join(x, "p.txt"), "w", encoding="utf-8") as f: f.write("p\n") git(x, "add", "p.txt") git(x, "commit", "-q", "-m", "First prototype of the graph walker") with open(os.path.join(x, "p.txt"), "a", encoding="utf-8") as f: f.write("q\n") git(x, "commit", "-q", "-am", "Walk depth-first instead") git(x, "checkout", "-q", "HEAD~1") return roots class Handler(http.server.BaseHTTPRequestHandler): roots = "" allow_fetch = "0" def _run(self, method): u = urlparse(self.path) env = dict(os.environ) env["QUERY_STRING"] = u.query env["REQUEST_METHOD"] = method env.pop("BOT_PASSWORD", None) env["GITSTAT_ONLY_ROOTS"] = "1" env["GITSTAT_ROOTS"] = self.roots env["GITSTAT_ALLOW_FETCH"] = self.allow_fetch out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout sep = out.find(b"\r\n\r\n") headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" body = out[sep + 4:] if sep >= 0 else out ctype = "text/html; charset=utf-8" status = 200 for line in headers.splitlines(): low = line.lower() if low.startswith("content-type:"): ctype = line.split(":", 1)[1].strip() if low.startswith("status:"): try: status = int(line.split(":", 1)[1].split()[0]) except (IndexError, ValueError): status = 200 self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def do_GET(self): # noqa: N802 self._run("GET") def do_POST(self): # noqa: N802 self._run("POST") def log_message(self, *_a): pass def main(): ap = argparse.ArgumentParser() ap.add_argument("--strict", action="store_true") args = ap.parse_args() if not os.path.exists(BIN): print("plugin_gitstat is not built; run make first", file=sys.stderr) return 1 try: from playwright.sync_api import sync_playwright except Exception: msg = "playwright not installed - skipping viewport e2e" if args.strict: print(msg, file=sys.stderr) return 2 print(msg) return 0 base = tempfile.mkdtemp(prefix="gitstat-e2e-") try: roots = build_fixtures(base) except subprocess.CalledProcessError as exc: print("cannot build the git fixtures: %s" % exc, file=sys.stderr) shutil.rmtree(base, ignore_errors=True) return 1 Handler.roots = roots os.makedirs(DOCS, exist_ok=True) failures = [] with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv: port = srv.server_address[1] threading.Thread(target=srv.serve_forever, daemon=True).start() url_base = "http://127.0.0.1:%d/plugin_gitstat" % port with sync_playwright() as p: browser = p.chromium.launch() for (w, h) in VIEWPORTS: for theme in THEMES: url = "%s?theme=%s" % (url_base, theme) page = browser.new_page(viewport={"width": w, "height": h}) errors = [] page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None) page.on("pageerror", lambda e: errors.append(str(e))) page.goto(url, wait_until="load") page.wait_for_timeout(1200) sw = page.evaluate("document.documentElement.scrollWidth") iw = page.evaluate("window.innerWidth") if sw > iw + 1: failures.append("%dx%d %s horizontal overflow %d > %d" % (w, h, theme, sw, iw)) applied = page.evaluate( "document.documentElement.getAttribute('data-theme')") if applied != theme: failures.append("%dx%d %s ?theme= did not apply (%r)" % (w, h, theme, applied)) total = page.evaluate( "document.getElementById('vAll').textContent") if total.strip() != "4": failures.append("%dx%d %s All chip says %r, want 4" % (w, h, theme, total)) rows = page.evaluate( "document.querySelectorAll('#rows tr.row').length") if rows != 4: failures.append("%dx%d %s table has %d rows, want 4" % (w, h, theme, rows)) dirty_v = page.evaluate( "document.getElementById('vDirty').textContent") if dirty_v.strip() != "1": failures.append("%dx%d %s Dirty chip says %r, want 1" % (w, h, theme, dirty_v)) stash_v = page.evaluate( "document.getElementById('vStash').textContent") if stash_v.strip() != "1": failures.append("%dx%d %s Stash chip says %r, want 1" % (w, h, theme, stash_v)) # the dirty repo must sort first first = page.evaluate( "document.querySelector('#rows tr.row .name').textContent") if first != "billing-service": failures.append("%dx%d %s first row is %r, want the dirty repo" % (w, h, theme, first)) # search narrows the list page.fill("#q", "sandbox") page.wait_for_timeout(250) narrowed = page.evaluate( "document.querySelectorAll('#rows tr.row').length") if narrowed != 1: failures.append("%dx%d %s search left %d rows, want 1" % (w, h, theme, narrowed)) page.fill("#q", "") page.wait_for_timeout(250) # the detail drawer opens with the changed file list page.click("#rows tr.row") page.wait_for_timeout(700) opened = page.evaluate( "document.getElementById('drawer').classList.contains('open')") if not opened: failures.append("%dx%d %s drawer did not open" % (w, h, theme)) else: files = page.evaluate( "document.querySelectorAll('#dBody .flist li').length") if files < 1: failures.append("%dx%d %s drawer listed no changed files" % (w, h, theme)) commits = page.evaluate( "document.querySelectorAll('#dBody .clist li').length") if commits < 1: failures.append("%dx%d %s drawer listed no commits" % (w, h, theme)) dsw = page.evaluate("document.documentElement.scrollWidth") diw = page.evaluate("window.innerWidth") if dsw > diw + 1: failures.append("%dx%d %s drawer overflow %d > %d" % (w, h, theme, dsw, diw)) page.click("#dClose") page.wait_for_timeout(350) if errors: failures.append("%dx%d %s console errors: %s" % (w, h, theme, errors[:3])) shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme)) page.screenshot(path=shot, full_page=False) page.close() browser.close() shutil.rmtree(base, ignore_errors=True) if failures: print("e2e failures:") for f in failures: print(" - %s" % f) return 1 print("e2e ok: %d viewports x %d themes, screenshots in docs/" % (len(VIEWPORTS), len(THEMES))) return 0 if __name__ == "__main__": sys.exit(main())