Debian Codegraph @

debian/patches/0001-Rewrite-wire-tests-to-use-an-in-process-Python-HTTP-.patch

raw symbols SCIP
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 -Pytest plugin that manages the WireMock container lifecycle for wire tests.
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 -starting and stopping the WireMock container exactly once per test run,
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 -import subprocess
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 -_COMPOSE_FILE = os.path.join(_PROJECT_ROOT, "wiremock", "docker-compose.test.yml")
47 -
48 -
49 -def _get_wiremock_port() -> str:
50 - """Gets the dynamically assigned port for the WireMock container."""
51 - try:
52 - result = subprocess.run(
53 - ["docker", "compose", "-f", _COMPOSE_FILE, "-p", _PROJECT_NAME, "port", "wiremock", "8080"],
54 - check=True,
55 - capture_output=True,
56 - text=True,
57 - )
58 - # Output is like "0.0.0.0:32768" or "[::]:32768"
59 - port = result.stdout.strip().split(":")[-1]
60 - return port
61 - except subprocess.CalledProcessError:
62 - return "8080" # Fallback to default
63 -
64 -
65 -def _start_wiremock() -> None:
66 - """Starts the WireMock container using docker-compose."""
67 - global _STARTED, _EXTERNAL, _WIREMOCK_URL
68 - if _STARTED:
69 - return
70 -
71 - # If WIREMOCK_URL is already set (e.g., by CI/CD pipeline), skip container management
72 - existing_url = os.environ.get("WIREMOCK_URL")
73 - if existing_url:
74 - _WIREMOCK_URL = existing_url
75 - _EXTERNAL = True
76 - _STARTED = True
77 - print(f"\nUsing external WireMock at {_WIREMOCK_URL} (container management skipped)")
78 - return
79 -
80 - print(f"\nStarting WireMock container (project: {_PROJECT_NAME})...")
81 - try:
82 - subprocess.run(
83 - ["docker", "compose", "-f", _COMPOSE_FILE, "-p", _PROJECT_NAME, "up", "-d", "--wait"],
84 - check=True,
85 - capture_output=True,
86 - text=True,
87 - )
88 - _WIREMOCK_PORT = _get_wiremock_port()
89 - _WIREMOCK_URL = f"http://localhost:{_WIREMOCK_PORT}"
90 - os.environ["WIREMOCK_URL"] = _WIREMOCK_URL
91 - print(f"WireMock container is ready at {_WIREMOCK_URL}")
92 - _STARTED = True
93 - except subprocess.CalledProcessError as e:
94 - print(f"Failed to start WireMock: {e.stderr}")
95 - raise
96 -
97 -
98 -def _stop_wiremock() -> None:
99 - """Stops and removes the WireMock container."""
100 - if _EXTERNAL:
101 - # Container is managed externally; nothing to tear down.
102 - return
103 -
104 - print("\nStopping WireMock container...")
105 - subprocess.run(
106 - ["docker", "compose", "-f", _COMPOSE_FILE, "-p", _PROJECT_NAME, "down", "-v"],
107 - check=False,
108 - capture_output=True,
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 - Starts WireMock container only from the controller process (xdist)
244 - or the single process (non-xdist). This ensures only one container
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 - # Workers never manage the container lifecycle.
252 + # Workers never manage the server lifecycle.
253 return
254
255 - _start_wiremock()
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 - Stops WireMock container only from the controller process (xdist)
276 - or the single process (non-xdist). This ensures the container is
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 - # Workers never manage the container lifecycle.
284 + # Workers never manage the server lifecycle.
285 return
286
287 - _stop_wiremock()
288 + if _server:
289 + _server.shutdown()
290 + _server = None
291 + if _server_thread:
292 + _server_thread.join(timeout=5)
293 + _server_thread = None