scorpiox-bot-plugin-files
←e2e.pypython
317 lines · 13 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport checks for the plugin_files browser.
3
4Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens
5it with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts:
6
7 * no console error and no page error at any viewport
8 * scrollWidth <= innerWidth (no horizontal overflow)
9 * the root list renders, a directory opens, a text file previews with line
10 numbers, a markdown file renders, an image previews
11 * the rendered page really has a stylesheet and a working script
12 * screenshots land in docs/ for the README
13
14Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays
15dependency-free.
16
17 python3 tests/e2e.py # run if Playwright is available
18 python3 tests/e2e.py --strict # exit 2 when Playwright is missing
19"""
20
21import argparse
22import http.server
23import os
24import shutil
25import socketserver
26import subprocess
27import sys
28import tempfile
29import threading
30from urllib.parse import urlparse
31
32ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
33BIN = os.path.join(ROOT, "plugin_files")
34DOCS = os.path.join(ROOT, "docs")
35VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
36THEMES = ["dark", "light"]
37
38PNG_1PX = (
39 b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
40 b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01"
41 b"\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82"
42)
43
44
45class Handler(http.server.BaseHTTPRequestHandler):
46 root_dir = ""
47
48 def _run(self, method):
49 u = urlparse(self.path)
50 length = int(self.headers.get("Content-Length") or 0)
51 body = self.rfile.read(length) if length else b""
52 env = dict(os.environ)
53 env["QUERY_STRING"] = u.query
54 env["REQUEST_METHOD"] = method
55 env["FILES_ALLOWED_ROOT"] = self.root_dir
56 env.pop("BOT_PASSWORD", None)
57 env["CONTENT_LENGTH"] = str(len(body))
58 out = subprocess.run(
59 [BIN], input=body, capture_output=True, env=env, timeout=60
60 ).stdout
61 sep = out.find(b"\r\n\r\n")
62 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
63 payload = out[sep + 4:] if sep >= 0 else out
64 status = 200
65 ctype = "application/json; charset=utf-8"
66 for line in headers.splitlines():
67 low = line.lower()
68 if low.startswith("content-type:"):
69 ctype = line.split(":", 1)[1].strip()
70 elif low.startswith("status:"):
71 try:
72 status = int(line.split(":", 1)[1].strip().split()[0])
73 except (IndexError, ValueError):
74 status = 200
75 self.send_response(status)
76 self.send_header("Content-Type", ctype)
77 self.send_header("Cache-Control", "no-store")
78 self.send_header("Content-Length", str(len(payload)))
79 self.end_headers()
80 self.wfile.write(payload)
81
82 def do_GET(self): # noqa: N802
83 self._run("GET")
84
85 def do_POST(self): # noqa: N802
86 self._run("POST")
87
88 def log_message(self, *_a):
89 pass
90
91
92def seed(root_dir):
93 os.makedirs(os.path.join(root_dir, "src"), exist_ok=True)
94 os.makedirs(os.path.join(root_dir, "docs"), exist_ok=True)
95
96 with open(os.path.join(root_dir, "README.md"), "w", encoding="utf-8") as f:
97 f.write(
98 "# Local File Browser\n\n"
99 "A read-only browser for **SCORPIOX BOT** nodes.\n\n"
100 "- list directories inside the allowlisted roots\n"
101 "- preview text with line numbers\n"
102 "- view images and download files\n\n"
103 "> Nothing on disk can be modified by this plugin.\n\n"
104 "```\ncurl 'http://node:8150/plugin_files?action=roots'\n```\n"
105 )
106 with open(os.path.join(root_dir, "src", "main.c"), "w", encoding="utf-8") as f:
107 f.write("#include <stdio.h>\n\nint main(void)\n{\n puts(\"hi\");\n return 0;\n}\n")
108 with open(os.path.join(root_dir, "notes.txt"), "w", encoding="utf-8") as f:
109 f.write("line one\nline two\nline three\n")
110 with open(os.path.join(root_dir, "blob.bin"), "wb") as f:
111 f.write(b"PK\x03\x04\x00\x00binary\x00data\x00")
112 with open(os.path.join(root_dir, "docs", "pixel.png"), "wb") as f:
113 f.write(PNG_1PX)
114 with open(os.path.join(root_dir, ".hiddenrc"), "w", encoding="utf-8") as f:
115 f.write("hidden\n")
116
117
118def main():
119 ap = argparse.ArgumentParser()
120 ap.add_argument("--strict", action="store_true",
121 help="exit 2 when Playwright is not installed")
122 args = ap.parse_args()
123
124 try:
125 from playwright.sync_api import sync_playwright
126 except Exception:
127 print("playwright not installed - skipping e2e (offline suite is unaffected)")
128 return 2 if args.strict else 0
129
130 if not os.path.exists(BIN):
131 print("plugin_files not built - run make first")
132 return 1
133
134 work = tempfile.mkdtemp(prefix="files-e2e-")
135 root_dir = os.path.join(work, "root")
136 os.makedirs(root_dir, exist_ok=True)
137 seed(root_dir)
138 Handler.root_dir = root_dir
139
140 httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler)
141 port = httpd.server_address[1]
142 threading.Thread(target=httpd.serve_forever, daemon=True).start()
143 base = "http://127.0.0.1:%d/" % port
144
145 os.makedirs(DOCS, exist_ok=True)
146 failures = []
147 checks = 0
148
149 def ok(cond, label):
150 nonlocal checks
151 checks += 1
152 if not cond:
153 failures.append(label)
154 print(" FAIL %s" % label)
155
156 try:
157 with sync_playwright() as pw:
158 browser = pw.chromium.launch()
159 for w, h in VIEWPORTS:
160 for theme in THEMES:
161 page = browser.new_page(viewport={"width": w, "height": h},
162 color_scheme=theme)
163 errors = []
164 page.on("console", lambda m: errors.append(m.text)
165 if m.type == "error" else None)
166 page.on("pageerror", lambda e: errors.append(str(e)))
167
168 page.goto(base + "?theme=%s" % theme, wait_until="load")
169 page.wait_for_selector(".root", timeout=8000)
170
171 ok(page.locator(".root").count() >= 1,
172 "roots rendered @%dx%d %s" % (w, h, theme))
173 # the seeded root is the last one, so pick it by its path
174 page.evaluate(
175 "ROOTPATH => Array.from(document.querySelectorAll('.root'))"
176 ".filter(function(b){return b.textContent.indexOf(ROOTPATH)>=0;})[0]"
177 ".click()", root_dir)
178 page.wait_for_function(
179 "document.querySelectorAll('.row').length >= 4",
180 timeout=8000)
181 page.wait_for_selector(".row", timeout=8000)
182
183 ok(page.locator(".row").count() >= 4,
184 "entries listed @%dx%d %s" % (w, h, theme))
185 ok(page.locator(".row.dir").count() >= 2,
186 "directories first @%dx%d %s" % (w, h, theme))
187 ok(".hiddenrc" not in page.inner_text("#entries"),
188 "hidden files hidden by default @%dx%d %s" % (w, h, theme))
189
190 sw = page.evaluate("document.documentElement.scrollWidth")
191 iw = page.evaluate("window.innerWidth")
192 ok(sw <= iw + 1, "no h-overflow (%d<=%d) @%dx%d %s"
193 % (sw, iw, w, h, theme))
194
195 # a real stylesheet, not plain text in the page
196 ok(page.evaluate(
197 "document.styleSheets.length>0 && "
198 "Array.from(document.styleSheets)"
199 ".reduce(function(n,s){return n+s.cssRules.length;},0)>80"),
200 "stylesheet parsed @%dx%d %s" % (w, h, theme))
201
202 # open the markdown file -> rendered headings and bold
203 page.evaluate(
204 "Array.from(document.querySelectorAll('.row'))"
205 ".filter(function(b){return b.textContent.indexOf('README.md')>=0;})[0]"
206 ".click()")
207 page.wait_for_selector(".md h1", timeout=8000)
208 html = page.inner_html(".md")
209 ok("<h1>Local File Browser</h1>" in html,
210 "markdown h1 rendered @%dx%d %s" % (w, h, theme))
211 ok("<strong>SCORPIOX BOT</strong>" in html,
212 "markdown bold rendered @%dx%d %s" % (w, h, theme))
213 ok("<script>" not in html,
214 "no raw script tag in preview @%dx%d %s" % (w, h, theme))
215
216 # text preview has line numbers
217 page.evaluate(
218 "Array.from(document.querySelectorAll('.row'))"
219 ".filter(function(b){return b.textContent.indexOf('notes.txt')>=0;})[0]"
220 ".click()")
221 page.wait_for_selector(".codetxt", timeout=8000)
222 ok(page.inner_text(".codetxt .ln").startswith("1"),
223 "line numbers start at 1 @%dx%d %s" % (w, h, theme))
224 ok("line three" in page.inner_text(".codetxt .tx"),
225 "text body rendered @%dx%d %s" % (w, h, theme))
226
227 # binary file degrades to a note, never to mojibake
228 page.evaluate(
229 "Array.from(document.querySelectorAll('.row'))"
230 ".filter(function(b){return b.textContent.indexOf('blob.bin')>=0;})[0]"
231 ".click()")
232 page.wait_for_selector(".note", timeout=8000)
233 ok("Binary file" in page.inner_text(".note"),
234 "binary file explained @%dx%d %s" % (w, h, theme))
235
236 # image opens in an <img>
237 page.evaluate(
238 "Array.from(document.querySelectorAll('.row.dir'))"
239 ".filter(function(b){return b.textContent.indexOf('docs')>=0;})[0]"
240 ".click()")
241 page.wait_for_function(
242 "Array.from(document.querySelectorAll('.row'))"
243 ".some(function(b){return b.textContent.indexOf('pixel.png')>=0;})",
244 timeout=8000)
245 page.evaluate(
246 "Array.from(document.querySelectorAll('.row'))"
247 ".filter(function(b){return b.textContent.indexOf('pixel.png')>=0;})[0]"
248 ".click()")
249 page.wait_for_selector(".imgwrap img", timeout=8000)
250 ok(page.evaluate(
251 "document.querySelector('.imgwrap img').naturalWidth > 0"),
252 "image decoded @%dx%d %s" % (w, h, theme))
253
254 # hidden toggle reveals the dotfile
255 # the sidebar is hidden on a phone while a preview is open,
256 # so drive the toggle the way a user would after Back
257 page.evaluate("document.getElementById('btnHidden').click()")
258 page.wait_for_function(
259 "Array.from(document.querySelectorAll('.row'))"
260 ".some(function(b){return b.textContent.indexOf('pixel.png')>=0;})",
261 timeout=8000)
262 ok(page.evaluate(
263 "document.documentElement.scrollWidth <= window.innerWidth + 1"),
264 "no h-overflow after toggle @%dx%d %s" % (w, h, theme))
265
266 # put the toggle back so the README shot is the default view
267 page.evaluate("document.getElementById('btnHidden').click()")
268 page.wait_for_function(
269 "!Array.from(document.querySelectorAll('.row'))"
270 ".some(function(b){return b.textContent.indexOf('.hiddenrc')>=0;})",
271 timeout=8000)
272
273 # screenshot of the browser with a markdown preview open
274 page.evaluate(
275 "Array.from(document.querySelectorAll('.crumb'))[0].click()")
276 page.wait_for_function(
277 "Array.from(document.querySelectorAll('.row'))"
278 ".some(function(b){return b.textContent.indexOf('README.md')>=0;})",
279 timeout=8000)
280 page.evaluate(
281 "Array.from(document.querySelectorAll('.row'))"
282 ".filter(function(b){return b.textContent.indexOf('README.md')>=0;})[0]"
283 ".click()")
284 page.wait_for_selector(".md h1", timeout=8000)
285 page.evaluate("document.querySelector('.prev-body').scrollTop = 0")
286 shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme))
287 page.screenshot(path=shot)
288
289 ok(len(errors) == 0, "no console/page errors @%dx%d %s (%s)"
290 % (w, h, theme, "; ".join(errors[:2])))
291 page.close()
292
293 # embed mode hides the theme toggle
294 page = browser.new_page(viewport={"width": 1024, "height": 768})
295 page.goto(base + "?embed=1&theme=dark", wait_until="load")
296 page.wait_for_selector(".root", timeout=8000)
297 ok(not page.is_visible("#btnTheme"), "embed hides the theme toggle")
298 ok(page.evaluate(
299 "document.documentElement.classList.contains('embedded')"),
300 "embed marks html.embedded")
301 page.close()
302 browser.close()
303 finally:
304 httpd.shutdown()
305 shutil.rmtree(work, ignore_errors=True)
306
307 print("\n%d checks, %d failure(s)" % (checks, len(failures)))
308 if failures:
309 for f in failures:
310 print(" - %s" % f)
311 return 1
312 print("RESULT: OK")
313 return 0
314
315
316if __name__ == "__main__":
317 sys.exit(main())