scorpiox-bot-plugin-services
←e2e.pypython
204 lines · 8 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport checks for the plugin_services board.
3
4Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, points it
5at the systemd fixtures so the table is always populated, 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 socketserver
20import subprocess
21import sys
22import tempfile
23import threading
24from urllib.parse import urlparse
25
26ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27BIN = os.path.join(ROOT, "plugin_services")
28DOCS = os.path.join(ROOT, "docs")
29VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
30THEMES = ["dark", "light"]
31
32UNITS = """[{"unit":"nginx.service","load":"loaded","active":"active","sub":"running","description":"A high performance web server and a reverse proxy server"},
33 {"unit":"ssh.service","load":"loaded","active":"active","sub":"running","description":"OpenBSD Secure Shell server"},
34 {"unit":"cron.service","load":"loaded","active":"inactive","sub":"dead","description":"Regular background program processing daemon"},
35 {"unit":"docker.service","load":"loaded","active":"active","sub":"running","description":"Docker Application Container Engine"},
36 {"unit":"broken.service","load":"loaded","active":"failed","sub":"failed","description":"A service that failed on purpose"},
37 {"unit":"postgresql.service","load":"loaded","active":"inactive","sub":"dead","description":"PostgreSQL RDBMS"}]
38"""
39
40SHOW = """Id=nginx.service
41MainPID=4242
42MemoryCurrent=10485760
43UnitFileState=enabled
44ActiveEnterTimestamp=Wed 2026-11-12 04:00:00 UTC
45
46Id=ssh.service
47MainPID=912
48MemoryCurrent=7340032
49UnitFileState=static
50ActiveEnterTimestamp=Wed 2026-11-12 03:00:00 UTC
51
52Id=docker.service
53MainPID=1180
54MemoryCurrent=205520896
55UnitFileState=enabled
56ActiveEnterTimestamp=Wed 2026-11-12 02:12:00 UTC
57
58"""
59
60
61class Handler(http.server.BaseHTTPRequestHandler):
62 fixture_dir = ""
63
64 def do_GET(self): # noqa: N802
65 u = urlparse(self.path)
66 env = dict(os.environ)
67 env["QUERY_STRING"] = u.query
68 env["REQUEST_METHOD"] = "GET"
69 env.pop("BOT_PASSWORD", None)
70 env["SERVICES_MOCK_SYSTEMCTL"] = os.path.join(self.fixture_dir, "units.json")
71 env["SERVICES_MOCK_SYSTEMCTL_SHOW"] = os.path.join(self.fixture_dir, "show.txt")
72 out = subprocess.run([BIN], capture_output=True, env=env, timeout=30).stdout
73 sep = out.find(b"\r\n\r\n")
74 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
75 body = out[sep + 4:] if sep >= 0 else out
76 ctype = "text/html; charset=utf-8"
77 for line in headers.splitlines():
78 if line.lower().startswith("content-type:"):
79 ctype = line.split(":", 1)[1].strip()
80 self.send_response(200)
81 self.send_header("Content-Type", ctype)
82 self.send_header("Cache-Control", "no-store")
83 self.send_header("Content-Length", str(len(body)))
84 self.end_headers()
85 self.wfile.write(body)
86
87 def log_message(self, *_a):
88 pass
89
90
91def main():
92 ap = argparse.ArgumentParser()
93 ap.add_argument("--strict", action="store_true")
94 args = ap.parse_args()
95
96 if not os.path.exists(BIN):
97 print("plugin_services is not built; run make first", file=sys.stderr)
98 return 1
99
100 try:
101 from playwright.sync_api import sync_playwright
102 except Exception:
103 msg = "playwright not installed - skipping viewport e2e"
104 if args.strict:
105 print(msg, file=sys.stderr)
106 return 2
107 print(msg)
108 return 0
109
110 fixture_dir = tempfile.mkdtemp(prefix="services-e2e-")
111 with open(os.path.join(fixture_dir, "units.json"), "w", encoding="utf-8") as f:
112 f.write(UNITS)
113 with open(os.path.join(fixture_dir, "show.txt"), "w", encoding="utf-8") as f:
114 f.write(SHOW)
115 Handler.fixture_dir = fixture_dir
116
117 os.makedirs(DOCS, exist_ok=True)
118
119 with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv:
120 port = srv.server_address[1]
121 threading.Thread(target=srv.serve_forever, daemon=True).start()
122 base = "http://127.0.0.1:%d/plugin_services" % port
123
124 failures = []
125 with sync_playwright() as p:
126 browser = p.chromium.launch()
127 for (w, h) in VIEWPORTS:
128 for theme in THEMES:
129 url = "%s?theme=%s" % (base, theme)
130 page = browser.new_page(viewport={"width": w, "height": h})
131 errors = []
132 page.on("console", lambda m: errors.append(m.text)
133 if m.type == "error" else None)
134 page.on("pageerror", lambda e: errors.append(str(e)))
135 page.goto(url, wait_until="load")
136 page.wait_for_timeout(1200)
137
138 sw = page.evaluate("document.documentElement.scrollWidth")
139 iw = page.evaluate("window.innerWidth")
140 if sw > iw + 1:
141 failures.append("%dx%d %s horizontal overflow %d > %d"
142 % (w, h, theme, sw, iw))
143
144 applied = page.evaluate(
145 "document.documentElement.getAttribute('data-theme')")
146 if applied != theme:
147 failures.append("%dx%d %s ?theme= did not apply (%r)"
148 % (w, h, theme, applied))
149
150 total = page.evaluate(
151 "document.getElementById('vAll').textContent")
152 if not total.strip().isdigit():
153 failures.append("%dx%d %s All chip did not render (%r)"
154 % (w, h, theme, total))
155
156 rows = page.evaluate(
157 "document.querySelectorAll('#rows tr.row').length")
158 if rows < 1:
159 failures.append("%dx%d %s service table is empty"
160 % (w, h, theme))
161
162 img = page.query_selector("#rows") and page.query_selector("svg")
163 if img is None:
164 failures.append("%dx%d %s no inline SVG icon rendered"
165 % (w, h, theme))
166
167 if theme == "dark":
168 page.click("#rows tr.row")
169 page.wait_for_timeout(350)
170 opened = page.evaluate(
171 "document.getElementById('drawer').classList.contains('open')")
172 if not opened:
173 failures.append("%dx%d drawer did not open" % (w, h))
174 name = page.evaluate(
175 "document.getElementById('dName').textContent")
176 if not name or name == "—":
177 failures.append("%dx%d drawer has no unit name" % (w, h))
178 page.screenshot(path=os.path.join(
179 DOCS, "ui-%d-%s.png" % (w, theme)), full_page=False)
180 page.click("#dClose")
181 else:
182 page.screenshot(path=os.path.join(
183 DOCS, "ui-%d-%s.png" % (w, theme)), full_page=False)
184
185 if errors:
186 failures.append("%dx%d %s console errors: %s"
187 % (w, h, theme, errors[:3]))
188
189 page.close()
190 browser.close()
191
192 if failures:
193 print("FAIL")
194 for f in failures:
195 print(" " + f)
196 return 1
197
198 print("ok - %d viewports x %d themes clean (no overflow, no console error, "
199 "chips + table + drawer rendered)" % (len(VIEWPORTS), len(THEMES)))
200 return 0
201
202
203if __name__ == "__main__":
204 sys.exit(main())