#!/usr/bin/env python3
"""tests/mockapi.py - a loopback mock of all six search backends.
One process serves every provider at its own path prefix, so the plugin's real
request builders are exercised end to end:
POST /duckduckgo/html/ an HTML result page
GET /searxng/search?q=... {"results":[...]}
GET /brave/res/v1/web/search {"web":{"results":[...]}}
POST /tavily/search {"answer":...,"results":[...]}
POST /exa/search {"results":[...]}
POST /perplexity/search {"results":[...]}
Every request is appended to `--log` as one JSON line *before* the reply is
written, recording method, path, query, the credential header and the parsed
body. The suite compares that record against what each provider's request
should have been — a reply-only assertion cannot see a wrong path, a dropped
query parameter or a missing key.
The mock also implements the failure paths a real provider has: a wrong key is
401 with the provider's own error text, `?fail=500` is a 500, and
`/duckduckgo/challenge/html/` returns DuckDuckGo's bot-detection page.
Usage: python3 tests/mockapi.py --port 0 --portfile /tmp/p --log /tmp/log.jsonl
"""
import argparse
import json
import os
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs
LOCK = threading.Lock()
# The credentials the mock accepts. Deliberately not real-looking: a suite that
# uses plausible key text ends up shipping it in a screenshot one day.
GOOD = {
"brave": "BRV-TEST-KEY-1",
"tavily": "TVL-TEST-KEY-1",
"exa": "EXA-TEST-KEY-1",
"perplexity": "PPX-TEST-KEY-1",
}
CHALLENGE_HTML = """
DuckDuckGo
Unfortunately, bots use DuckDuckGo too.
"""
def ddg_page(n=3, q="mocked query"):
rows = []
for i in range(n):
# Alternate the two link shapes DuckDuckGo really emits: a direct href
# and the /l/?uddg= redirect wrapper.
if i % 2 == 0:
href = "https://example%d.test/page%d" % (i, i)
else:
href = ("/l/?uddg=https%%3A%%2F%%2Fexample%d.test%%2Fpage%d"
"&rut=abc" % (i, i))
rows.append(
'' % (href, i, q, href, i, q))
return ("%s at DuckDuckGo"
"%s
"
% (q, "".join(rows)))
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
log_path = None
def log_message(self, *a): # silence stderr noise
pass
def _record(self, method, path, query, body_bytes, cred):
entry = {
"method": method,
"path": path,
"query": query,
"cred": cred,
"body": None,
"length": len(body_bytes or b""),
}
if body_bytes:
try:
entry["body"] = json.loads(body_bytes.decode("utf-8", "replace"))
except Exception:
entry["body"] = body_bytes.decode("utf-8", "replace")
if self.log_path:
with LOCK:
with open(self.log_path, "a", encoding="utf-8") as f:
f.write(json.dumps(entry) + "\n")
def _send(self, code, body, ctype="application/json"):
raw = body.encode("utf-8") if isinstance(body, str) else body
self.send_response(code)
self.send_header("Content-Type", ctype + "; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Connection", "close")
self.end_headers()
self.wfile.write(raw)
def _err(self, code, provider, msg):
self._send(code, json.dumps({"error": {"message": msg},
"message": msg}))
def do_GET(self):
u = urlparse(self.path)
q = parse_qs(u.query)
cred = (self.headers.get("X-Subscription-Token")
or self.headers.get("x-api-key")
or self.headers.get("Authorization") or "")
self._record("GET", u.path, {k: v[0] for k, v in q.items()}, b"", cred)
if q.get("fail", [""])[0] == "500":
self._err(500, "mock", "synthetic upstream failure")
return
if u.path == "/duckduckgo/html/":
# A GET is what a real DuckDuckGo answers with a challenge; the
# plugin must POST, so reaching this branch at all is a bug and the
# suite asserts the recorded method.
self._send(200, CHALLENGE_HTML, "text/html")
return
if u.path == "/duckduckgo/challenge/html/":
self._send(200, CHALLENGE_HTML, "text/html")
return
if u.path == "/searxng/search":
if q.get("format", [""])[0] != "json":
self._err(403, "searxng", "format=json is not enabled")
return
n = 3
self._send(200, json.dumps({"results": [
{"title": "SearX %d" % i,
"url": "https://sx%d.test/a" % i,
"content": "self-hosted snippet %d" % i,
"publishedDate": "2026-01-0%d" % (i + 1)}
for i in range(n)]}))
return
if u.path == "/brave/res/v1/web/search":
if cred != GOOD["brave"]:
self._err(401, "brave", "invalid subscription token")
return
if float(q.get("count", ["5"])[0]) < 1:
self._err(422, "brave", "count must be positive")
return
self._send(200, json.dumps({"web": {"results": [
{"title": "Brave %d" % i,
"url": "https://br%d.test/x" % i,
"description": "brave snippet %d" % i,
"age": "%d days ago" % (i + 1)}
for i in range(3)]}}))
return
self._err(404, "mock", "no route for %s" % u.path)
def do_POST(self):
u = urlparse(self.path)
q = parse_qs(u.query)
n = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(n) if n > 0 else b""
cred = (self.headers.get("x-api-key")
or self.headers.get("Authorization")
or self.headers.get("X-Subscription-Token") or "")
self._record("POST", u.path, {k: v[0] for k, v in q.items()}, raw, cred)
if q.get("fail", [""])[0] == "500":
self._err(500, "mock", "synthetic upstream failure")
return
if u.path == "/duckduckgo/html/":
if "q=" not in raw.decode("utf-8", "replace"):
self._send(400, CHALLENGE_HTML, "text/html")
return
self._send(200, ddg_page(3, "rust lang"), "text/html")
return
if u.path == "/tavily/search":
if not cred.endswith(GOOD["tavily"]):
self._err(401, "tavily", "unauthorized: bad api key")
return
body = json.loads(raw or b"{}")
if not body.get("query"):
self._err(400, "tavily", "query is required")
return
out = {"results": [
{"title": "Tavily %d" % i,
"url": "https://tv%d.test/y" % i,
"content": "tavily content %d" % i,
"published_date": "2026-02-0%d" % (i + 1)}
for i in range(int(body.get("max_results", 5)))]}
if body.get("include_answer"):
out["answer"] = "A short synthesised answer."
self._send(200, json.dumps(out))
return
if u.path == "/exa/search":
if cred != GOOD["exa"]:
self._err(401, "exa", "invalid x-api-key")
return
body = json.loads(raw or b"{}")
self._send(200, json.dumps({"results": [
{"title": "Exa %d" % i,
"url": "https://ex%d.test/z" % i,
"publishedDate": "2026-03-0%d" % (i + 1),
"highlights": ["exa highlight %d" % i]}
for i in range(int(body.get("numResults", 5)))]}))
return
if u.path == "/perplexity/search":
if not cred.endswith(GOOD["perplexity"]):
self._err(401, "perplexity", "invalid api key")
return
body = json.loads(raw or b"{}")
self._send(200, json.dumps({"results": [
{"title": "Pplx %d" % i,
"url": "https://px%d.test/w" % i,
"snippet": "perplexity snippet %d" % i,
"date": "2026-04-0%d" % (i + 1)}
for i in range(int(body.get("max_results", 5)))]}))
return
self._err(404, "mock", "no route for %s" % u.path)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=0)
ap.add_argument("--portfile")
ap.add_argument("--log")
a = ap.parse_args()
Handler.log_path = a.log
srv = ThreadingHTTPServer(("127.0.0.1", a.port), Handler)
srv.daemon_threads = True
port = srv.server_address[1]
if a.portfile:
tmp = a.portfile + ".tmp"
with open(tmp, "w") as f:
f.write(str(port))
os.replace(tmp, a.portfile)
sys.stderr.write("mockapi listening on 127.0.0.1:%d\n" % port)
sys.stderr.flush()
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()