scorpiox-bot-plugin-sessionstats
←e2e.pypython
136 lines · 4 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport checks for the plugin_sessionstats dashboard.
3
4Serves the plugin through a tiny CGI-style HTTP shim on a loopback port, opens
5it with Playwright at 1440 / 1024 / 390 CSS pixels, and asserts there is no
6horizontal overflow, no console error, and that the KPI cards, the profile bars
7and the session table all rendered from the live session store. Skips cleanly
8(exit 0) when Playwright is not installed, so the offline suite stays
9dependency-free.
10
11 python3 tests/e2e.py # run if Playwright is available
12 python3 tests/e2e.py --strict # exit 2 when Playwright is missing
13"""
14
15import argparse
16import http.server
17import os
18import socketserver
19import subprocess
20import sys
21import threading
22
23ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
24BIN = os.path.join(ROOT, "plugin_sessionstats")
25VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
26
27
28class Handler(http.server.BaseHTTPRequestHandler):
29 def do_GET(self): # noqa: N802
30 from urllib.parse import urlparse
31 u = urlparse(self.path)
32 env = dict(os.environ)
33 env["QUERY_STRING"] = u.query
34 env["REQUEST_METHOD"] = "GET"
35 env.pop("BOT_PASSWORD", None)
36 out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout
37 sep = out.find(b"\r\n\r\n")
38 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
39 body = out[sep + 4:] if sep >= 0 else out
40 ctype = "text/html; charset=utf-8"
41 for line in headers.splitlines():
42 if line.lower().startswith("content-type:"):
43 ctype = line.split(":", 1)[1].strip()
44 self.send_response(200)
45 self.send_header("Content-Type", ctype)
46 self.send_header("Cache-Control", "no-store")
47 self.send_header("Content-Length", str(len(body)))
48 self.end_headers()
49 self.wfile.write(body)
50
51 def log_message(self, *_a):
52 pass
53
54
55def main():
56 ap = argparse.ArgumentParser()
57 ap.add_argument("--strict", action="store_true")
58 args = ap.parse_args()
59
60 if not os.path.exists(BIN):
61 print("plugin_sessionstats is not built; run make first", file=sys.stderr)
62 return 1
63
64 try:
65 from playwright.sync_api import sync_playwright
66 except Exception:
67 msg = "playwright not installed - skipping viewport e2e"
68 if args.strict:
69 print(msg, file=sys.stderr)
70 return 2
71 print(msg)
72 return 0
73
74 with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv:
75 port = srv.server_address[1]
76 threading.Thread(target=srv.serve_forever, daemon=True).start()
77 url = "http://127.0.0.1:%d/plugin_sessionstats" % port
78
79 failures = []
80 with sync_playwright() as p:
81 browser = p.chromium.launch()
82 for (w, h) in VIEWPORTS:
83 page = browser.new_page(viewport={"width": w, "height": h})
84 errors = []
85 page.on("console", lambda m: errors.append(m.text)
86 if m.type == "error" else None)
87 page.goto(url, wait_until="load")
88 page.wait_for_timeout(2200)
89
90 sw = page.evaluate("document.documentElement.scrollWidth")
91 iw = page.evaluate("window.innerWidth")
92 if sw > iw + 1:
93 failures.append("%dx%d horizontal overflow %d > %d" % (w, h, sw, iw))
94
95 sessions = page.evaluate(
96 "document.getElementById('kSessions').textContent")
97 if not sessions.strip().isdigit():
98 failures.append("%dx%d sessions KPI did not render (%r)"
99 % (w, h, sessions))
100
101 duty = page.evaluate(
102 "document.getElementById('kDuty').textContent")
103 if "%" not in duty:
104 failures.append("%dx%d duty KPI did not render (%r)"
105 % (w, h, duty))
106
107 bars = page.evaluate(
108 "document.querySelectorAll('#profBars .row').length")
109 if bars < 1:
110 failures.append("%dx%d no profile bar rendered" % (w, h))
111
112 rows = page.evaluate(
113 "document.querySelectorAll('#tbody tr').length")
114 if rows < 1:
115 failures.append("%dx%d session table is empty" % (w, h))
116
117 if errors:
118 failures.append("%dx%d console errors: %s" % (w, h, errors[:3]))
119
120 page.screenshot(path=os.path.join(ROOT, "docs",
121 "shot-%dx%d.png" % (w, h)))
122 page.close()
123 browser.close()
124
125 if failures:
126 print("FAIL")
127 for f in failures:
128 print(" " + f)
129 return 1
130
131 print("PASS - %d viewports clean" % len(VIEWPORTS))
132 return 0
133
134
135if __name__ == "__main__":
136 sys.exit(main())