Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
test(ui): chat tests answer the proxied call in process; stub servers skip the fqdn lookup (#1870)
Alpamys Makazhan53fff9a9dedf
diff --git a/tests/_loopback_http.py b/tests/_loopback_http.pynew file mode 100644index 00000000..bfe32aa4--- /dev/null+++ b/tests/_loopback_http.py@@ -0,0 +1,38 @@+"""THE stub HTTP server for tests that need a real socket to talk to. One definition.++``http.server.HTTPServer.server_bind`` ends with ``self.server_name =+socket.getfqdn(host)``: a reverse lookup of the address the server was just bound+to. Nothing in a test reads ``server_name`` (the standard library uses it for the+CGI ``SERVER_NAME`` variable only), and on GitHub's ``macos-latest`` runners the+first such lookup in a process takes about 35 seconds.++Read off two green ``test (macos-latest, 3.12)`` logs of 2026-10-13 (jobs+115319900581 and 115293582800, three xdist workers each): in each of the five+workers that built a stock ``ThreadingHTTPServer``, the first test to do so took+35.1 to 35.5 s and no later one more than 2.4 s, whichever of the four files that+then used the class came first on that worker. In ``test_issue1221_*`` the test just+before it sends the same client request to a closed port, with no server, and took+0.0 s, so the wait is on the server's side, where ``getfqdn`` is the only lookup.+That is by elimination: nobody has timed the call itself on a runner.++``LoopbackHTTPServer`` is ``ThreadingHTTPServer`` without that lookup. Use it for+every stub server; ``tests/test_loopback_http.py`` fails when a test file builds the+stock class instead.+"""++from __future__ import annotations++import http.server+import socketserver+++class LoopbackHTTPServer(http.server.ThreadingHTTPServer):+ """``ThreadingHTTPServer`` whose ``server_name`` is the bound host, not its FQDN."""++ def server_bind(self) -> None:+ # Deliberately skips ``HTTPServer.server_bind``: all it adds to the+ # ``TCPServer`` one is the two attributes below and the ``getfqdn`` call.+ socketserver.TCPServer.server_bind(self)+ host, port = self.server_address[:2]+ self.server_name = host+ self.server_port = portdiff --git a/tests/test_issue1221_forge_judge_failures.py b/tests/test_issue1221_forge_judge_failures.pyindex bd5aae8b..c3c91ecb 100644--- a/tests/test_issue1221_forge_judge_failures.py+++ b/tests/test_issue1221_forge_judge_failures.py@@ -12,13 +12,14 @@ from __future__ import annotationsimport jsonimport reimport threading-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from http.server import BaseHTTPRequestHandlerfrom pathlib import Pathfrom typing import Iterator, Listimport pytestfrom typer.testing import CliRunner+from tests._loopback_http import LoopbackHTTPServerfrom tests.conftest import strip_ansi_HEALTHY_ANSWER = "Customers receive refunds within five business days."@@ -104,7 +105,7 @@ def stub_judge() -> Iterator[tuple[_StubJudge, str]]:def log_message(self, *_args) -> None:return- server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server = LoopbackHTTPServer(("127.0.0.1", 0), Handler)thread = threading.Thread(target=server.serve_forever, daemon=True)thread.start()try:diff --git a/tests/test_issue1274_augment_distill_provider_failures.py b/tests/test_issue1274_augment_distill_provider_failures.pyindex f75968d9..146bb24b 100644--- a/tests/test_issue1274_augment_distill_provider_failures.py+++ b/tests/test_issue1274_augment_distill_provider_failures.py@@ -14,13 +14,14 @@ from __future__ import annotationsimport jsonimport reimport threading-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from http.server import BaseHTTPRequestHandlerfrom pathlib import Pathfrom typing import Iterator, Listimport pytestfrom typer.testing import CliRunner+from tests._loopback_http import LoopbackHTTPServerfrom tests.conftest import strip_ansi_HEALTHY_ANSWER = "Rewritten text."@@ -72,7 +73,7 @@ def stub_judge() -> Iterator[tuple[_StubJudge, str]]:def log_message(self, *_args) -> None:return- server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server = LoopbackHTTPServer(("127.0.0.1", 0), Handler)thread = threading.Thread(target=server.serve_forever, daemon=True)thread.start()try:diff --git a/tests/test_issue204_langfuse_pull.py b/tests/test_issue204_langfuse_pull.pyindex 07398f6d..5d38d2f4 100644--- a/tests/test_issue204_langfuse_pull.py+++ b/tests/test_issue204_langfuse_pull.py@@ -40,6 +40,8 @@ from urllib.parse import parse_qs, urlsplitimport pytest+from tests._loopback_http import LoopbackHTTPServer+_PUBLIC = "pk-lf-SOUPPLANTEDPUBLIC-5b1d"_SECRET = "sk-lf-SOUPPLANTEDSECRET-9e27"_BASIC = base64.b64encode(f"{_PUBLIC}:{_SECRET}".encode()).decode()@@ -358,7 +360,7 @@ def loopback(monkeypatch):except (BrokenPipeError, ConnectionResetError):pass- server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server = LoopbackHTTPServer(("127.0.0.1", 0), Handler)server.daemon_threads = Truethread = threading.Thread(target=server.serve_forever, daemon=True)thread.start()diff --git a/tests/test_issue865_langfuse_pull_bounds.py b/tests/test_issue865_langfuse_pull_bounds.pyindex 69be5043..303f17b0 100644--- a/tests/test_issue865_langfuse_pull_bounds.py+++ b/tests/test_issue865_langfuse_pull_bounds.py@@ -26,6 +26,8 @@ from urllib.parse import parse_qs, urlsplitimport pytest+from tests._loopback_http import LoopbackHTTPServer+_PUBLIC = "pk-lf-SOUP865PUBLIC-1a2b"_SECRET = "sk-lf-SOUP865SECRET-3c4d"@@ -125,7 +127,7 @@ def drip_server(monkeypatch):except (BrokenPipeError, ConnectionResetError):pass- server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server = LoopbackHTTPServer(("127.0.0.1", 0), Handler)server.daemon_threads = Truethreading.Thread(target=server.serve_forever, daemon=True).start()try:diff --git a/tests/test_loopback_http.py b/tests/test_loopback_http.pynew file mode 100644index 00000000..f948bb1b--- /dev/null+++ b/tests/test_loopback_http.py@@ -0,0 +1,168 @@+"""``tests/_loopback_http.py``: the stub server binds without a name lookup, and is the only one.++Why the helper exists is in its docstring: on ``macos-latest`` the first stock+``ThreadingHTTPServer`` a process builds waits about 35 s in ``socket.getfqdn``. These+tests pin the two things that keep that wait out of the suite. The helper must not+look a name up, and no test file may build the stock class beside it.+"""++from __future__ import annotations++import ast+import http.server+import socket+import threading+import urllib.request+from pathlib import Path++import pytest++from tests._loopback_http import LoopbackHTTPServer++_TESTS_DIR = Path(__file__).resolve().parent+_HOME = _TESTS_DIR / "_loopback_http.py"++#: The standard-library classes whose ``server_bind`` calls ``socket.getfqdn``.+_STOCK_SERVERS = frozenset({"HTTPServer", "ThreadingHTTPServer"})++#: The only files that may name them: the helper subclasses one, and this file+#: builds one as the control below.+_MAY_NAME_THE_STOCK_CLASS = frozenset({_HOME.name, Path(__file__).name})++_LOOKUPS = ("getfqdn", "gethostbyaddr")+++class _Hello(http.server.BaseHTTPRequestHandler):+ def do_GET(self) -> None: # noqa: N802 - http.server API+ body = b"hello"+ self.send_response(200)+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *_args) -> None:+ return+++def lookups(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, str]]:+ """Every reverse lookup made while the test runs, answered without the resolver."""+ asked: list[tuple[str, str]] = []++ def answer(kind: str):+ def lookup(name: str = "", *_args):+ asked.append((kind, name))+ return name if kind == "getfqdn" else (name, [], [name])++ return lookup++ for kind in _LOOKUPS:+ monkeypatch.setattr(socket, kind, answer(kind))+ return asked+++def _stock_class_mentions(source: str) -> list[int]:+ """Lines of ``source`` whose CODE names a stock server class.++ A name, an attribute or an import alias: that covers building one, subclassing+ one and importing one. A comment or a string that mentions the class is not code.+ """+ lines = []+ for node in ast.walk(ast.parse(source)):+ if isinstance(node, ast.Name) and node.id in _STOCK_SERVERS:+ lines.append(node.lineno)+ elif isinstance(node, ast.Attribute) and node.attr in _STOCK_SERVERS:+ lines.append(node.lineno)+ elif isinstance(node, (ast.Import, ast.ImportFrom)):+ lines.extend(+ node.lineno for alias in node.names+ if alias.name.rpartition(".")[2] in _STOCK_SERVERS+ )+ return sorted(set(lines))+++class TestTheHelperLooksNothingUp:+ def test_binding_makes_no_reverse_lookup(self, lookups):+ server = LoopbackHTTPServer(("127.0.0.1", 0), _Hello)+ try:+ assert lookups == []+ assert server.server_name == "127.0.0.1"+ assert server.server_port == server.server_address[1] != 0+ finally:+ server.server_close()++ def test_control_the_stock_class_does(self, lookups):+ """The recorder sees the lookup the helper removes.++ If this one fails, ``HTTPServer.server_bind`` no longer calls ``getfqdn`` on+ this Python, and the helper has nothing left to remove.+ """+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Hello)+ try:+ assert lookups == [("getfqdn", "127.0.0.1")]+ finally:+ server.server_close()++ def test_it_still_serves_a_request(self):+ server = LoopbackHTTPServer(("127.0.0.1", 0), _Hello)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ try:+ # No proxy from the environment between the test and its own server.+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))+ url = f"http://127.0.0.1:{server.server_address[1]}/"+ with opener.open(url, timeout=10) as response:+ assert (response.status, response.read()) == (200, b"hello")+ finally:+ server.shutdown()+ server.server_close()++ def test_it_is_the_threading_server(self):+ assert issubclass(LoopbackHTTPServer, http.server.ThreadingHTTPServer)+ assert LoopbackHTTPServer.daemon_threads is True+++class TestNoTestFileBuildsTheStockServer:+ def test_only_the_helper_names_the_stock_classes(self):+ offenders = []+ for path in sorted(_TESTS_DIR.rglob("*.py")):+ if path.name in _MAY_NAME_THE_STOCK_CLASS:+ continue+ source = path.read_text(encoding="utf-8")+ if "HTTPServer" not in source: # cheap: nearly every file stops here+ continue+ offenders += [+ f"{path.relative_to(_TESTS_DIR).as_posix()}:{line}"+ for line in _stock_class_mentions(source)+ ]+ assert offenders == [], (+ "build stub servers from tests._loopback_http.LoopbackHTTPServer; the stock "+ "class waits about 35 s in socket.getfqdn on macos-latest (see that module): "+ f"{offenders}"+ )++ @pytest.mark.parametrize(+ "source",+ [+ "from http.server import ThreadingHTTPServer\n",+ "from http.server import HTTPServer as Server\n",+ "import http.server\nserver = http.server.ThreadingHTTPServer(('::1', 0), None)\n",+ "import http.server\nserver = http.server.HTTPServer(('::1', 0), None)\n",+ "import http.server\nclass Mine(http.server.ThreadingHTTPServer):\n pass\n",+ "import http.server as hs\nfactory = hs.HTTPServer\n",+ ],+ )+ def test_the_scan_sees_each_way_of_reaching_one(self, source):+ assert _stock_class_mentions(source) != []++ @pytest.mark.parametrize(+ "source",+ [+ "from tests._loopback_http import LoopbackHTTPServer\n"+ "server = LoopbackHTTPServer(('127.0.0.1', 0), None)\n",+ "# a ThreadingHTTPServer would wait in getfqdn here\n",+ "NOTE = 'HTTPServer.server_bind calls socket.getfqdn'\n",+ "import http.server\nclass Handler(http.server.BaseHTTPRequestHandler):\n pass\n",+ ],+ )+ def test_the_scan_leaves_the_helper_and_plain_mentions_alone(self, source):+ assert _stock_class_mentions(source) == []diff --git a/tests/test_ui_chat.py b/tests/test_ui_chat.pyindex ba4def78..c3fc3ef7 100644--- a/tests/test_ui_chat.py+++ b/tests/test_ui_chat.py@@ -1,9 +1,33 @@-"""Tests for Web UI Chat Upgrade — SSE proxy, SSRF validation, param bounds."""-+"""Tests for Web UI Chat Upgrade — SSE proxy, SSRF validation, param bounds.++No test in this file reaches the network. ``chat_send`` proxies an allowed request+with ``httpx.stream``, and three tests used to let that call go out for real: to+``localhost:8000``, to ``api.example.com`` and to ``127.0.0.2:8000``. The last one+took 75.3 s in each of two green ``test (macos-latest, 3.12)`` logs of 2026-10-13+(jobs 115319900581 and 115293582800). The likely reason, not read off a runner: macOS+puts 127.0.0.1 alone on ``lo0``, so a connect to another 127.x address is not refused+and waits out the default TCP connect timeout, 75 s, well inside the 120 s the+handler gives ``httpx``.++So the "allowed" tests answer the proxied call from ``upstream``, an in-process+``httpx.MockTransport``, and say which URL the request was forwarded to. The+endpoint check itself is never patched. ``refused_network`` holds for every test+here: a name lookup or a socket connect raises at once, and a test that tried one+fails with where it was going.+"""++import contextlib+import socket+import threadingfrom unittest.mock import MagicMock, patchimport pytest+_UPSTREAM_REPLY = 'data: {"choices":[{"delta":{"content":"pong"}}]}\n\ndata: [DONE]\n\n'++# What the browser receives when the proxied reply above went through `chat_send`.+_PROXIED_REPLY = 'data: {"delta": "pong"}\n\ndata: {"done": true}\n\n'+def _auth_headers():"""Return auth headers with the current UI token."""@@ -11,6 +35,115 @@ def _auth_headers():return {"Authorization": f"Bearer {get_auth_token()}"}+class _NetworkRefusedError(OSError):+ """Raised in place of a name lookup or a socket connect."""+++def _network_refused():+ """Refuse every name lookup and every socket connect; fail on exit if any was tried.++ An ``OSError``, so a client library reports it as the connection error it+ stands for and ``chat_send`` takes its real "Connection failed" branch. That+ branch swallows the exception, which is why the attempts are also counted and+ checked when the block is over. Code that asks for a refusal on purpose clears+ the list itself. ``socket.getfqdn`` swallows it too, and ``gethostbyaddr`` is+ the call it makes.++ One exemption. ``socket.socketpair`` on Windows is a listening socket and a+ ``connect`` to it on 127.0.0.1, and every event loop makes one for its+ self-pipe. The test client starts a loop per request, so a connect made inside+ ``socketpair`` goes through. It cannot leave the process. The exemption is+ per thread and ends when ``socketpair`` returns. Nowhere else does it exist:+ Linux and macOS build the pair without a connect.++ This is a helper rather than only a fixture so that the guard itself can be+ tested (``TestThisFileIsOffline``).+ """+ attempts = []+ plumbing = threading.local()+ real_socketpair = socket.socketpair+ real_connect = socket.socket.connect+ real_connect_ex = socket.socket.connect_ex++ def refuse(kind, target):+ attempts.append((kind, target))+ raise _NetworkRefusedError(f"{kind}({target!r}) refused: tests/test_ui_chat.py is offline")++ def socketpair(*args, **kwargs):+ plumbing.depth = getattr(plumbing, "depth", 0) + 1+ try:+ return real_socketpair(*args, **kwargs)+ finally:+ plumbing.depth -= 1++ def connect(sock, address):+ if getattr(plumbing, "depth", 0):+ return real_connect(sock, address)+ return refuse("connect", address)++ def connect_ex(sock, address):+ if getattr(plumbing, "depth", 0):+ return real_connect_ex(sock, address)+ return refuse("connect_ex", address)++ with pytest.MonkeyPatch.context() as monkeypatch:+ monkeypatch.setattr(socket, "socketpair", socketpair)+ monkeypatch.setattr(socket.socket, "connect", connect)+ monkeypatch.setattr(socket.socket, "connect_ex", connect_ex)+ monkeypatch.setattr(+ socket, "create_connection",+ lambda address, *_args, **_kwargs: refuse("create_connection", address),+ )+ for lookup in ("getaddrinfo", "gethostbyname", "gethostbyname_ex", "gethostbyaddr"):+ monkeypatch.setattr(+ socket, lookup,+ lambda host, *_args, _kind=lookup, **_kwargs: refuse(_kind, host),+ )+ yield attempts+ assert attempts == [], f"this test tried to reach the network: {attempts}"++[email protected](autouse=True)+def refused_network():+ """``_network_refused`` for every test in this file; yields the attempts list."""+ with _network_refused() as attempts:+ yield attempts+++class _Upstream:+ """The model server ``chat_send`` proxies to, living in this process.++ It replaces ``httpx.stream``, the one outbound call the handler makes, and+ answers from an ``httpx.MockTransport``: the handler still reads a real+ ``httpx.Response``, and no socket is opened. A request the endpoint check+ refuses never gets this far, so ``urls`` is how a test tells "allowed and+ forwarded there" from "merely not a 400".+ """++ def __init__(self, httpx):+ self._httpx = httpx+ self.urls = []++ @contextlib.contextmanager+ def stream(self, method, url, *, json, headers, timeout):+ self.urls.append(url)+ transport = self._httpx.MockTransport(+ lambda request: self._httpx.Response(200, text=_UPSTREAM_REPLY)+ )+ with self._httpx.Client(transport=transport, timeout=timeout) as client:+ with client.stream(method, url, json=json, headers=headers) as response:+ yield response+++def upstream(monkeypatch):+ httpx = pytest.importorskip("httpx")+ fake = _Upstream(httpx)+ monkeypatch.setattr(httpx, "stream", fake.stream)+ return fake++class TestChatEndpointExists:"""Test /api/chat/send endpoint registration."""@@ -51,7 +184,7 @@ class TestChatSSRFProtection:)assert response.status_code == 400- def test_allows_localhost_http(self):+ def test_allows_localhost_http(self, upstream):"""Chat endpoint should allow localhost HTTP URLs."""try:from fastapi.testclient import TestClient@@ -61,7 +194,6 @@ class TestChatSSRFProtection:from soup_cli.ui.app import create_appclient = TestClient(create_app())- # Will fail at connection level but not at validationresponse = client.post("/api/chat/send",json={@@ -70,10 +202,12 @@ class TestChatSSRFProtection:},headers=_auth_headers(),)- # Should not be 400 (SSRF rejection) — may be 502 or stream error- assert response.status_code != 400+ # Not 400 (SSRF rejection): the request went on to the model server.+ assert response.status_code == 200, response.text+ assert upstream.urls == ["http://localhost:8000/v1/chat/completions"]+ assert response.text == _PROXIED_REPLY- def test_allows_https_remote(self):+ def test_allows_https_remote(self, upstream):"""Chat endpoint should allow HTTPS remote URLs."""try:from fastapi.testclient import TestClient@@ -91,8 +225,10 @@ class TestChatSSRFProtection:},headers=_auth_headers(),)- # Should not be 400 (SSRF rejection)- assert response.status_code != 400+ # Not 400 (SSRF rejection): the request went on to the remote server.+ assert response.status_code == 200, response.text+ assert upstream.urls == ["https://api.example.com/v1/chat/completions"]+ assert response.text == _PROXIED_REPLYclass TestChatParamBounds:@@ -206,7 +342,7 @@ class TestChatInvalidScheme:)assert response.status_code == 400- def test_allows_127_loopback_range(self):+ def test_allows_127_loopback_range(self, upstream):"""Chat endpoint should allow 127.x.x.x loopback addresses."""try:from fastapi.testclient import TestClient@@ -224,8 +360,10 @@ class TestChatInvalidScheme:},headers=_auth_headers(),)- # 127.0.0.2 is loopback — should NOT be rejected as SSRF- assert response.status_code != 400+ # 127.0.0.2 is loopback — NOT rejected as SSRF, and forwarded to that host+ assert response.status_code == 200, response.text+ assert upstream.urls == ["http://127.0.0.2:8000/v1/chat/completions"]+ assert response.text == _PROXIED_REPLYdef test_rejects_file_scheme(self):"""Chat endpoint should reject file:// URLs."""@@ -326,3 +464,182 @@ class TestChatValidation:) as resp:assert resp.status_code == 200assert "text/event-stream" in resp.headers["content-type"]+++class TestThisFileIsOffline:+ """``refused_network`` has to stop what a real client does, or it proves nothing."""++ def test_a_lookup_or_a_connect_is_refused(self, refused_network):+ with pytest.raises(_NetworkRefusedError):+ socket.getaddrinfo("api.example.com", 443)+ with pytest.raises(_NetworkRefusedError):+ socket.gethostbyname("localhost")+ with pytest.raises(_NetworkRefusedError):+ socket.create_connection(("127.0.0.2", 8000), timeout=1)+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ try:+ with pytest.raises(_NetworkRefusedError):+ sock.connect(("127.0.0.2", 8000))+ with pytest.raises(_NetworkRefusedError):+ sock.connect_ex(("127.0.0.2", 8000))+ finally:+ sock.close()+ assert refused_network == [+ ("getaddrinfo", "api.example.com"),+ ("gethostbyname", "localhost"),+ ("create_connection", ("127.0.0.2", 8000)),+ ("connect", ("127.0.0.2", 8000)),+ ("connect_ex", ("127.0.0.2", 8000)),+ ]+ refused_network.clear() # asked for on purpose++ def test_control_an_unpatched_proxy_call_is_stopped_at_the_socket(self, refused_network):+ """Without ``upstream`` the real ``httpx.stream`` runs, and gets nowhere.++ This is the request that waited 75 s on macOS. If it ever passes the guard,+ the list is empty and this test says so.+ """+ try:+ from fastapi.testclient import TestClient+ except ImportError:+ pytest.skip("FastAPI not installed")++ from soup_cli.ui.app import create_app++ client = TestClient(create_app())+ response = client.post(+ "/api/chat/send",+ json={+ "messages": [{"role": "user", "content": "hi"}],+ "endpoint": "http://127.0.0.2:8000",+ },+ headers=_auth_headers(),+ )+ assert response.status_code == 200, response.text+ assert response.text == 'data: {"error": "Connection failed"}\n\n'+ assert refused_network != []+ refused_network.clear() # asked for on purpose++ def test_the_event_loop_can_still_build_its_self_pipe(self):+ """The one exemption: a ``socketpair`` is local plumbing, also on Windows."""+ left, right = socket.socketpair()+ try:+ left.sendall(b"x")+ assert right.recv(1) == b"x"+ finally:+ left.close()+ right.close()++ # What follows tests the guard itself: its teardown, its scope and its edges.+ # Every target below is local, so a guard that let a call through would fail+ # the test and still not leave the machine.++ def test_the_guard_applies_to_a_test_that_does_not_ask_for_it(self, request):+ """``autouse``: the tests above that never name the fixture are covered too."""+ assert "refused_network" in request.fixturenames++ @pytest.mark.parametrize(+ ("lookup", "args"),+ [+ ("getaddrinfo", ("localhost", 443)),+ ("gethostbyname", ("localhost",)),+ ("gethostbyname_ex", ("localhost",)),+ ("gethostbyaddr", ("127.0.0.1",)),+ ],+ )+ def test_every_name_lookup_is_refused(self, refused_network, lookup, args):+ with pytest.raises(_NetworkRefusedError):+ getattr(socket, lookup)(*args)+ assert refused_network == [(lookup, args[0])]+ refused_network.clear() # asked for on purpose++ def test_getfqdn_is_refused_through_gethostbyaddr(self, refused_network):+ """The call behind ``HTTPServer.server_bind``, which swallows the refusal.++ ``getfqdn`` falls back to the name it was given, so only the attempt log+ shows that it went to the resolver.+ """+ assert socket.getfqdn("127.0.0.1") == "127.0.0.1"+ assert refused_network == [("gethostbyaddr", "127.0.0.1")]+ refused_network.clear() # asked for on purpose++ def test_a_refusal_that_the_code_swallowed_still_fails_the_block(self):+ """The reason for the attempt list: the code under test may catch the OSError."""+ with pytest.raises(AssertionError, match=r"tried to reach the network.*getaddrinfo"):+ with _network_refused():+ with contextlib.suppress(OSError):+ socket.getaddrinfo("localhost", 443)++ def test_a_block_that_stays_offline_passes(self):+ with _network_refused() as attempts:+ pass+ assert attempts == []++ def test_the_exemption_ends_when_socketpair_returns(self, refused_network):+ """A connect after a ``socketpair`` is refused, on Windows and everywhere else.++ The target is a listener of this test's own, so a connect that got through+ would succeed at once instead of waiting on a refused port.+ """+ with socket.socket() as listener:+ listener.bind(("127.0.0.1", 0))+ listener.listen(1)+ address = listener.getsockname()+ left, right = socket.socketpair()+ left.close()+ right.close()+ with socket.socket() as client:+ with pytest.raises(_NetworkRefusedError):+ client.connect(address)+ with pytest.raises(_NetworkRefusedError):+ client.connect_ex(address)+ assert refused_network == [("connect", address), ("connect_ex", address)]+ refused_network.clear() # asked for on purpose++ def test_the_exemption_ends_when_socketpair_raises(self):+ """The same, for a ``socketpair`` that fails (no free port, out of descriptors)."""++ def failing_socketpair(*_args, **_kwargs):+ raise OSError("no socketpair")++ with pytest.MonkeyPatch.context() as monkeypatch:+ monkeypatch.setattr(socket, "socketpair", failing_socketpair)+ with _network_refused() as attempts:+ with pytest.raises(OSError, match="no socketpair"):+ socket.socketpair()+ with socket.socket() as client:+ with pytest.raises(_NetworkRefusedError):+ client.connect(("127.0.0.2", 8000))+ assert attempts == [("connect", ("127.0.0.2", 8000))]+ attempts.clear() # asked for on purpose++ def test_the_exemption_belongs_to_the_thread_inside_socketpair(self):+ """A second thread's connect is refused while the first is inside ``socketpair``.++ ``blocked_socketpair`` stands in for the real one and holds the worker+ there until the main thread has made its attempt: two events, no sleeps.+ It is installed before the guard, because the guard wraps whatever+ ``socket.socketpair`` is when it starts.+ """+ inside, release = threading.Event(), threading.Event()++ def blocked_socketpair(*_args, **_kwargs):+ inside.set()+ release.wait(timeout=10)+ return None, None++ with pytest.MonkeyPatch.context() as monkeypatch:+ monkeypatch.setattr(socket, "socketpair", blocked_socketpair)+ with _network_refused() as attempts:+ worker = threading.Thread(target=socket.socketpair)+ worker.start()+ try:+ assert inside.wait(timeout=10), "the worker never entered socketpair"+ with socket.socket() as client:+ with pytest.raises(_NetworkRefusedError):+ client.connect(("127.0.0.2", 8000))+ finally:+ release.set()+ worker.join(timeout=10)+ assert attempts == [("connect", ("127.0.0.2", 8000))]+ attempts.clear() # asked for on purpose