python network_error ai_generated true

httpx.ConnectError: [Errno 111] Connection refused # despite using respx / pytest-httpx mock

ID: python/pytest-httpx-mock-not-applied

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2026-01-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.21 active

Root Cause

The HTTP client was instantiated before the mock was applied, or the mock targets a different client instance than the one used by the code under test.

generic

中文

HTTP 客户端在 mock 应用之前被实例化,或 mock 针对的客户端实例与被测代码使用的实例不同。

Workarounds

  1. 95% success
    import respx, httpx
    
    def test_fetch(respx_mock):
        respx_mock.get('https://api.example.com/data').mock(
            return_value=httpx.Response(200, json={'ok': True})
        )
        client = httpx.Client()  # created after mock
        assert client.get('https://api.example.com/data').json()['ok']
  2. 92% success
    def test_fetch(httpx_mock):
        httpx_mock.add_response(json={'ok': True})
        with httpx.Client() as c:
            assert c.get('https://api.example.com/data').json()['ok']

Dead Ends

Common approaches that don't work:

  1. 80% fail

    If the client is module-level or created earlier, the transport is already bound and the mock is bypassed.

  2. 95% fail

    No such env var; respx/pytest-httpx don't read it, so the real network is still used.

  3. 70% fail

    Fragile against httpx internal changes and misses async variants; can break unrelated tests.