#!/usr/bin/env python3 """tests/mockd.py - the throwaway server for the plugin_fetch offline suite. One process, one family of loopback listeners, deterministic fixtures, and nothing but the Python 3 standard library. Everything binds 127.0.0.1, and the suite reaches it only through the plugin's explicit test-only private-address allowance (FETCH_ALLOW_PRIVATE / the policy toggle). python3 tests/mockd.py http python3 tests/mockd.py https and the ready line "READY " lands on stdout so the runner can wait for it. Routes (GET, POST and HEAD all answer the same way): /article 200 text/html - the big fixture: headings h1..h6, links (absolute, relative, query), nested lists, fenced code, inline code, blockquote, table, image, hr, entities (named, decimal, hex), and the boilerplate that must be stripped: script, style, noscript, svg, nav, aside, header, form, footer, plus a that must vanish. /title 200 text/html - differs from <h1> (notice vs heading) /plain 200 text/plain - "plain text body" (cannot be simplified) /md 200 text/markdown - returned verbatim, no notice /noctype 200, no Content-Type at all, body opens "<!DOCTYPE html" (sniffed as HTML) /noctype-text 200, no Content-Type, plain body (not sniffed as HTML) /json 200 application/json /big 200 text/html - 400 deterministic paragraphs (pagination) /long 200 text/plain - 200000 'x' characters (chunk truncation) /chunked 200 text/html, Transfer-Encoding: chunked (the article) /gzip 200 text/html, Content-Encoding: gzip (only decoded when the plugin was built with HAVE_ZLIB; otherwise it must refuse) /noclen 200 text/plain, no Content-Length, Connection: close /headonly 200 with Content-Length larger than the read cap (must be refused without reading the body) /r1 -> /r2 -> /article 2-hop redirect chain (302 then 301) /rel 302 -> "relative" (relative Location, no leading slash) /relative 200 text/html /loop 302 -> /loop (redirect loop -> hop cap) /selfloop 302 -> absolute self URL (loop with absolute Location) /privatehop 302 -> http://127.0.0.1:<port>/plain (hop to a denied IP) /badtarget 302 -> an absolute URL with a bogus scheme /404 /403 /500 error pages /slow sleeps 25 s then 200 (read deadline path) /echo 200 application/json with the request headers we care about (User-Agent, Accept-Encoding, Host) so the request shape can be asserted HTTPS mode wraps the same routes in TLS 1.2+ with a self-signed certificate, so the plugin must refuse it with no trust anchors and accept it when FETCH_TLS_CA_FILE points at the matching PEM. """ import gzip import http.server import json import ssl import sys import time HTML = """<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Widget & Gadget \u2014 Docs SHOULD_NOT_APPEAR_svg

Widgets and Gadgets

Installation

Run make install & then restart the service. Prices start at 5 USD — half is 1/2 <3> & 75%.

Steps

  1. one
  2. two
  3. three

Fourth

Fifth
Sixth
int main(void) {
    return 0;
}
Quoted text second line
NameValue
a1
Logo

Entities: © 2026 •café — ✓ AB

external and hrefless

SHOULD_NOT_APPEAR_footer
""" HTML_TITLE = """TITLE_IS_HERE

H1_IS_DIFFERENT

body text under the heading

