python network_error ai_generated true

httpx.ConnectError: [Errno -2] Name or service not known

ID: python/pytest-httpx-mock-interface-mismatch

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2025-05-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.20.x active — — —
0.21.x active — — —

Root Cause

respx/httpx mock router wasn't registered for the URL being requested, or the client instance was created before the mock was installed, so the real network call is attempted.

generic

中文

respx/httpx mock 路由未注册所请求的 URL,或客户端实例在 mock 安装之前创建,导致尝试真实网络调用。

Workarounds

  1. 93% success
    import httpx, respx
    
    @respx.mock
    def test_get():
        respx.get('https://api.example.com/users/1').mock(
            return_value=httpx.Response(200, json={'id': 1})
        )
        with httpx.Client() as c:
            r = c.get('https://api.example.com/users/1')
        assert r.json()['id'] == 1
  2. 90% success
    with respx.mock(assert_all_called=True) as router:
        router.get('https://api.example.com/').mock(return_value=httpx.Response(200))
        run_code()

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Over-broad; hides typos in URLs and returns the same mock for every request, defeating per-endpoint assertions.

  2. 80% fail

    Bypasses proxies but doesn't prevent the real DNS lookup; the error persists.