scorpiox-bot-plugin-websearch
←mockapi.pypython
261 lines · 9 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/mockapi.py - a loopback mock of all six search backends.
3
4One process serves every provider at its own path prefix, so the plugin's real
5request builders are exercised end to end:
6
7 POST /duckduckgo/html/ an HTML result page
8 GET /searxng/search?q=... {"results":[...]}
9 GET /brave/res/v1/web/search {"web":{"results":[...]}}
10 POST /tavily/search {"answer":...,"results":[...]}
11 POST /exa/search {"results":[...]}
12 POST /perplexity/search {"results":[...]}
13
14Every request is appended to `--log` as one JSON line *before* the reply is
15written, recording method, path, query, the credential header and the parsed
16body. The suite compares that record against what each provider's request
17should have been — a reply-only assertion cannot see a wrong path, a dropped
18query parameter or a missing key.
19
20The mock also implements the failure paths a real provider has: a wrong key is
21401 with the provider's own error text, `?fail=500` is a 500, and
22`/duckduckgo/challenge/html/` returns DuckDuckGo's bot-detection page.
23
24Usage: python3 tests/mockapi.py --port 0 --portfile /tmp/p --log /tmp/log.jsonl
25"""
26
27import argparse
28import json
29import os
30import sys
31import threading
32from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
33from urllib.parse import urlparse, parse_qs
34
35LOCK = threading.Lock()
36
37# The credentials the mock accepts. Deliberately not real-looking: a suite that
38# uses plausible key text ends up shipping it in a screenshot one day.
39GOOD = {
40 "brave": "BRV-TEST-KEY-1",
41 "tavily": "TVL-TEST-KEY-1",
42 "exa": "EXA-TEST-KEY-1",
43 "perplexity": "PPX-TEST-KEY-1",
44}
45
46CHALLENGE_HTML = """<!DOCTYPE html><html><head><title>DuckDuckGo</title></head>
47<body><div id="anomaly-modal"><h1>Unfortunately, bots use DuckDuckGo too.</h1>
48<form id="challenge-form" action="/anomaly.js"></form>
49<div class="g-recaptcha"></div></div></body></html>
50"""
51
52
53def ddg_page(n=3, q="mocked query"):
54 rows = []
55 for i in range(n):
56 # Alternate the two link shapes DuckDuckGo really emits: a direct href
57 # and the /l/?uddg=<percent-encoded> redirect wrapper.
58 if i % 2 == 0:
59 href = "https://example%d.test/page%d" % (i, i)
60 else:
61 href = ("/l/?uddg=https%%3A%%2F%%2Fexample%d.test%%2Fpage%d"
62 "&rut=abc" % (i, i))
63 rows.append(
64 '<div class="result results_links web-result">'
65 '<h2 class="result__title">'
66 '<a rel="nofollow" class="result__a" href="%s">Result &amp; %d '
67 '<b>%s</b></a></h2>'
68 '<a class="result__snippet" href="%s">Snippet %d for &quot;%s&quot; '
69 '&mdash; with <b>highlighted</b> words.</a>'
70 '</div>' % (href, i, q, href, i, q))
71 return ("<!DOCTYPE html><html><head><title>%s at DuckDuckGo</title></head>"
72 "<body><div class=\"results\">%s</div></body></html>"
73 % (q, "".join(rows)))
74
75
76class Handler(BaseHTTPRequestHandler):
77 protocol_version = "HTTP/1.1"
78 log_path = None
79
80 def log_message(self, *a): # silence stderr noise
81 pass
82
83 def _record(self, method, path, query, body_bytes, cred):
84 entry = {
85 "method": method,
86 "path": path,
87 "query": query,
88 "cred": cred,
89 "body": None,
90 "length": len(body_bytes or b""),
91 }
92 if body_bytes:
93 try:
94 entry["body"] = json.loads(body_bytes.decode("utf-8", "replace"))
95 except Exception:
96 entry["body"] = body_bytes.decode("utf-8", "replace")
97 if self.log_path:
98 with LOCK:
99 with open(self.log_path, "a", encoding="utf-8") as f:
100 f.write(json.dumps(entry) + "\n")
101
102 def _send(self, code, body, ctype="application/json"):
103 raw = body.encode("utf-8") if isinstance(body, str) else body
104 self.send_response(code)
105 self.send_header("Content-Type", ctype + "; charset=utf-8")
106 self.send_header("Content-Length", str(len(raw)))
107 self.send_header("Connection", "close")
108 self.end_headers()
109 self.wfile.write(raw)
110
111 def _err(self, code, provider, msg):
112 self._send(code, json.dumps({"error": {"message": msg},
113 "message": msg}))
114
115 def do_GET(self):
116 u = urlparse(self.path)
117 q = parse_qs(u.query)
118 cred = (self.headers.get("X-Subscription-Token")
119 or self.headers.get("x-api-key")
120 or self.headers.get("Authorization") or "")
121 self._record("GET", u.path, {k: v[0] for k, v in q.items()}, b"", cred)
122
123 if q.get("fail", [""])[0] == "500":
124 self._err(500, "mock", "synthetic upstream failure")
125 return
126
127 if u.path == "/duckduckgo/html/":
128 # A GET is what a real DuckDuckGo answers with a challenge; the
129 # plugin must POST, so reaching this branch at all is a bug and the
130 # suite asserts the recorded method.
131 self._send(200, CHALLENGE_HTML, "text/html")
132 return
133 if u.path == "/duckduckgo/challenge/html/":
134 self._send(200, CHALLENGE_HTML, "text/html")
135 return
136
137 if u.path == "/searxng/search":
138 if q.get("format", [""])[0] != "json":
139 self._err(403, "searxng", "format=json is not enabled")
140 return
141 n = 3
142 self._send(200, json.dumps({"results": [
143 {"title": "SearX %d" % i,
144 "url": "https://sx%d.test/a" % i,
145 "content": "self-hosted snippet %d" % i,
146 "publishedDate": "2026-01-0%d" % (i + 1)}
147 for i in range(n)]}))
148 return
149
150 if u.path == "/brave/res/v1/web/search":
151 if cred != GOOD["brave"]:
152 self._err(401, "brave", "invalid subscription token")
153 return
154 if float(q.get("count", ["5"])[0]) < 1:
155 self._err(422, "brave", "count must be positive")
156 return
157 self._send(200, json.dumps({"web": {"results": [
158 {"title": "Brave %d" % i,
159 "url": "https://br%d.test/x" % i,
160 "description": "brave snippet %d" % i,
161 "age": "%d days ago" % (i + 1)}
162 for i in range(3)]}}))
163 return
164
165 self._err(404, "mock", "no route for %s" % u.path)
166
167 def do_POST(self):
168 u = urlparse(self.path)
169 q = parse_qs(u.query)
170 n = int(self.headers.get("Content-Length") or 0)
171 raw = self.rfile.read(n) if n > 0 else b""
172 cred = (self.headers.get("x-api-key")
173 or self.headers.get("Authorization")
174 or self.headers.get("X-Subscription-Token") or "")
175 self._record("POST", u.path, {k: v[0] for k, v in q.items()}, raw, cred)
176
177 if q.get("fail", [""])[0] == "500":
178 self._err(500, "mock", "synthetic upstream failure")
179 return
180
181 if u.path == "/duckduckgo/html/":
182 if "q=" not in raw.decode("utf-8", "replace"):
183 self._send(400, CHALLENGE_HTML, "text/html")
184 return
185 self._send(200, ddg_page(3, "rust lang"), "text/html")
186 return
187
188 if u.path == "/tavily/search":
189 if not cred.endswith(GOOD["tavily"]):
190 self._err(401, "tavily", "unauthorized: bad api key")
191 return
192 body = json.loads(raw or b"{}")
193 if not body.get("query"):
194 self._err(400, "tavily", "query is required")
195 return
196 out = {"results": [
197 {"title": "Tavily %d" % i,
198 "url": "https://tv%d.test/y" % i,
199 "content": "tavily content %d" % i,
200 "published_date": "2026-02-0%d" % (i + 1)}
201 for i in range(int(body.get("max_results", 5)))]}
202 if body.get("include_answer"):
203 out["answer"] = "A short synthesised answer."
204 self._send(200, json.dumps(out))
205 return
206
207 if u.path == "/exa/search":
208 if cred != GOOD["exa"]:
209 self._err(401, "exa", "invalid x-api-key")
210 return
211 body = json.loads(raw or b"{}")
212 self._send(200, json.dumps({"results": [
213 {"title": "Exa %d" % i,
214 "url": "https://ex%d.test/z" % i,
215 "publishedDate": "2026-03-0%d" % (i + 1),
216 "highlights": ["exa highlight %d" % i]}
217 for i in range(int(body.get("numResults", 5)))]}))
218 return
219
220 if u.path == "/perplexity/search":
221 if not cred.endswith(GOOD["perplexity"]):
222 self._err(401, "perplexity", "invalid api key")
223 return
224 body = json.loads(raw or b"{}")
225 self._send(200, json.dumps({"results": [
226 {"title": "Pplx %d" % i,
227 "url": "https://px%d.test/w" % i,
228 "snippet": "perplexity snippet %d" % i,
229 "date": "2026-04-0%d" % (i + 1)}
230 for i in range(int(body.get("max_results", 5)))]}))
231 return
232
233 self._err(404, "mock", "no route for %s" % u.path)
234
235
236def main():
237 ap = argparse.ArgumentParser()
238 ap.add_argument("--port", type=int, default=0)
239 ap.add_argument("--portfile")
240 ap.add_argument("--log")
241 a = ap.parse_args()
242
243 Handler.log_path = a.log
244 srv = ThreadingHTTPServer(("127.0.0.1", a.port), Handler)
245 srv.daemon_threads = True
246 port = srv.server_address[1]
247 if a.portfile:
248 tmp = a.portfile + ".tmp"
249 with open(tmp, "w") as f:
250 f.write(str(port))
251 os.replace(tmp, a.portfile)
252 sys.stderr.write("mockapi listening on 127.0.0.1:%d\n" % port)
253 sys.stderr.flush()
254 try:
255 srv.serve_forever()
256 except KeyboardInterrupt:
257 pass
258
259
260if __name__ == "__main__":
261 main()