From 8bb32a2d17d60b9036c4245b5d4e55434bf02fbe Mon Sep 17 00:00:00 2001 From: Hasan Basbunar Date: Thu, 29 Oct 2026 00:16:48 +0100 Subject: [PATCH] tests: the port a test starts a server on stays its own beside the other jobs ci-local.sh runs the six jobs side by side on one machine, and three of them run the same test files. Eleven files took a port number out of a socket they then closed, to start a proxy on it or to have a port where nothing listens. Anyone could be handed that port before the server bound it: a stranger could then answer in its place, and a dead port could come alive. run_suite.py ran those files one at a time, which kept them apart inside the suite job and not from the other jobs (code review, 2026-10-28, never seen in three runs). tests/localports.py gives three answers. held() keeps a port bound and never listening: a connection to it is refused and no other program can bind it. serve() starts a server of the test's process on a held port, beside the socket that keeps it (SO_REUSEPORT), so an engine that stops and starts again keeps its port in between. spawn() starts a proxy in a process of its own and keeps it once the socket listening on its port is its own, read in /proc, else starts it again on another port. The certificate test passes port 0, since nobody connects to a proxy that refuses to start, and now checks that the refusal is the certificate's. test_localports.py proves each answer on the machine, and fails on a test file that takes a port the old way: on the tree before this commit it names the eleven. With none left, the suite runs them four at a time. Co-Authored-By: Claude Opus 5.5 --- TESTING.md | 23 +-- dashboard/tests/test_agent_relay.py | 7 +- tests/localports.py | 135 ++++++++++++++++ tests/run_suite.py | 4 +- tests/test_bench_agent_exits.py | 9 +- tests/test_localports.py | 169 +++++++++++++++++++++ tests/test_needle_engine_down.py | 10 +- tests/test_proxy_count_tokens.py | 24 +-- tests/test_proxy_door.py | 26 ++-- tests/test_proxy_guard.py | 122 +++++---------- tests/test_proxy_hold.py | 28 ++-- tests/test_proxy_memory_ceiling.py | 24 +-- tests/test_proxy_refusal_reaches_client.py | 19 +-- tests/test_proxy_tls.py | 45 ++---- tests/test_proxy_vllm_lane.py | 10 +- 15 files changed, 434 insertions(+), 221 deletions(-) create mode 100644 tests/localports.py create mode 100644 tests/test_localports.py diff --git a/TESTING.md b/TESTING.md index 19dff3e7..4260898f 100644 --- a/TESTING.md +++ b/TESTING.md @@ -26,9 +26,11 @@ checkout as it is with `CI_LOCAL_SERIAL=1`. A fragment runs in the checkout as i after the other. A full run took 12 minutes on the reference box on 2026-10-28 (741 and 744 s, the length of `single`), against 63 one step after the other the same day (v1.40.4), and 72 on GitHub when the steps ran as one job (v1.40.3). On one machine the jobs share its ports, as they -do not on GitHub, where each job has a runner of its own: the files that take a port number out of -a socket they close run alone within the suite, not apart from the other jobs. While working, run -the gate you care about by name fragment, and the whole thing before pushing. +do not on GitHub, where each job has a runner of its own: a test takes the port of a server it starts +from `tests/localports.py`, which keeps that port the test's beside the other jobs and any program of +the machine, and `test_localports.py` fails on a test file that takes a port number out of a socket +it closes. While working, run the gate you care about by name fragment, and the whole thing before +pushing. The runtime is **stdlib only** and stays that way. Three measuring gates need pip packages (`coverage`, `hypothesis`); they ask `tests/testpy.sh` for an @@ -488,9 +490,12 @@ the hole, a conditional is both branches. persists an HMAC secret (so a service restart does not log every browser out) and that suite had not redirected `COCKPIT_CONFIG_DIR`. `test_cockpit_collectors.py` adds the other half by recording every argv its - stub was asked for. The step runs the files up to four at a time, except the - ones that call `getsockname()[1]`: they take a port number out of a socket - they close, to start a server on it later or to have a port where nothing - listens, and a file running beside them could be handed that port meanwhile, - so they run alone once the others are over. A test that frees a port it - still relies on takes the number that way to be found. + stub was asked for. The step runs the files up to four at a time. A file that + calls `getsockname()[1]` takes a port number out of a socket it closes, to + start a server on it later or to have a port where nothing listens, and a file + running beside it could be handed that port meanwhile, so such a file runs + alone once the others are over. None does since `tests/localports.py` + (2026-10-28): `held()` keeps a port where nothing listens, `serve()` starts a + server of the test's process on it, and `spawn()` keeps a server's own process + once the socket listening on its port is its own. `test_localports.py` fails + on a test file that takes a port the old way. diff --git a/dashboard/tests/test_agent_relay.py b/dashboard/tests/test_agent_relay.py index a5162b21..c3def2ec 100644 --- a/dashboard/tests/test_agent_relay.py +++ b/dashboard/tests/test_agent_relay.py @@ -22,6 +22,9 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import agent_relay as ar # noqa: E402 +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tests")) +import localports # noqa: E402 + GOOD_AUTH = "Basic " + base64.b64encode(b"cockpit:secret").decode() SPA_DOC = b"Oc
" @@ -376,9 +379,7 @@ class RelayTests(unittest.TestCase): self.assertIn("credentials", json.loads(body)["error"]) def test_upstream_down_is_502(self): - with socket.socket() as dead: - dead.bind(("127.0.0.1", 0)) - port = dead.getsockname()[1] + _, port = localports.held(self) # nothing listens there, and no other program can cfg = ar.RelayConfig(upstream=("127.0.0.1", port), credentials=lambda: ("a", "b"), is_authed=lambda c: True, cockpit_port=30090) srv = ar.serve(cfg, "127.0.0.1", 0) diff --git a/tests/localports.py b/tests/localports.py new file mode 100644 index 00000000..468909f8 --- /dev/null +++ b/tests/localports.py @@ -0,0 +1,135 @@ +"""Ports for the tests that start servers, safe beside every other program of the machine. + +A port number read from a socket that is then closed is free for anyone until the server it was taken +for binds it: ci-local.sh runs the workflow's jobs side by side on one machine, three of them run the +same test files, and any program there can be handed that port meanwhile (code review, 2026-10-28). +run_suite.py ran those files one at a time, which kept them from each other inside one job, not from the +other jobs. Three answers, each proven in test_localports.py: + +- held(): a port kept for the test, bound and never listening. A connection to it is refused, as to a + lane that is gone, and no other program can bind it: the socket has no SO_REUSEADDR, with which + another socket could share the port while this one is not listening. +- serve(port, ...): a server of this process on a held port, shared with the socket that keeps it by + SO_REUSEPORT: an engine that was gone comes up there, goes down and comes up again, and the port stays + the test's in between. +- spawn(start): a server in a process of its own, which cannot share a held port. It starts on a port + that was free a moment ago and is kept once the socket listening there is its own (read in /proc), + else it starts again on another port. +""" +import os +import socket +import subprocess +import time + +HOST = "127.0.0.1" + + +def held(test=None, host=HOST): + """(socket, port): a port kept until the socket closes, at the test's cleanup when the test is given.""" + sock = socket.socket() + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + sock.bind((host, 0)) + if test is not None: + test.addCleanup(sock.close) + return sock, sock.getsockname()[1] + + +def serve(port, server_class, handler, host=HOST): + """A server_class (socketserver) listening on a held port, beside the socket that keeps it.""" + class Shared(server_class): + def server_bind(self): + self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + super().server_bind() + Shared.__name__ = Shared.__qualname__ = server_class.__name__ + return Shared((host, port), handler) + + +def _listener(port): + """The inode of the socket listening on this TCP port, whatever its address, or None.""" + for table in ("/proc/net/tcp", "/proc/net/tcp6"): + try: + with open(table) as f: + rows = f.read().splitlines()[1:] + except OSError: + continue + for row in rows: + cols = row.split() + if len(cols) > 9 and cols[3] == "0A" and int(cols[1].rsplit(":", 1)[1], 16) == port: + return cols[9] + return None + + +def _family(pid): + """The process and every process under it: a server started through a wrapper listens in a child.""" + kids = {} + for d in os.listdir("/proc"): + if d.isdigit(): + try: + with open(f"/proc/{d}/stat") as f: + ppid = int(f.read().rsplit(")", 1)[1].split()[1]) + except (OSError, ValueError, IndexError): + continue + kids.setdefault(ppid, []).append(int(d)) + out, todo = [], [pid] + while todo: + p = todo.pop() + out.append(p) + todo += kids.get(p, []) + return out + + +def _holds(pid, inode): + """Whether the process, or one under it, holds the socket of that inode.""" + for p in _family(pid): + try: + fds = os.listdir(f"/proc/{p}/fd") + except OSError: + continue + for fd in fds: + try: + if os.readlink(f"/proc/{p}/fd/{fd}") == f"socket:[{inode}]": + return True + except OSError: + continue + return False + + +def _end(proc): + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + + +def spawn(start, tries=5, within=20.0, host=HOST, pick=None): + """(process, port), start(port) being a Popen of a server that binds port: kept once the socket + listening on the port is the process's own, started again on another port when the process ended + first (someone had the port) or someone else listens there. pick(), for this module's tests, names + the port to try, None for one that was free a moment ago.""" + tried = [] + for _ in range(tries): + port = pick() if pick else None + if port is None: + probe = socket.socket() + probe.bind((host, 0)) + port = probe.getsockname()[1] + probe.close() + proc = start(port) + deadline, why = time.monotonic() + within, f"nothing listened in {within:g} s" + while time.monotonic() < deadline: + inode = _listener(port) + if inode and _holds(proc.pid, inode): + return proc, port + if inode: + why = "someone else listens there" + break + if proc.poll() is not None: + why = f"it ended with {proc.returncode}" + break + time.sleep(0.02) + tried.append(f"{port}: {why}") + _end(proc) + raise RuntimeError(f"no port of its own after {tries} tries ({'; '.join(tried)})") diff --git a/tests/run_suite.py b/tests/run_suite.py index 71f64a35..56bad1b8 100644 --- a/tests/run_suite.py +++ b/tests/run_suite.py @@ -15,7 +15,9 @@ and takes every fact from that one run: - it contacts no serving port (the same hook records a connect() to one, with the test line). Files that take a port number out of a socket they close (getsockname()[1]) run one at a time once -the others are over: a file running beside them could be handed the same port meanwhile. The +the others are over: a file running beside them could be handed the same port meanwhile. No test file +does since tests/localports.py, which keeps a port the test's beside the other jobs as well +(test_localports.py fails on a file that does): the planted files of this script's own test still do. The witness HOME, the listeners and what is left running are the CI step's, around this script. Usage: run_suite.py [--jobs N] [--report FILE] [--repo DIR --first F1,F2] (exit 1 on any failure; diff --git a/tests/test_bench_agent_exits.py b/tests/test_bench_agent_exits.py index 6d9f2730..e6284942 100644 --- a/tests/test_bench_agent_exits.py +++ b/tests/test_bench_agent_exits.py @@ -8,7 +8,6 @@ partial loop is not a measurement, which is what exit 3 says elsewhere in this t """ import http.server import os -import socket import subprocess import sys import threading @@ -16,6 +15,9 @@ import time import unittest from pathlib import Path +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import localports # noqa: E402 + REPO = Path(__file__).resolve().parents[1] TOOL = REPO / "bench-agent.py" MODE = ["hang"] @@ -66,10 +68,7 @@ class TheExits(unittest.TestCase): self.assertNotIn("Traceback", r.stderr) def test_a_lane_that_is_gone(self): - s = socket.socket() - s.bind(("127.0.0.1", 0)) - port = s.getsockname()[1] - s.close() # nothing listens there now + _, port = localports.held(self) # nothing listens there, and no other program can r = self.run_tool(port) self.assertEqual(r.returncode, 3, r.stderr) self.assertNotIn("Traceback", r.stderr) diff --git a/tests/test_localports.py b/tests/test_localports.py new file mode 100644 index 00000000..da4b20cb --- /dev/null +++ b/tests/test_localports.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""tests/localports.py: the port a test starts a server on stays the test's, beside any other program. + +ci-local.sh runs the workflow's jobs side by side on one machine, three of them over the same test files, +and eleven of those files took a port number out of a socket they then closed: anyone could be handed +the port before the server it was for bound it, a stranger could answer in its place, and a port meant +to be dead could come alive (code review, 2026-10-28). Each answer of localports.py is proven here on the +machine itself, and the last case keeps any test file from taking a port that way again.""" +import http.server +import os +import pathlib +import socket +import subprocess +import sys +import threading +import unittest +import urllib.request + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import localports # noqa: E402 + +REPO = pathlib.Path(__file__).resolve().parents[1] +# The files that may hold the words: this module and its test (the old way, as a witness), run_suite.py, +# which reads them, its own test's planted file, and the reaper's listener, which keeps its socket open. +SPARED = {"tests/localports.py", "tests/test_localports.py", "tests/run_suite.py", "tests/test_run_suite.py", + "tests/test_suite_reaper.py"} +SERVER = ("import http.server, sys\n" + "class H(http.server.BaseHTTPRequestHandler):\n" + " def do_GET(self):\n" + " self.send_response(200); self.send_header('Content-Length', '4'); self.end_headers()\n" + " self.wfile.write(b'mine')\n" + " def log_message(self, *a):\n" + " pass\n" + "http.server.HTTPServer(('127.0.0.1', int(sys.argv[1])), H).serve_forever()\n") + + +class Ok(http.server.BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + self.send_header("Content-Length", "2") + self.end_headers() + self.wfile.write(b"ok") + + def log_message(self, *a): + pass + + +def get(port): + """What the port answers: the body, or the kind of error.""" + try: + with urllib.request.urlopen(f"http://127.0.0.1:{port}/", timeout=5) as r: + return r.read().decode() + except OSError as e: + return type(e).__name__ + + +def a_stranger_binds(port, host="127.0.0.1", reuse=False): + s = socket.socket() + try: + if reuse: + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + s.bind((host, port)) + return True + except OSError: + return False + finally: + s.close() + + +class AHeldPort(unittest.TestCase): + def test_refuses_a_connection_and_no_one_else_can_bind_it(self): + _, port = localports.held(self) + self.assertEqual(get(port), "URLError") + for host in ("127.0.0.1", "0.0.0.0"): + for reuse in (False, True): + self.assertFalse(a_stranger_binds(port, host, reuse), (host, reuse)) + with self.assertRaises(OSError): + http.server.HTTPServer(("127.0.0.1", port), Ok) + + def test_the_old_way_left_it_to_anyone(self): + # the witness: a port read out of a socket that is then closed is anyone's at once + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + self.assertTrue(a_stranger_binds(port)) + + def test_a_server_comes_and_goes_on_it_and_it_stays_the_tests(self): + _, port = localports.held(self) + for _ in range(3): + srv = localports.serve(port, http.server.ThreadingHTTPServer, Ok) + threading.Thread(target=srv.serve_forever, daemon=True).start() + self.assertIsInstance(srv, http.server.ThreadingHTTPServer) + self.assertEqual([get(port) for _ in range(3)], ["ok"] * 3) + srv.shutdown() + srv.server_close() + self.assertEqual(get(port), "URLError", "down again, as an engine that stopped") + self.assertFalse(a_stranger_binds(port, reuse=True), "and still the test's") + + +class ASpawnedServer(unittest.TestCase): + def start(self, port): + proc = subprocess.Popen([sys.executable, "-c", SERVER, str(port)], stderr=subprocess.DEVNULL) + self.addCleanup(localports._end, proc) + return proc + + def stranger(self): + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Ok) + threading.Thread(target=srv.serve_forever, daemon=True).start() + self.addCleanup(lambda: (srv.shutdown(), srv.server_close())) + return srv.server_address[1] + + def test_is_kept_once_the_port_is_its_own(self): + proc, port = localports.spawn(self.start) + self.assertIsNone(proc.poll()) + self.assertEqual(get(port), "mine") + + def test_moves_on_when_someone_else_listens_on_the_port(self): + taken = self.stranger() + # the old way: start the server there, then take a connection that succeeds for it ready + old = self.start(taken) + socket.create_connection(("127.0.0.1", taken), timeout=5).close() + self.assertEqual(get(taken), "ok", "the old way would have tested the stranger") + old.wait(timeout=10) + tries = iter([taken]) + proc, port = localports.spawn(self.start, pick=lambda: next(tries, None)) + self.assertNotEqual(port, taken) + self.assertEqual((get(port), get(taken)), ("mine", "ok")) + + def test_a_server_behind_a_wrapper_is_its_own(self): + def wrapped(port): + # "; :" keeps bash from replacing itself with the server: the listener is a child of the process + proc = subprocess.Popen(["bash", "-c", f'"{sys.executable}" -c "$0" {port}; :', SERVER], + stderr=subprocess.DEVNULL, start_new_session=True) + self.addCleanup(self.end_group, proc) + return proc + _, port = localports.spawn(wrapped) + self.assertEqual(get(port), "mine") + + def end_group(self, proc): + try: + os.killpg(proc.pid, 15) + except ProcessLookupError: + pass + proc.wait(timeout=10) + + def test_says_why_when_no_try_is_kept(self): + def ends(port): + return subprocess.Popen([sys.executable, "-c", "raise SystemExit(3)"]) + with self.assertRaises(RuntimeError) as cm: + localports.spawn(ends, tries=2, within=5) + self.assertIn("after 2 tries", str(cm.exception)) + self.assertIn("it ended with 3", str(cm.exception)) + taken = self.stranger() + with self.assertRaises(RuntimeError) as cm: + localports.spawn(self.start, tries=1, pick=lambda: taken) + self.assertIn(f"{taken}: someone else listens there", str(cm.exception)) + + +class NoTestFile(unittest.TestCase): + def test_takes_a_port_number_out_of_a_socket_it_closes(self): + files = sorted(str(p.relative_to(REPO)) for d in ("tests", "dashboard/tests") for p in (REPO / d).glob("*.py")) + self.assertIn("tests/test_proxy_hold.py", files) + taking = [f for f in files if f not in SPARED and "getsockname()[1]" in (REPO / f).read_text()] + self.assertEqual(taking, [], "take it from tests/localports.py: held() for a port nothing listens on, " + "serve() for a server of the test's process, spawn() for one of its own") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/test_needle_engine_down.py b/tests/test_needle_engine_down.py index 0e7638b9..207d3c27 100644 --- a/tests/test_needle_engine_down.py +++ b/tests/test_needle_engine_down.py @@ -8,12 +8,15 @@ review, 2026-09-24). Run against a port nothing listens on, with a HOME of its o """ import os import shutil -import socket import subprocess +import sys import tempfile import unittest from pathlib import Path +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import localports # noqa: E402 + NEEDLE = Path(__file__).resolve().parents[1] / "needle.sh" @@ -24,10 +27,7 @@ class AnEngineThatIsDown(unittest.TestCase): os.makedirs(os.path.join(self.home, ".config", "qwen38")) with open(os.path.join(self.home, ".config", "qwen38", "api-key"), "w") as f: f.write("test-key\n") - s = socket.socket() - s.bind(("127.0.0.1", 0)) - self.port = s.getsockname()[1] - s.close() # nothing listens there now + _, self.port = localports.held(self) # nothing listens there, and no other program can def run_needle(self, *args): r = subprocess.run(["bash", str(NEEDLE), *args, "--trials", "1", "--depths", "1000", "--no-flush"], diff --git a/tests/test_proxy_count_tokens.py b/tests/test_proxy_count_tokens.py index 6560c44d..dc8f65ff 100644 --- a/tests/test_proxy_count_tokens.py +++ b/tests/test_proxy_count_tokens.py @@ -15,7 +15,6 @@ import json import os import pathlib import shutil -import socket import socketserver import subprocess import sys @@ -24,6 +23,9 @@ import threading import time import unittest +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import localports # noqa: E402 + REPO = pathlib.Path(__file__).resolve().parents[1] WORDS = 150_000 # past the 100,000-token pool, in 900 KB of text @@ -71,12 +73,6 @@ class Engine(socketserver.ThreadingMixIn, http.server.HTTPServer): daemon_threads = True -def free_port(): - with socket.socket() as s: - s.bind(("127.0.0.1", 0)) - return s.getsockname()[1] - - class TheCountIsAnswered(unittest.TestCase): @classmethod def setUpClass(cls): @@ -91,19 +87,13 @@ class TheCountIsAnswered(unittest.TestCase): @classmethod def start_proxy(cls): """A proxy of its own: the pool it measured stays cached for ten minutes.""" - port = free_port() env = {"PATH": os.environ["PATH"], "HOME": str(cls.home), "PROXY_BIND": "127.0.0.1", "UPSTREAM": f"http://127.0.0.1:{cls.engine.server_address[1]}", "PROMPT_CEILING_TOKENS": "0", "FLASH_PROMPT_CEILING_TOKENS": "0"} - cls.proxies.append(subprocess.Popen([sys.executable, str(REPO / "keepalive-proxy.py"), str(port)], env=env, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) - end = time.time() + 20 - while time.time() < end: - try: - socket.create_connection(("127.0.0.1", port), timeout=0.5).close() - break - except OSError: - time.sleep(0.1) + proc, port = localports.spawn(lambda port: subprocess.Popen( + [sys.executable, str(REPO / "keepalive-proxy.py"), str(port)], env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) + cls.proxies.append(proc) return port @classmethod diff --git a/tests/test_proxy_door.py b/tests/test_proxy_door.py index adabc97b..d64cc377 100644 --- a/tests/test_proxy_door.py +++ b/tests/test_proxy_door.py @@ -21,6 +21,9 @@ import time import unittest from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import localports # noqa: E402 + HERE = Path(__file__).resolve() KEY = "door-test-key-0123456789" @@ -121,26 +124,17 @@ class Engine(http.server.BaseHTTPRequestHandler): "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}) -def _free_port(): - with socket.socket() as sk: - sk.bind(("127.0.0.1", 0)) - return sk.getsockname()[1] - - def _start_proxy(home, upstream_port, extra_env=None): - port = _free_port() err = tempfile.NamedTemporaryFile(prefix="door-proxy-stderr-", delete=False) env = {"PATH": os.environ["PATH"], "HOME": str(home), "PROXY_BIND": "127.0.0.1", "UPSTREAM": f"http://127.0.0.1:{upstream_port}", **(extra_env or {})} - proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(port)], - env=env, stdout=err, stderr=err) - end = time.time() + 20 - while time.time() < end: - try: - socket.create_connection(("127.0.0.1", port), timeout=0.2).close() - break - except OSError: - time.sleep(0.05) + + def start(port): + err.seek(0) + err.truncate() # what a try on a port someone else had wrote goes + return subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(port)], + env=env, stdout=err, stderr=err) + proc, port = localports.spawn(start) return proc, port, err.name diff --git a/tests/test_proxy_guard.py b/tests/test_proxy_guard.py index 0e3474e9..d2eb305a 100644 --- a/tests/test_proxy_guard.py +++ b/tests/test_proxy_guard.py @@ -15,6 +15,9 @@ import urllib.error import urllib.request from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import localports # noqa: E402 + def _keep_env(cls): """Put os.environ back as this class found it, once it is done: the variables set for @@ -406,11 +409,9 @@ class ProxyInFrontOfLoadingEngine(unittest.TestCase): @classmethod def setUpClass(cls): - import socket, subprocess, sys, time + import subprocess, sys cls.eng = http.server.HTTPServer(("127.0.0.1", 0), LoadingEngine) threading.Thread(target=cls.eng.serve_forever, daemon=True).start() - with socket.socket() as sk: - sk.bind(("127.0.0.1", 0)); cls.port = sk.getsockname()[1] # This class models a loading engine whose pool IS known (200000 via # /get_server_info) while /tokenize still 503s. pool_tokens() needs the # api-key file to ask, so the proxy runs in a HOME that has one; without @@ -419,13 +420,9 @@ class ProxyInFrontOfLoadingEngine(unittest.TestCase): cls.home = key_home() env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{cls.eng.server_address[1]}", HOME=str(cls.home)) - cls.proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(cls.port)], - env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - for _ in range(100): - try: - socket.create_connection(("127.0.0.1", cls.port), timeout=0.2).close(); break - except OSError: - time.sleep(0.05) + cls.proc, cls.port = localports.spawn(lambda port: subprocess.Popen( + [sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(port)], + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) @classmethod def tearDownClass(cls): @@ -464,29 +461,22 @@ class ProxyOnABoxSwitchedToImages(unittest.TestCase): asked through PATH, so a fake systemctl stands in for it here, in both directions.""" def spawn(self, image_active): - import socket, subprocess, sys, tempfile, time + import subprocess, sys, tempfile fake = Path(tempfile.mkdtemp(prefix="fake-systemctl-")) (fake / "systemctl").write_text( "#!/bin/sh\n" f'[ "$*" = "is-active --quiet qwen38-image.service" ] && exit {0 if image_active else 3}\n' "exit 3\n") (fake / "systemctl").chmod(0o755) - with socket.socket() as sk: # a port nothing listens on: the engine is gone - sk.bind(("127.0.0.1", 0)); dead = sk.getsockname()[1] - with socket.socket() as sk: - sk.bind(("127.0.0.1", 0)); port = sk.getsockname()[1] + _, dead = localports.held(self) # a port nothing listens on: the engine is gone home = no_key_home() self.addCleanup(shutil.rmtree, home, True) env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{dead}", PATH=f"{fake}:{os.environ.get('PATH', '')}", HOME=str(home)) - proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(port)], - env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + proc, port = localports.spawn(lambda port: subprocess.Popen( + [sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(port)], + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) self.addCleanup(lambda: (proc.terminate(), proc.wait(timeout=5))) - for _ in range(100): - try: - socket.create_connection(("127.0.0.1", port), timeout=0.2).close(); break - except OSError: - time.sleep(0.05) return port def ask(self, port): @@ -590,21 +580,15 @@ class RefusalIsRecognisableAsOverflow(unittest.TestCase): @classmethod def setUpClass(cls): - import socket, subprocess, sys, time + import subprocess, sys cls.eng = http.server.HTTPServer(("127.0.0.1", 0), SmallPoolEngine) threading.Thread(target=cls.eng.serve_forever, daemon=True).start() - with socket.socket() as sk: - sk.bind(("127.0.0.1", 0)); cls.port = sk.getsockname()[1] cls.home = key_home() env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{cls.eng.server_address[1]}", HOME=str(cls.home)) - cls.proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(cls.port)], - env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - for _ in range(100): - try: - socket.create_connection(("127.0.0.1", cls.port), timeout=0.2).close(); break - except OSError: - time.sleep(0.05) + cls.proc, cls.port = localports.spawn(lambda port: subprocess.Popen( + [sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(port)], + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) @classmethod def tearDownClass(cls): @@ -874,22 +858,16 @@ class CorruptionTripwireEndToEnd(unittest.TestCase): @classmethod def setUpClass(cls): - import socket, subprocess, time + import subprocess CorruptingEngine.aborted = [] cls.eng = http.server.ThreadingHTTPServer(("127.0.0.1", 0), CorruptingEngine) threading.Thread(target=cls.eng.serve_forever, daemon=True).start() - with socket.socket() as sk: - sk.bind(("127.0.0.1", 0)); cls.port = sk.getsockname()[1] cls.home = no_key_home() env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{cls.eng.server_address[1]}", CORRUPTION_RUN="48", PROMPT_CEILING_TOKENS="0", HOME=str(cls.home)) - cls.proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(cls.port)], - env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - for _ in range(100): - try: - socket.create_connection(("127.0.0.1", cls.port), timeout=0.2).close(); break - except OSError: - time.sleep(0.05) + cls.proc, cls.port = localports.spawn(lambda port: subprocess.Popen( + [sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(port)], + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) @classmethod def tearDownClass(cls): @@ -960,22 +938,16 @@ class HardeningV615(unittest.TestCase): @classmethod def setUpClass(cls): - import socket, subprocess + import subprocess cls.eng = http.server.ThreadingHTTPServer(("127.0.0.1", 0), HardeningEngine) threading.Thread(target=cls.eng.serve_forever, daemon=True).start() - with socket.socket() as sk: - sk.bind(("127.0.0.1", 0)); cls.port = sk.getsockname()[1] cls.home = no_key_home() env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{cls.eng.server_address[1]}", PROMPT_CEILING_TOKENS="200000", UPSTREAM_GET_TIMEOUT_S="1", MAX_BODY_BYTES="1000000", HOME=str(cls.home)) - cls.proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(cls.port)], - env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - for _ in range(100): - try: - socket.create_connection(("127.0.0.1", cls.port), timeout=0.2).close(); break - except OSError: - time.sleep(0.05) + cls.proc, cls.port = localports.spawn(lambda port: subprocess.Popen( + [sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(port)], + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) cls.k = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(cls.k) @@ -1858,23 +1830,15 @@ class TheOversizeGuardReachesTheNonV1Routes(unittest.TestCase): @classmethod def setUpClass(cls): - import socket, subprocess + import subprocess cls.eng = http.server.HTTPServer(("127.0.0.1", 0), SmallPoolEngine) threading.Thread(target=cls.eng.serve_forever, daemon=True).start() - with socket.socket() as sk: - sk.bind(("127.0.0.1", 0)); cls.port = sk.getsockname()[1] cls.home = key_home() env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{cls.eng.server_address[1]}", HOME=str(cls.home)) - cls.proc = subprocess.Popen( - [sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(cls.port)], - env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - for _ in range(100): - try: - import socket as _s - _s.create_connection(("127.0.0.1", cls.port), timeout=0.2).close(); break - except OSError: - time.sleep(0.05) + cls.proc, cls.port = localports.spawn(lambda port: subprocess.Popen( + [sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(port)], + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) @classmethod def tearDownClass(cls): @@ -1916,22 +1880,15 @@ class TheGuardNominatesByItsBound(unittest.TestCase): @classmethod def setUpClass(cls): - import socket, subprocess + import subprocess cls.eng = http.server.HTTPServer(("127.0.0.1", 0), SmallPoolEngine) threading.Thread(target=cls.eng.serve_forever, daemon=True).start() - with socket.socket() as sk: - sk.bind(("127.0.0.1", 0)); cls.port = sk.getsockname()[1] cls.home = key_home() env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{cls.eng.server_address[1]}", HOME=str(cls.home)) - cls.proc = subprocess.Popen( - [sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(cls.port)], - env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - for _ in range(100): - try: - socket.create_connection(("127.0.0.1", cls.port), timeout=0.2).close(); break - except OSError: - time.sleep(0.05) + cls.proc, cls.port = localports.spawn(lambda port: subprocess.Popen( + [sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(port)], + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) @classmethod def tearDownClass(cls): @@ -2004,22 +1961,15 @@ class WhereNoWedgeIsPossibleTheAverageNominates(unittest.TestCase): @classmethod def setUpClass(cls): - import socket, subprocess + import subprocess cls.eng = http.server.HTTPServer(("127.0.0.1", 0), cls.ENGINE) threading.Thread(target=cls.eng.serve_forever, daemon=True).start() - with socket.socket() as sk: - sk.bind(("127.0.0.1", 0)); cls.port = sk.getsockname()[1] cls.home = key_home() env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{cls.eng.server_address[1]}", HOME=str(cls.home)) - cls.proc = subprocess.Popen( - [sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(cls.port)], - env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - for _ in range(100): - try: - socket.create_connection(("127.0.0.1", cls.port), timeout=0.2).close(); break - except OSError: - time.sleep(0.05) + cls.proc, cls.port = localports.spawn(lambda port: subprocess.Popen( + [sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(port)], + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) @classmethod def tearDownClass(cls): diff --git a/tests/test_proxy_hold.py b/tests/test_proxy_hold.py index 5f234d58..dce5e9bc 100644 --- a/tests/test_proxy_hold.py +++ b/tests/test_proxy_hold.py @@ -27,17 +27,14 @@ import time import unittest from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import localports # noqa: E402 + HERE = Path(__file__).resolve() PROXY = HERE.parents[1] / "keepalive-proxy.py" UNITS = "qwen38-sglang.service qwen38-flash.service" -def free_port(): - with socket.socket() as sk: - sk.bind(("127.0.0.1", 0)) - return sk.getsockname()[1] - - class Engine(http.server.BaseHTTPRequestHandler): """SGLang as the proxy sees it: its info route, a generation in both dialects, /tokenize. The server's `mode` is "up" or "starting" (503, as SGLang answers while it loads) for @@ -122,7 +119,8 @@ class Box: f'if [ "$1" = list-jobs ]; then cat "{self.jobs_file}" 2>/dev/null; exit 0; fi\n' "exit 3\n") (self.t / "bin/systemctl").chmod(0o755) - self.engine_port, self.port = free_port(), free_port() + # the engine's port is gone until start_engine, and the test's all along: no one else can take it + self.engine_sock, self.engine_port = localports.held(test) self.srv = None self.generations = [] env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{self.engine_port}", HOME=str(self.t / "home"), @@ -148,13 +146,13 @@ class Box: self.port = self.proxy.server_address[1] return self.log = open(self.t / "proxy.log", "w") - self.proc = subprocess.Popen([sys.executable, str(PROXY), str(self.port)], env=env, - stdout=subprocess.DEVNULL, stderr=self.log) - for _ in range(100): - try: - socket.create_connection(("127.0.0.1", self.port), timeout=0.2).close(); break - except OSError: - time.sleep(0.05) + + def start(port): + self.log.seek(0) + self.log.truncate() # what a try on a port someone else had wrote goes + return subprocess.Popen([sys.executable, str(PROXY), str(port)], env=env, + stdout=subprocess.DEVNULL, stderr=self.log) + self.proc, self.port = localports.spawn(start) def state(self, s): self.state_file.write_text(s + "\n") @@ -165,7 +163,7 @@ class Box: def start_engine(self, mode="up", pool=200000, info_mode=None): if self.srv is None: - self.srv = http.server.ThreadingHTTPServer(("127.0.0.1", self.engine_port), Engine) + self.srv = localports.serve(self.engine_port, http.server.ThreadingHTTPServer, Engine) self.srv.generations = self.generations threading.Thread(target=self.srv.serve_forever, daemon=True).start() self.srv.mode, self.srv.pool, self.srv.info_mode = mode, pool, info_mode or mode diff --git a/tests/test_proxy_memory_ceiling.py b/tests/test_proxy_memory_ceiling.py index c02f2d93..8cc53cfc 100644 --- a/tests/test_proxy_memory_ceiling.py +++ b/tests/test_proxy_memory_ceiling.py @@ -28,15 +28,16 @@ import os import pathlib import re import shutil -import socket import socketserver import subprocess import sys import tempfile import threading -import time import unittest +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import localports # noqa: E402 + REPO = pathlib.Path(__file__).resolve().parents[1] BODY_MIB = 24 @@ -75,12 +76,6 @@ class Engine(socketserver.ThreadingMixIn, http.server.HTTPServer): daemon_threads = True -def free_port(): - with socket.socket() as s: - s.bind(("127.0.0.1", 0)) - return s.getsockname()[1] - - def peak_mib(pid): """The process's highest resident set so far (VmHWM), in MiB.""" with open(f"/proc/{pid}/status") as f: @@ -134,19 +129,12 @@ class TheCeilingHoldsTheBudget(unittest.TestCase): def rate(self, shape): """The proxy's peak resident growth for one body of this shape, over the body's bytes, on a proxy of its own: its peak (VmHWM) only grows, so a second body would measure from the first's peak.""" - port = free_port() env = {"PATH": os.environ["PATH"], "HOME": str(self.home), "PROXY_BIND": "127.0.0.1", "UPSTREAM": f"http://127.0.0.1:{self.engine.server_address[1]}", "PROXY_HOLD_UNITS": ""} - proxy = subprocess.Popen([sys.executable, str(REPO / "keepalive-proxy.py"), str(port)], env=env, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + proxy, port = localports.spawn(lambda port: subprocess.Popen( + [sys.executable, str(REPO / "keepalive-proxy.py"), str(port)], env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) try: - end = time.time() + 20 - while time.time() < end: - try: - socket.create_connection(("127.0.0.1", port), timeout=0.5).close() - break - except OSError: - time.sleep(0.1) self.send(port, {"model": "qwen3.8-27b", "messages": [{"role": "user", "content": "2+2?"}]}) idle = peak_mib(proxy.pid) body = json.dumps({"model": "qwen3.8-27b", "reasoning_effort": "lean", diff --git a/tests/test_proxy_refusal_reaches_client.py b/tests/test_proxy_refusal_reaches_client.py index 080be10b..5ed4d353 100644 --- a/tests/test_proxy_refusal_reaches_client.py +++ b/tests/test_proxy_refusal_reaches_client.py @@ -18,9 +18,11 @@ import socket import subprocess import sys import tempfile -import time import unittest +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import localports # noqa: E402 + REPO = pathlib.Path(__file__).resolve().parents[1] CAP = 1024 * 1024 KEY = "k-test" # the key this harness gives the proxy @@ -32,20 +34,11 @@ class TheRefusalArrives(unittest.TestCase): cls.home = pathlib.Path(tempfile.mkdtemp(prefix="kp-413-")) (cls.home / ".config" / "qwen38").mkdir(parents=True) (cls.home / ".config" / "qwen38" / "api-key").write_text(KEY + "\n") - with socket.socket() as s: - s.bind(("127.0.0.1", 0)) - cls.port = s.getsockname()[1] env = {"PATH": os.environ["PATH"], "HOME": str(cls.home), "PROXY_BIND": "127.0.0.1", "UPSTREAM": "http://127.0.0.1:9", "MAX_BODY_BYTES": str(CAP)} - cls.proxy = subprocess.Popen([sys.executable, str(REPO / "keepalive-proxy.py"), str(cls.port)], env=env, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - end = time.time() + 20 - while time.time() < end: - try: - socket.create_connection(("127.0.0.1", cls.port), timeout=0.5).close() - break - except OSError: - time.sleep(0.1) + cls.proxy, cls.port = localports.spawn(lambda port: subprocess.Popen( + [sys.executable, str(REPO / "keepalive-proxy.py"), str(port)], env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) @classmethod def tearDownClass(cls): diff --git a/tests/test_proxy_tls.py b/tests/test_proxy_tls.py index abc02120..89be72af 100644 --- a/tests/test_proxy_tls.py +++ b/tests/test_proxy_tls.py @@ -27,6 +27,9 @@ import unittest import urllib.request from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import localports # noqa: E402 + REPO = Path(__file__).resolve().parents[1] @@ -61,12 +64,6 @@ def start_engine(): return srv, srv.server_address[1] -def free_port(): - with socket.socket() as s: - s.bind(("127.0.0.1", 0)) - return s.getsockname()[1] - - def base_env(upstream_port, extra=None): env = {"PATH": "/usr/local/bin:/usr/bin:/bin", "HOME": tempfile.mkdtemp(), "UPSTREAM": "http://127.0.0.1:%d" % upstream_port} @@ -75,21 +72,11 @@ def base_env(upstream_port, extra=None): return env -def run_proxy(port, env, capture_stderr=False): - proc = subprocess.Popen( - [sys.executable, str(REPO / "keepalive-proxy.py"), str(port)], env=env, - stderr=subprocess.PIPE if capture_stderr else subprocess.DEVNULL) - deadline = time.time() + 10 - while time.time() < deadline: - try: - with socket.create_connection(("127.0.0.1", port), 0.5): - return proc - except OSError: - if proc.poll() is not None: - tail = proc.stderr.read().decode()[-400:] if capture_stderr else "" - raise AssertionError(f"proxy exited early rc={proc.returncode} {tail}") - proc.terminate() - raise AssertionError("proxy never listened") +def run_proxy(env): + """(process, port): a proxy on a port of its own.""" + return localports.spawn(lambda port: subprocess.Popen( + [sys.executable, str(REPO / "keepalive-proxy.py"), str(port)], env=env, stderr=subprocess.DEVNULL), + within=10) def https_post(port, path, obj): @@ -133,8 +120,7 @@ class TlsDoor(unittest.TestCase): cls.engine.server_close() def test_cert_named_speaks_tls_and_nothing_plain_answers_beside_it(self): - port = free_port() - proc = run_proxy(port, base_env(self.engine_port, {"QWEN38_TLS_CERT": self.cert, + proc, port = run_proxy(base_env(self.engine_port, {"QWEN38_TLS_CERT": self.cert, "QWEN38_TLS_KEY": self.key})) try: status, body = https_post(port, "/v1/chat/completions", BODY) @@ -147,8 +133,7 @@ class TlsDoor(unittest.TestCase): proc.wait(timeout=5) def test_no_cert_named_keeps_the_plain_socket_exactly_as_before(self): - port = free_port() - proc = run_proxy(port, base_env(self.engine_port)) + proc, port = run_proxy(base_env(self.engine_port)) try: status, _ = plain_post(port, "/v1/chat/completions", BODY) self.assertEqual(status, 200) @@ -163,8 +148,7 @@ class TlsDoor(unittest.TestCase): TCP connection parked every other client until the handshake timed out. With the handshake moved into the connection thread, the silent client burns only its own thread and live clients are unaffected.""" - port = free_port() - proc = run_proxy(port, base_env(self.engine_port, + proc, port = run_proxy(base_env(self.engine_port, {"QWEN38_TLS_CERT": self.cert, "QWEN38_TLS_KEY": self.key, "QWEN38_TLS_HANDSHAKE_S": "2"})) @@ -184,14 +168,17 @@ class TlsDoor(unittest.TestCase): proc.wait(timeout=5) def test_unusable_cert_refuses_to_start(self): - port = free_port() + # port 0, the kernel's own free port: the proxy binds it and leaves before anyone connects, so + # the refusal is the certificate's, never that of a port someone else took proc = subprocess.Popen( - [sys.executable, str(REPO / "keepalive-proxy.py"), str(port)], + [sys.executable, str(REPO / "keepalive-proxy.py"), "0"], env=base_env(self.engine_port, {"QWEN38_TLS_CERT": "/nonexistent/cert.pem"}), stderr=subprocess.PIPE) rc = proc.wait(timeout=10) + err = proc.stderr.read().decode() proc.stderr.close() self.assertNotEqual(rc, 0) + self.assertIn("refusing to start: certificate /nonexistent/cert.pem is not usable", err) if __name__ == "__main__": diff --git a/tests/test_proxy_vllm_lane.py b/tests/test_proxy_vllm_lane.py index f568243f..3f88fdd7 100644 --- a/tests/test_proxy_vllm_lane.py +++ b/tests/test_proxy_vllm_lane.py @@ -31,6 +31,9 @@ import urllib.request from contextlib import redirect_stderr from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import localports # noqa: E402 + HERE = Path(__file__).resolve() KEY = "test-key-vllm-lane" METRICS = ( @@ -597,9 +600,8 @@ class ALaneSwitch(unittest.TestCase): f'if [ "$1" = show ]; then cat "{self.state}"; exit 0; fi\n' "exit 3\n") (self.t / "bin/systemctl").chmod(0o755) - with socket.socket() as sk: - sk.bind(("127.0.0.1", 0)) - self.engine_port = sk.getsockname()[1] + # the engine's port is gone until start_engine, and the test's all along: no one else can take it + _, self.engine_port = localports.held(self) saved, saved_argv = dict(os.environ), list(sys.argv) self.addCleanup(lambda: (os.environ.clear(), os.environ.update(saved), setattr(sys, "argv", saved_argv))) os.environ.update(UPSTREAM=f"http://127.0.0.1:{self.engine_port}", KEEPALIVE_S="0.4", @@ -619,7 +621,7 @@ class ALaneSwitch(unittest.TestCase): FakeVllm.bodies.clear(); FakeVllm.aborts.clear(); FakeVllm.closed_at.clear() def start_engine(self): - self.engine = http.server.ThreadingHTTPServer(("127.0.0.1", self.engine_port), FakeVllm) + self.engine = localports.serve(self.engine_port, http.server.ThreadingHTTPServer, FakeVllm) self.engine.daemon_threads = True threading.Thread(target=self.engine.serve_forever, daemon=True).start() self.addCleanup(lambda: (self.engine.shutdown(), self.engine.server_close()))