scorpiox-bot-plugin-logs
←e2e.pypython
285 lines · 11 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport and live-behaviour checks for the plugin_logs UI.
3
4Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, opens it
5with Playwright at 1440 / 1024 / 390 CSS pixels in BOTH themes, and asserts
6there is no horizontal overflow, no console error, that the source picker is
7populated from action=sources, that a tail renders rows, that a search renders
8highlighted hits, and that the live/save/theme controls respond.
9
10Skips cleanly (exit 0) when Playwright is not installed, so `make test` stays
11offline-only.
12
13 python3 tests/e2e.py # run if Playwright is available
14 python3 tests/e2e.py --strict # exit 2 when Playwright is missing
15"""
16
17import argparse
18import http.server
19import os
20import shutil
21import subprocess
22import sys
23import tempfile
24import threading
25from urllib.parse import urlparse, parse_qs
26
27ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
28BIN = os.path.join(ROOT, "plugin_logs")
29VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
30SHOTS = os.path.join(ROOT, "docs")
31
32FAILS = []
33PASSES = []
34
35
36def ok(desc):
37 PASSES.append(desc)
38 print(" ok %s" % desc)
39
40
41def bad(desc, extra=""):
42 FAILS.append(desc)
43 print(" FAIL %s%s" % (desc, (" -- " + str(extra)) if extra else ""))
44
45
46def check(desc, cond, extra=""):
47 ok(desc) if cond else bad(desc, extra)
48
49
50def prepare_fixtures():
51 """A journal fixture plus a fixture log tree, exported for the child."""
52 tmp = tempfile.mkdtemp(prefix="logs_e2e_")
53 jfix = os.path.join(tmp, "journal.jsonl")
54 with open(jfix, "w") as f:
55 rows = [
56 ("1762923001000000", "3", "nginx.service",
57 "upstream timed out while reading response header from upstream"),
58 ("1762923002000000", "4", "systemd", "Some unit is deprecated"),
59 ("1762923003000000", "6", "kernel", "eth0 link up, 1000 Mbps"),
60 ("1762923004000000", "6", "sshd.service",
61 "Accepted publickey for root from a trusted key"),
62 ("1762923005000000", "2", "postgresql.service",
63 "PANIC: could not locate a valid checkpoint record"),
64 ]
65 for ts, pri, unit, msg in rows:
66 f.write('{"__REALTIME_TIMESTAMP":"%s","PRIORITY":"%s",'
67 '"__CURSOR":"x","_SYSTEMD_UNIT":"%s","MESSAGE":"%s"}\n'
68 % (ts, pri, unit, msg))
69
70 root = os.path.join(tmp, "fixtures")
71 os.makedirs(os.path.join(root, "svc"))
72 with open(os.path.join(root, "svc", "app.log"), "w") as f:
73 for i in range(60):
74 sev = "error" if i % 7 == 0 else ("warn" if i % 5 == 0 else "info")
75 f.write("Nov 12 06:%02d:%02d host app[%d]: %s: request %d handled\n"
76 % (i // 60 % 60, i % 60, 100 + i, sev, i))
77
78 env = dict(os.environ)
79 env["SX_LOGS_JOURNAL_FIXTURE"] = jfix
80 env["SX_LOGS_EXTRA_ROOT"] = root
81 return tmp, env
82
83
84class Handler(http.server.BaseHTTPRequestHandler):
85 env = {}
86
87 def do_GET(self): # noqa: N802
88 u = urlparse(self.path)
89 qs = u.query
90 # The UI appends ?pwd= for real nodes; this shim has no password set,
91 # so just pass the query through.
92 env = dict(self.env)
93 env["QUERY_STRING"] = qs
94 env["REQUEST_METHOD"] = "GET"
95 env.pop("BOT_PASSWORD", None)
96 if parse_qs(qs).get("theme"):
97 pass
98 out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout
99 sep = out.find(b"\r\n\r\n")
100 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
101 body = out[sep + 4:] if sep >= 0 else out
102 ctype = "text/html; charset=utf-8"
103 for line in headers.splitlines():
104 if line.lower().startswith("content-type:"):
105 ctype = line.split(":", 1)[1].strip()
106 self.send_response(200)
107 self.send_header("Content-Type", ctype)
108 self.send_header("Cache-Control", "no-store")
109 # no Content-Length from the plugin; the shim sets its own framing
110 self.send_header("Content-Length", str(len(body)))
111 self.end_headers()
112 self.wfile.write(body)
113
114 def log_message(self, *_a):
115 pass
116
117
118def serve(env):
119 Handler.env = env
120 httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
121 t = threading.Thread(target=httpd.serve_forever, daemon=True)
122 t.start()
123 return httpd, httpd.server_address[1]
124
125
126def main():
127 ap = argparse.ArgumentParser()
128 ap.add_argument("--strict", action="store_true")
129 args = ap.parse_args()
130
131 try:
132 from playwright.sync_api import sync_playwright
133 except Exception:
134 print(" skip e2e (playwright not installed)")
135 return 2 if args.strict else 0
136
137 if not os.path.exists(BIN):
138 print(" FAIL plugin binary missing; run `make` first")
139 return 1
140
141 tmp, env = prepare_fixtures()
142 httpd, port = serve(env)
143 base = "http://127.0.0.1:%d/" % port
144 print("== e2e: %s ==" % base)
145
146 os.makedirs(SHOTS, exist_ok=True)
147 try:
148 with sync_playwright() as p:
149 browser = p.chromium.launch()
150 for w, h in VIEWPORTS:
151 for theme in ("dark", "light"):
152 page = browser.new_page(viewport={"width": w, "height": h},
153 device_scale_factor=1)
154 errors = []
155 page.on("console", lambda m: errors.append(m.text)
156 if m.type == "error" else None)
157 page.on("pageerror", lambda e: errors.append(str(e)))
158 page.goto(base + "?theme=" + theme, wait_until="load")
159 page.wait_for_timeout(900)
160
161 tag = "%dx%d %s" % (w, h, theme)
162 check("%s: no console errors" % tag, not errors, errors[:3])
163
164 # theme actually applied
165 attr = page.evaluate(
166 "document.documentElement.getAttribute('data-theme')")
167 check("%s: theme applied" % tag, attr == theme, attr)
168
169 # horizontal overflow
170 over = page.evaluate(
171 "() => Math.max(document.documentElement.scrollWidth,"
172 " document.body.scrollWidth) - window.innerWidth")
173 check("%s: no horizontal overflow" % tag, over <= 1, over)
174
175 # source picker populated from action=sources
176 n = page.evaluate("document.querySelectorAll('#srcSel option').length")
177 check("%s: source picker populated" % tag, n >= 2, n)
178
179 # tail rendered rows
180 rows = page.evaluate("document.querySelectorAll('#log .ln').length")
181 check("%s: tail rendered entries" % tag, rows >= 5, rows)
182
183 # severity colouring present at least once
184 sev = page.evaluate(
185 "document.querySelectorAll('#log .ln.err, #log .ln.warn').length")
186 check("%s: severity classes applied" % tag, sev >= 1, sev)
187
188 # no stray grid overflow inside the log
189 clip = page.evaluate(
190 "() => { var l=document.getElementById('log');"
191 " return l.scrollWidth - l.clientWidth; }")
192 check("%s: log body fits its own width" % tag, clip <= 2, clip)
193
194 shot = os.path.join(SHOTS, "ui-%dx%d-%s.png" % (w, h, theme))
195 page.screenshot(path=shot, full_page=False)
196 size = os.path.getsize(shot)
197 check("%s: screenshot < 900 KB" % tag, size < 900 * 1024, size)
198
199 page.close()
200
201 # one deep behavioural run at the primary viewport
202 page = browser.new_page(viewport={"width": 1440, "height": 900})
203 page.goto(base + "?theme=dark", wait_until="load")
204 page.wait_for_timeout(800)
205
206 # switch to the fixture app.log, which carries "error" lines
207 page.evaluate(
208 "() => { var sel = document.getElementById('srcSel');"
209 " for (var i = 0; i < sel.options.length; i++) {"
210 " if (sel.options[i].value.indexOf('app.log') >= 0) {"
211 " sel.value = sel.options[i].value;"
212 " sel.dispatchEvent(new Event('change')); return; } } }")
213 page.wait_for_timeout(800)
214
215 # search renders highlighted hits
216 page.fill("#q", "error")
217 page.click("#btnSearch")
218 page.wait_for_timeout(900)
219 marks = page.evaluate("document.querySelectorAll('#log mark').length")
220 check("search renders highlighted hits", marks >= 1, marks)
221 fcount = page.inner_text("#fCount")
222 check("search reports hits and scanned count",
223 "hits" in fcount and "scanned" in fcount, fcount)
224
225 # wrap toggle widens the layout class
226 page.click("#btnWrap")
227 page.wait_for_timeout(150)
228 wrap = page.evaluate("document.getElementById('log').classList.contains('wrap')")
229 check("wrap toggle applies", wrap is True, wrap)
230 page.click("#btnWrap")
231
232 # clearing the query returns to tail
233 page.fill("#q", "")
234 page.click("#btnSearch")
235 page.wait_for_timeout(700)
236 rows = page.evaluate("document.querySelectorAll('#log .ln').length")
237 check("empty query returns to tail", rows >= 5, rows)
238
239 # follow toggle pauses the poller
240 page.click("#btnFollow")
241 page.wait_for_timeout(200)
242 st = page.inner_text("#pState")
243 check("follow toggle pauses", "paused" in st.lower(), st)
244 page.click("#btnFollow")
245
246 # line-count segment changes the request
247 page.click("#segLines button[data-n='500']")
248 page.wait_for_timeout(700)
249 on = page.evaluate(
250 "document.querySelector('#segLines button.on').getAttribute('data-n')")
251 check("line-count segment switches", on == "500", on)
252
253 # theme button flips the document
254 before = page.evaluate("document.documentElement.getAttribute('data-theme')")
255 page.click("#btnTheme")
256 page.wait_for_timeout(200)
257 after = page.evaluate("document.documentElement.getAttribute('data-theme')")
258 check("theme button flips appearance", before != after, (before, after))
259
260 # embed mode hides the back-link only
261 page.goto(base + "?embed=1&theme=dark", wait_until="load")
262 page.wait_for_timeout(600)
263 body = page.inner_text("body")
264 check("embed=1 hides the back-link", "Back to Bot" not in body)
265 rows = page.evaluate("document.querySelectorAll('#log .ln').length")
266 check("embed=1 still renders entries", rows >= 5, rows)
267
268 page.close()
269 browser.close()
270 finally:
271 httpd.shutdown()
272 shutil.rmtree(tmp, ignore_errors=True)
273
274 print("\n== summary ==")
275 print(" passed: %d" % len(PASSES))
276 print(" failed: %d" % len(FAILS))
277 if FAILS:
278 print(" RESULT: FAILED")
279 return 1
280 print(" RESULT: ALL PASSED")
281 return 0
282
283
284if __name__ == "__main__":
285 sys.exit(main())