| 1 |
From: Edward Betts <[email protected]> |
| 2 |
Date: Tue, 5 May 2026 14:51:10 +0100 |
| 3 |
Subject: Rewrite wire tests to use an in-process Python HTTP server instead |
| 4 |
of Docker and WireMock, |
| 5 |
allowing the tests to run during build and autopkgtest without requiring |
| 6 |
Docker. |
| 7 |
|
| 8 |
--- |
| 9 |
tests/conftest.py | 237 +++++++++++++++++++++++++++++++++++++----------------- |
| 10 |
1 file changed, 162 insertions(+), 75 deletions(-) |
| 11 |
|
| 12 |
diff --git a/tests/conftest.py b/tests/conftest.py |
| 13 |
index 4174fa9..dda7f05 100644 |
| 14 |
--- a/tests/conftest.py |
| 15 |
+++ b/tests/conftest.py |
| 16 |
@@ -1,16 +1,22 @@ |
| 17 |
""" |
| 18 |
|
| 19 |
+Pytest plugin that manages the mock server lifecycle for wire tests. |
| 20 |
|
| 21 |
This plugin is loaded globally for the test suite and is responsible for |
| 22 |
|
| 23 |
+starting and stopping the mock server exactly once per test run, |
| 24 |
including when running with pytest-xdist over the entire project. |
| 25 |
|
| 26 |
It lives under tests/ (as tests/conftest.py) and is discovered automatically |
| 27 |
by pytest's normal test collection rules. |
| 28 |
""" |
| 29 |
|
| 30 |
+import json |
| 31 |
import os |
| 32 |
|
| 33 |
+import re |
| 34 |
+import threading |
| 35 |
+from http.server import BaseHTTPRequestHandler, HTTPServer |
| 36 |
+from socketserver import ThreadingMixIn |
| 37 |
+from typing import Any |
| 38 |
+from urllib.parse import parse_qs, urlparse |
| 39 |
|
| 40 |
import pytest |
| 41 |
|
| 42 |
@@ -21,70 +27,132 @@ _PROJECT_NAME: str = "auth0-api" |
| 43 |
|
| 44 |
# This file lives at tests/conftest.py, so the project root is one level up. |
| 45 |
_PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
+_MAPPINGS_FILE = os.path.join(_PROJECT_ROOT, "wiremock", "wiremock-mappings.json") |
| 111 |
+ |
| 112 |
+_server: "ThreadedHTTPServer | None" = None |
| 113 |
+_server_thread: "threading.Thread | None" = None |
| 114 |
+_recorded_requests: "list[dict[str, Any]]" = [] |
| 115 |
+_lock = threading.Lock() |
| 116 |
+_routes: "list[dict[str, Any]]" = [] |
| 117 |
+ |
| 118 |
+ |
| 119 |
+class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): |
| 120 |
+ daemon_threads = True |
| 121 |
+ |
| 122 |
+ |
| 123 |
+def _template_to_regex(template: str) -> "re.Pattern[str]": |
| 124 |
+ parts = re.split(r"(\{[^}]+\})", template) |
| 125 |
+ regex = "^" + "".join("[^/]+" if p.startswith("{") else re.escape(p) for p in parts) + "$" |
| 126 |
+ return re.compile(regex) |
| 127 |
+ |
| 128 |
+ |
| 129 |
+def _load_routes() -> "list[dict[str, Any]]": |
| 130 |
+ with open(_MAPPINGS_FILE) as f: |
| 131 |
+ data = json.load(f) |
| 132 |
+ routes = [] |
| 133 |
+ for mapping in data.get("mappings", []): |
| 134 |
+ req = mapping.get("request", {}) |
| 135 |
+ resp = mapping.get("response", {}) |
| 136 |
+ template = req.get("urlPathTemplate") or req.get("urlPath", "") |
| 137 |
+ json_body = resp.get("jsonBody") |
| 138 |
+ if json_body is not None: |
| 139 |
+ body = json.dumps(json_body).encode() |
| 140 |
+ else: |
| 141 |
+ raw = resp.get("body", "") |
| 142 |
+ body = raw.encode() if isinstance(raw, str) else b"{}" |
| 143 |
+ routes.append({ |
| 144 |
+ "method": req.get("method", "ANY"), |
| 145 |
+ "pattern": _template_to_regex(template), |
| 146 |
+ "status": resp.get("status", 200), |
| 147 |
+ "body": body, |
| 148 |
+ "headers": resp.get("headers", {}), |
| 149 |
+ }) |
| 150 |
+ return routes |
| 151 |
+ |
| 152 |
+ |
| 153 |
+class _MockHandler(BaseHTTPRequestHandler): |
| 154 |
+ def _read_body(self) -> bytes: |
| 155 |
+ length = int(self.headers.get("Content-Length", 0)) |
| 156 |
+ return self.rfile.read(length) if length else b"" |
| 157 |
+ |
| 158 |
+ def _send_response(self, status: int, body: bytes, headers: "dict[str, str]") -> None: |
| 159 |
+ self.send_response(status) |
| 160 |
+ content_type = headers.get("Content-Type", "application/json") |
| 161 |
+ self.send_header("Content-Type", content_type) |
| 162 |
+ self.send_header("Content-Length", str(len(body))) |
| 163 |
+ for key, value in headers.items(): |
| 164 |
+ if key != "Content-Type": |
| 165 |
+ self.send_header(key, value) |
| 166 |
+ self.end_headers() |
| 167 |
+ self.wfile.write(body) |
| 168 |
+ |
| 169 |
+ def do_POST(self) -> None: |
| 170 |
+ if urlparse(self.path).path == "/__admin/requests/find": |
| 171 |
+ self._admin_find() |
| 172 |
+ else: |
| 173 |
+ self._record_and_respond() |
| 174 |
+ |
| 175 |
+ def do_GET(self) -> None: |
| 176 |
+ self._record_and_respond() |
| 177 |
+ |
| 178 |
+ def do_PUT(self) -> None: |
| 179 |
+ self._record_and_respond() |
| 180 |
+ |
| 181 |
+ def do_PATCH(self) -> None: |
| 182 |
+ self._record_and_respond() |
| 183 |
+ |
| 184 |
+ def do_DELETE(self) -> None: |
| 185 |
+ self._record_and_respond() |
| 186 |
+ |
| 187 |
+ def _admin_find(self) -> None: |
| 188 |
+ criteria = json.loads(self._read_body() or b"{}") |
| 189 |
+ method = criteria.get("method", "") |
| 190 |
+ url_path = criteria.get("urlPath", "") |
| 191 |
+ header_criteria = criteria.get("headers", {}) |
| 192 |
+ query_criteria = criteria.get("queryParameters", {}) |
| 193 |
+ |
| 194 |
+ with _lock: |
| 195 |
+ matching = [ |
| 196 |
+ r for r in _recorded_requests |
| 197 |
+ if r["method"] == method |
| 198 |
+ and r["path"] == url_path |
| 199 |
+ and all( |
| 200 |
+ r["headers"].get(h.lower()) == spec.get("equalTo") |
| 201 |
+ for h, spec in header_criteria.items() |
| 202 |
+ ) |
| 203 |
+ and all( |
| 204 |
+ r["query_params"].get(q) == spec.get("equalTo") |
| 205 |
+ for q, spec in query_criteria.items() |
| 206 |
+ ) |
| 207 |
+ ] |
| 208 |
+ |
| 209 |
+ self._send_response(200, json.dumps({"requests": matching}).encode(), {}) |
| 210 |
+ |
| 211 |
+ def _record_and_respond(self) -> None: |
| 212 |
+ self._read_body() # consume to keep connection clean |
| 213 |
+ parsed = urlparse(self.path) |
| 214 |
+ path = parsed.path |
| 215 |
+ query_params = {k: v[0] for k, v in parse_qs(parsed.query).items()} |
| 216 |
+ headers_lc = {k.lower(): v for k, v in self.headers.items()} |
| 217 |
+ |
| 218 |
+ with _lock: |
| 219 |
+ _recorded_requests.append({ |
| 220 |
+ "method": self.command, |
| 221 |
+ "path": path, |
| 222 |
+ "query_params": query_params, |
| 223 |
+ "headers": headers_lc, |
| 224 |
+ }) |
| 225 |
+ |
| 226 |
+ status, body, resp_headers = 200, b"{}", {} |
| 227 |
+ for route in _routes: |
| 228 |
+ if route["method"] in (self.command, "ANY") and route["pattern"].match(path): |
| 229 |
+ status, body, resp_headers = route["status"], route["body"], route["headers"] |
| 230 |
+ break |
| 231 |
+ |
| 232 |
+ self._send_response(status, body, resp_headers) |
| 233 |
+ |
| 234 |
+ def log_message(self, format: str, *args: Any) -> None: |
| 235 |
+ pass # suppress per-request log noise |
| 236 |
|
| 237 |
|
| 238 |
def _is_xdist_worker(config: pytest.Config) -> bool: |
| 239 |
@@ -121,27 +189,46 @@ def pytest_configure(config: pytest.Config) -> None: |
| 240 |
""" |
| 241 |
Pytest hook that runs during test session setup. |
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
+ Starts the mock server only from the controller process (xdist) |
| 246 |
+ or the single process (non-xdist). This ensures only one server |
| 247 |
is started regardless of the number of worker processes. |
| 248 |
""" |
| 249 |
+ global _server, _server_thread, _routes, _recorded_requests |
| 250 |
if _is_xdist_worker(config): |
| 251 |
|
| 252 |
+ # Workers never manage the server lifecycle. |
| 253 |
return |
| 254 |
|
| 255 |
|
| 256 |
+ _routes = _load_routes() |
| 257 |
+ _recorded_requests = [] |
| 258 |
+ _server = ThreadedHTTPServer(("127.0.0.1", 0), _MockHandler) |
| 259 |
+ port = str(_server.server_address[1]) |
| 260 |
+ os.environ["WIREMOCK_PORT"] = port |
| 261 |
+ os.environ["WIREMOCK_URL"] = f"http://127.0.0.1:{port}" |
| 262 |
+ for var in ("no_proxy", "NO_PROXY"): |
| 263 |
+ existing = os.environ.get(var, "") |
| 264 |
+ if "127.0.0.1" not in existing: |
| 265 |
+ os.environ[var] = f"{existing},127.0.0.1" if existing else "127.0.0.1" |
| 266 |
+ _server_thread = threading.Thread(target=_server.serve_forever, daemon=True) |
| 267 |
+ _server_thread.start() |
| 268 |
+ print(f"\nMock HTTP server started on port {port}") |
| 269 |
|
| 270 |
|
| 271 |
def pytest_unconfigure(config: pytest.Config) -> None: |
| 272 |
""" |
| 273 |
Pytest hook that runs during test session teardown. |
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
+ Stops the mock server only from the controller process (xdist) |
| 278 |
+ or the single process (non-xdist). This ensures the server is |
| 279 |
cleaned up after all workers have finished. |
| 280 |
""" |
| 281 |
+ global _server, _server_thread |
| 282 |
if _is_xdist_worker(config): |
| 283 |
|
| 284 |
+ # Workers never manage the server lifecycle. |
| 285 |
return |
| 286 |
|
| 287 |
|
| 288 |
+ if _server: |
| 289 |
+ _server.shutdown() |
| 290 |
+ _server = None |
| 291 |
+ if _server_thread: |
| 292 |
+ _server_thread.join(timeout=5) |
| 293 |
+ _server_thread = None |