scorpiox-bot-plugin-fetch
←e2e.pypython
257 lines · 10 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport + interaction checks for the plugin_fetch page.
3
4Serves the plugin through a small CGI-ish HTTP shim on a loopback port, starts
5tests/mockd.py so the page has something real to fetch, opens it with
6Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts:
7
8 * no console error and no page error at any viewport
9 * scrollWidth <= innerWidth (no horizontal overflow)
10 * the URL box, the fetch button, the tabs and the policy switch render
11 * a real fetch round-trip lands Markdown in the output pane
12 * the metadata strip fills in (status / type / bytes / content length)
13 * Next/Prev pagination walks a long document
14 * the Raw tab shows the untouched HTML
15 * the SSRF policy switch round-trips through the node API
16 * screenshots land in docs/ for the README
17
18Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays
19dependency-free.
20
21 python3 tests/e2e.py # run if Playwright is available
22 python3 tests/e2e.py --strict # exit 2 when Playwright is missing
23"""
24
25import argparse
26import http.server
27import os
28import socketserver
29import subprocess
30import sys
31import threading
32import time
33from urllib.parse import urlparse, quote
34
35ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
36BIN = os.path.join(ROOT, "plugin_fetch")
37DOCS = os.path.join(ROOT, "docs")
38VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
39THEMES = ["dark", "light"]
40PW = "e2e-node-password"
41MOCK_PORT = 18780
42MOCK = "http://127.0.0.1:%d" % MOCK_PORT
43
44
45class Handler(http.server.BaseHTTPRequestHandler):
46 conf_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["SX_CONNECTOR_DIR"] = self.conf_dir
56 env["BOT_PASSWORD"] = PW
57 env["CONTENT_LENGTH"] = str(len(body))
58 # the fixture listeners are loopback; the suite is the only reason
59 # the plugin ever agrees to talk to them
60 env["FETCH_ALLOW_PRIVATE"] = "1"
61 # forward the header the page sets, so the shim behaves like the node
62 if self.headers.get("X-Bot-Password"):
63 env["HTTP_X_BOT_PASSWORD"] = self.headers.get("X-Bot-Password")
64 out = subprocess.run([BIN], input=body, capture_output=True, env=env,
65 timeout=60).stdout
66 sep = out.find(b"\r\n\r\n")
67 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
68 payload = out[sep + 4:] if sep >= 0 else out
69 status = 200
70 ctype = "text/html; charset=utf-8"
71 for line in headers.splitlines():
72 low = line.lower()
73 if low.startswith("content-type:"):
74 ctype = line.split(":", 1)[1].strip()
75 elif low.startswith("status:"):
76 try:
77 status = int(line.split(":", 1)[1].strip().split()[0])
78 except (IndexError, ValueError):
79 status = 200
80 self.send_response(status)
81 self.send_header("Content-Type", ctype)
82 self.send_header("Cache-Control", "no-store")
83 self.send_header("Content-Length", str(len(payload)))
84 self.end_headers()
85 self.wfile.write(payload)
86
87 def do_GET(self): # noqa: N802
88 self._run("GET")
89
90 def do_POST(self): # noqa: N802
91 self._run("POST")
92
93 def log_message(self, *_a):
94 pass
95
96
97def main():
98 ap = argparse.ArgumentParser()
99 ap.add_argument("--strict", action="store_true",
100 help="exit 2 when Playwright is not installed")
101 args = ap.parse_args()
102
103 try:
104 from playwright.sync_api import sync_playwright
105 except Exception:
106 print("playwright not installed - skipping e2e (offline suite is unaffected)")
107 return 2 if args.strict else 0
108
109 if not os.path.exists(BIN):
110 print("plugin_fetch not built - run make first")
111 return 1
112
113 work = os.path.join("/tmp", "fetch-e2e-%d" % os.getpid())
114 conf = os.path.join(work, "conf")
115 os.makedirs(conf, exist_ok=True)
116
117 # the fixture server (plain HTTP only - the page never does TLS)
118 cert = os.path.join(work, "cert.pem")
119 key = os.path.join(work, "key.pem")
120 subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
121 "-days", "2", "-keyout", key, "-out", cert,
122 "-subj", "/CN=test.invalid"],
123 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
124 mock = subprocess.Popen([sys.executable, os.path.join(ROOT, "tests", "mockd.py"),
125 "http", str(MOCK_PORT)],
126 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
127 for _ in range(60):
128 try:
129 import urllib.request
130 with urllib.request.urlopen(MOCK + "/plain", timeout=1) as r:
131 if r.status == 200:
132 break
133 except Exception:
134 time.sleep(0.1)
135
136 Handler.conf_dir = conf
137 httpd = socketserver.ThreadingTCPServer(("127.0.0.1", 0), Handler)
138 httpd.allow_reuse_address = True
139 port = httpd.server_address[1]
140 threading.Thread(target=httpd.serve_forever, daemon=True).start()
141 base = "http://127.0.0.1:%d/?pwd=%s" % (port, quote(PW))
142
143 os.makedirs(DOCS, exist_ok=True)
144 failures = []
145 checks = 0
146
147 def ok(cond, label):
148 nonlocal checks
149 checks += 1
150 if not cond:
151 failures.append(label)
152 print(" FAIL %s" % label)
153
154 with sync_playwright() as p:
155 browser = p.chromium.launch()
156 for (w, h) in VIEWPORTS:
157 for theme in THEMES:
158 page = browser.new_page(viewport={"width": w, "height": h})
159 errors = []
160 page.on("console", lambda m: errors.append(m.text)
161 if m.type == "error" else None)
162 page.on("pageerror", lambda e: errors.append(str(e)))
163 page.goto(base + "&theme=" + theme, wait_until="load")
164 tag = "%dx%d-%s" % (w, h, theme)
165
166 ok(page.locator("#url").is_visible(), "%s: url box" % tag)
167 ok(page.locator("#go").is_visible(), "%s: fetch button" % tag)
168 ok(page.locator("#tabmd").is_visible(), "%s: markdown tab" % tag)
169 ok(page.locator("#tabraw").is_visible(), "%s: raw tab" % tag)
170 ok(page.locator("#allowpriv").is_visible(), "%s: policy switch" % tag)
171 ok(page.evaluate("document.documentElement.scrollWidth <= "
172 "document.documentElement.clientWidth + 1"),
173 "%s: no horizontal overflow" % tag)
174 ok(len(errors) == 0, "%s: no console errors (%s)"
175 % (tag, "; ".join(errors[:2])))
176
177 # a real round-trip through the CGI
178 page.fill("#url", MOCK + "/article")
179 page.fill("#maxlen", "400")
180 page.click("#go")
181 page.wait_for_selector("#meta", state="visible", timeout=15000)
182 out = page.inner_text("#out")
183 ok("Widgets and Gadgets" in out, "%s: markdown rendered" % tag)
184 ok("##" in out or "-" in out, "%s: structure preserved" % tag)
185 ok("SHOULD_NOT_APPEAR" not in out, "%s: boilerplate stripped" % tag)
186 ok(page.inner_text("#mStatus").strip() == "200",
187 "%s: status pill says 200" % tag)
188 ok(page.inner_text("#mType").startswith("text/html"),
189 "%s: content type shown" % tag)
190 ok(page.inner_text("#mBytes").strip().isdigit() and
191 int(page.inner_text("#mBytes")) > 0, "%s: bytes read shown" % tag)
192 ok(page.inner_text("#mLen").strip().isdigit(),
193 "%s: content length shown" % tag)
194
195 # pagination across the same document
196 page.fill("#url", MOCK + "/big")
197 page.fill("#maxlen", "1000")
198 page.fill("#start", "0")
199 page.click("#go")
200 page.wait_for_timeout(600)
201 first = page.inner_text("#out")
202 ok("Paragraph number 000" in first, "%s: first chunk" % tag)
203 if page.locator("#pager").is_visible():
204 page.click("#pager button:has-text('Next')")
205 page.wait_for_timeout(600)
206 second = page.inner_text("#out")
207 ok("Paragraph number 000" not in second or first != second,
208 "%s: next chunk differs" % tag)
209 ok(int(page.input_value("#start")) > 0,
210 "%s: start_index advanced" % tag)
211 page.click("#pager button:has-text('Prev')")
212 page.wait_for_timeout(600)
213 ok(page.input_value("#start") == "0", "%s: prev returned" % tag)
214 else:
215 ok(False, "%s: pager visible on a long document" % tag)
216
217 # the raw tab
218 page.fill("#url", MOCK + "/article")
219 page.click("#tabraw")
220 page.click("#go")
221 page.wait_for_timeout(700)
222 ok("<!DOCTYPE html>" in page.inner_text("#out"),
223 "%s: raw tab shows html" % tag)
224 page.click("#tabmd")
225
226 # the policy switch round-trips through the node API
227 page.click("#allowpriv", force=True)
228 page.wait_for_timeout(400)
229 page.reload(wait_until="load")
230 ok(page.locator("#allowpriv").is_checked(),
231 "%s: policy switch persisted" % tag)
232 page.click("#allowpriv", force=True)
233 page.wait_for_timeout(400)
234
235 # an error path stays readable
236 page.fill("#url", "ftp://example.invalid/x")
237 page.click("#go")
238 page.wait_for_timeout(600)
239 ok("scheme" in page.inner_text("#out").lower(),
240 "%s: refusal surfaced in the pane" % tag)
241
242 page.screenshot(path=os.path.join(
243 DOCS, "fetch-%s.png" % tag), full_page=False)
244 page.close()
245 browser.close()
246
247 httpd.shutdown()
248 mock.terminate()
249
250 print("%d checks, %d failures" % (checks, len(failures)))
251 for f in failures:
252 print(" - %s" % f)
253 return 1 if failures else 0
254
255
256if __name__ == "__main__":
257 sys.exit(main())