""" RELATIVE_OK = "

relative ok

reached /relative

" NOT_FOUND = "gone" class H(http.server.BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, *a): pass def _send(self, code, ctype, body, extra=None): if isinstance(body, str): body = body.encode("utf-8") self.send_response(code) if ctype: self.send_header("Content-Type", ctype) for k, v in (extra or {}).items(): self.send_header(k, v) self.send_header("Content-Length", str(len(body))) self.end_headers() if self.command != "HEAD": self.wfile.write(body) def _redirect(self, loc): self.send_response(302) self.send_header("Location", loc) self.send_header("Content-Length", "0") self.end_headers() def _base(self): return "http://%s" % self.headers.get("Host", "127.0.0.1") def do_GET(self): p = self.path.split("?")[0] port = self.server.server_address[1] if p in ("/", "/article"): self._send(200, "text/html; charset=utf-8", HTML) elif p == "/title": self._send(200, "text/html; charset=utf-8", HTML_TITLE) elif p == "/plain": self._send(200, "text/plain; charset=utf-8", "plain text body") elif p == "/md": self._send(200, "text/markdown; charset=utf-8", "# MD body\n\ntext stays as-is") elif p == "/noctype": self._send(200, None, "

sniffed

as html

") elif p == "/noctype-text": self._send(200, None, "just some text with no declared type") elif p == "/json": self._send(200, "application/json", json.dumps({"hello": "world"})) elif p == "/big": rows = ["

Big Page

"] for i in range(400): rows.append("

Paragraph number %03d with enough filler words " "to make the document long enough to paginate." % i) rows.append("") self._send(200, "text/html; charset=utf-8", "\n".join(rows)) elif p == "/long": self._send(200, "text/plain; charset=utf-8", "x" * 200000) elif p == "/chunked": body = HTML.encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Transfer-Encoding", "chunked") self.end_headers() for i in range(0, len(body), 111): part = body[i:i + 111] self.wfile.write(("%x\r\n" % len(part)).encode() + part + b"\r\n") self.wfile.write(b"0\r\n\r\n") elif p == "/gzip": raw = HTML.encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Encoding", "gzip") self.send_header("Content-Length", str(len(gzip.compress(raw)))) self.end_headers() self.wfile.write(gzip.compress(raw)) elif p == "/noclen": self.send_response(200) self.send_header("Content-Type", "text/plain; charset=utf-8") self.send_header("Connection", "close") self.end_headers() self.wfile.write(b"no-content-length-body") self.close_connection = True elif p == "/headonly": self.send_response(200) self.send_header("Content-Type", "text/plain; charset=utf-8") self.send_header("Content-Length", str(5 * 1024 * 1024 + 7)) self.end_headers() elif p == "/r1": self._redirect("/r2") elif p == "/r2": self.send_response(301) self.send_header("Location", "/article") self.send_header("Content-Length", "0") self.end_headers() elif p == "/rel": self._redirect("relative") elif p == "/relative": self._send(200, "text/html", RELATIVE_OK) elif p == "/loop": self._redirect("/loop") elif p == "/selfloop": self._redirect(self._base() + "/selfloop") elif p == "/privatehop": self._redirect("http://127.0.0.1:%d/plain" % port) elif p == "/badtarget": self._redirect("ftp://example.invalid/nope") elif p == "/404": self._send(404, "text/html", NOT_FOUND) elif p == "/403": self._send(403, "text/html", "403 forbidden") elif p == "/500": self._send(500, "text/html", "500 boom") elif p == "/slow": # longer than the plugin read deadline (FX_READ_MS = 15 s) time.sleep(25) self._send(200, "text/plain", "too late") elif p == "/echo": self._send(200, "application/json", json.dumps({ "path": p, "host": self.headers.get("Host"), "ua": self.headers.get("User-Agent"), "accept_encoding": self.headers.get("Accept-Encoding"), "connection": self.headers.get("Connection"), "accept": self.headers.get("Accept"), })) else: self._send(404, "text/plain", "not found") do_POST = do_GET do_HEAD = do_GET def main(): mode = sys.argv[1] port = int(sys.argv[2]) srv = http.server.ThreadingHTTPServer(("127.0.0.1", port), H) if mode == "https": ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.load_cert_chain(sys.argv[3], sys.argv[4]) try: ctx.minimum_version = ssl.TLSVersion.TLSv1_2 except Exception: pass srv.socket = ctx.wrap_socket(srv.socket, server_side=True) sys.stdout.write("READY %s %d\n" % (mode, port)) sys.stdout.flush() srv.serve_forever() if __name__ == "__main__": main()