python network_error ai_generated true

httpx.ConnectError: [Errno -2] 无法解析名称或服务

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2025-05-30首次发现

版本兼容性

版本状态引入弃用备注
0.20.x active — — —
0.21.x active — — —

根因分析

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

English

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

解决方案

  1. 93% 成功率
    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% 成功率
    with respx.mock(assert_all_called=True) as router:
        router.get('https://api.example.com/').mock(return_value=httpx.Response(200))
        run_code()

无效尝试

常见但无效的做法:

  1. 70% 失败

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

  2. 80% 失败

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