From: Edward Betts Date: Tue, 5 May 2026 14:51:10 +0100 Subject: Rewrite wire tests to use an in-process Python HTTP server instead of Docker and WireMock, allowing the tests to run during build and autopkgtest without requiring Docker. --- tests/conftest.py | 237 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 162 insertions(+), 75 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 4174fa9..dda7f05 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,16 +1,22 @@ """ -Pytest plugin that manages the WireMock container lifecycle for wire tests. +Pytest plugin that manages the mock server lifecycle for wire tests. This plugin is loaded globally for the test suite and is responsible for -starting and stopping the WireMock container exactly once per test run, +starting and stopping the mock server exactly once per test run, including when running with pytest-xdist over the entire project. It lives under tests/ (as tests/conftest.py) and is discovered automatically by pytest's normal test collection rules. """ +import json import os -import subprocess +import re +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer +from socketserver import ThreadingMixIn +from typing import Any +from urllib.parse import parse_qs, urlparse import pytest @@ -21,70 +27,132 @@ _PROJECT_NAME: str = "auth0-api" # This file lives at tests/conftest.py, so the project root is one level up. _PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) -_COMPOSE_FILE = os.path.join(_PROJECT_ROOT, "wiremock", "docker-compose.test.yml") - - -def _get_wiremock_port() -> str: - """Gets the dynamically assigned port for the WireMock container.""" - try: - result = subprocess.run( - ["docker", "compose", "-f", _COMPOSE_FILE, "-p", _PROJECT_NAME, "port", "wiremock", "8080"], - check=True, - capture_output=True, - text=True, - ) - # Output is like "0.0.0.0:32768" or "[::]:32768" - port = result.stdout.strip().split(":")[-1] - return port - except subprocess.CalledProcessError: - return "8080" # Fallback to default - - -def _start_wiremock() -> None: - """Starts the WireMock container using docker-compose.""" - global _STARTED, _EXTERNAL, _WIREMOCK_URL - if _STARTED: - return - - # If WIREMOCK_URL is already set (e.g., by CI/CD pipeline), skip container management - existing_url = os.environ.get("WIREMOCK_URL") - if existing_url: - _WIREMOCK_URL = existing_url - _EXTERNAL = True - _STARTED = True - print(f"\nUsing external WireMock at {_WIREMOCK_URL} (container management skipped)") - return - - print(f"\nStarting WireMock container (project: {_PROJECT_NAME})...") - try: - subprocess.run( - ["docker", "compose", "-f", _COMPOSE_FILE, "-p", _PROJECT_NAME, "up", "-d", "--wait"], - check=True, - capture_output=True, - text=True, - ) - _WIREMOCK_PORT = _get_wiremock_port() - _WIREMOCK_URL = f"http://localhost:{_WIREMOCK_PORT}" - os.environ["WIREMOCK_URL"] = _WIREMOCK_URL - print(f"WireMock container is ready at {_WIREMOCK_URL}") - _STARTED = True - except subprocess.CalledProcessError as e: - print(f"Failed to start WireMock: {e.stderr}") - raise - - -def _stop_wiremock() -> None: - """Stops and removes the WireMock container.""" - if _EXTERNAL: - # Container is managed externally; nothing to tear down. - return - - print("\nStopping WireMock container...") - subprocess.run( - ["docker", "compose", "-f", _COMPOSE_FILE, "-p", _PROJECT_NAME, "down", "-v"], - check=False, - capture_output=True, - ) +_MAPPINGS_FILE = os.path.join(_PROJECT_ROOT, "wiremock", "wiremock-mappings.json") + +_server: "ThreadedHTTPServer | None" = None +_server_thread: "threading.Thread | None" = None +_recorded_requests: "list[dict[str, Any]]" = [] +_lock = threading.Lock() +_routes: "list[dict[str, Any]]" = [] + + +class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): + daemon_threads = True + + +def _template_to_regex(template: str) -> "re.Pattern[str]": + parts = re.split(r"(\{[^}]+\})", template) + regex = "^" + "".join("[^/]+" if p.startswith("{") else re.escape(p) for p in parts) + "$" + return re.compile(regex) + + +def _load_routes() -> "list[dict[str, Any]]": + with open(_MAPPINGS_FILE) as f: + data = json.load(f) + routes = [] + for mapping in data.get("mappings", []): + req = mapping.get("request", {}) + resp = mapping.get("response", {}) + template = req.get("urlPathTemplate") or req.get("urlPath", "") + json_body = resp.get("jsonBody") + if json_body is not None: + body = json.dumps(json_body).encode() + else: + raw = resp.get("body", "") + body = raw.encode() if isinstance(raw, str) else b"{}" + routes.append({ + "method": req.get("method", "ANY"), + "pattern": _template_to_regex(template), + "status": resp.get("status", 200), + "body": body, + "headers": resp.get("headers", {}), + }) + return routes + + +class _MockHandler(BaseHTTPRequestHandler): + def _read_body(self) -> bytes: + length = int(self.headers.get("Content-Length", 0)) + return self.rfile.read(length) if length else b"" + + def _send_response(self, status: int, body: bytes, headers: "dict[str, str]") -> None: + self.send_response(status) + content_type = headers.get("Content-Type", "application/json") + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + for key, value in headers.items(): + if key != "Content-Type": + self.send_header(key, value) + self.end_headers() + self.wfile.write(body) + + def do_POST(self) -> None: + if urlparse(self.path).path == "/__admin/requests/find": + self._admin_find() + else: + self._record_and_respond() + + def do_GET(self) -> None: + self._record_and_respond() + + def do_PUT(self) -> None: + self._record_and_respond() + + def do_PATCH(self) -> None: + self._record_and_respond() + + def do_DELETE(self) -> None: + self._record_and_respond() + + def _admin_find(self) -> None: + criteria = json.loads(self._read_body() or b"{}") + method = criteria.get("method", "") + url_path = criteria.get("urlPath", "") + header_criteria = criteria.get("headers", {}) + query_criteria = criteria.get("queryParameters", {}) + + with _lock: + matching = [ + r for r in _recorded_requests + if r["method"] == method + and r["path"] == url_path + and all( + r["headers"].get(h.lower()) == spec.get("equalTo") + for h, spec in header_criteria.items() + ) + and all( + r["query_params"].get(q) == spec.get("equalTo") + for q, spec in query_criteria.items() + ) + ] + + self._send_response(200, json.dumps({"requests": matching}).encode(), {}) + + def _record_and_respond(self) -> None: + self._read_body() # consume to keep connection clean + parsed = urlparse(self.path) + path = parsed.path + query_params = {k: v[0] for k, v in parse_qs(parsed.query).items()} + headers_lc = {k.lower(): v for k, v in self.headers.items()} + + with _lock: + _recorded_requests.append({ + "method": self.command, + "path": path, + "query_params": query_params, + "headers": headers_lc, + }) + + status, body, resp_headers = 200, b"{}", {} + for route in _routes: + if route["method"] in (self.command, "ANY") and route["pattern"].match(path): + status, body, resp_headers = route["status"], route["body"], route["headers"] + break + + self._send_response(status, body, resp_headers) + + def log_message(self, format: str, *args: Any) -> None: + pass # suppress per-request log noise def _is_xdist_worker(config: pytest.Config) -> bool: @@ -121,27 +189,46 @@ def pytest_configure(config: pytest.Config) -> None: """ Pytest hook that runs during test session setup. - Starts WireMock container only from the controller process (xdist) - or the single process (non-xdist). This ensures only one container + Starts the mock server only from the controller process (xdist) + or the single process (non-xdist). This ensures only one server is started regardless of the number of worker processes. """ + global _server, _server_thread, _routes, _recorded_requests if _is_xdist_worker(config): - # Workers never manage the container lifecycle. + # Workers never manage the server lifecycle. return - _start_wiremock() + _routes = _load_routes() + _recorded_requests = [] + _server = ThreadedHTTPServer(("127.0.0.1", 0), _MockHandler) + port = str(_server.server_address[1]) + os.environ["WIREMOCK_PORT"] = port + os.environ["WIREMOCK_URL"] = f"http://127.0.0.1:{port}" + for var in ("no_proxy", "NO_PROXY"): + existing = os.environ.get(var, "") + if "127.0.0.1" not in existing: + os.environ[var] = f"{existing},127.0.0.1" if existing else "127.0.0.1" + _server_thread = threading.Thread(target=_server.serve_forever, daemon=True) + _server_thread.start() + print(f"\nMock HTTP server started on port {port}") def pytest_unconfigure(config: pytest.Config) -> None: """ Pytest hook that runs during test session teardown. - Stops WireMock container only from the controller process (xdist) - or the single process (non-xdist). This ensures the container is + Stops the mock server only from the controller process (xdist) + or the single process (non-xdist). This ensures the server is cleaned up after all workers have finished. """ + global _server, _server_thread if _is_xdist_worker(config): - # Workers never manage the container lifecycle. + # Workers never manage the server lifecycle. return - _stop_wiremock() + if _server: + _server.shutdown() + _server = None + if _server_thread: + _server_thread.join(timeout=5) + _server_thread = None