python
network_error
ai_generated
true
httpx.ConnectError: [Errno 111] 连接被拒绝 # 尽管使用了 respx / pytest-httpx mock
httpx.ConnectError: [Errno 111] Connection refused # despite using respx / pytest-httpx mock
ID: python/pytest-httpx-mock-not-applied
80%修复率
85%置信度
0证据数
2026-01-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 0.21 | active | — | — | — |
根因分析
HTTP 客户端在 mock 应用之前被实例化,或 mock 针对的客户端实例与被测代码使用的实例不同。
English
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.
解决方案
-
95% 成功率
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'] -
92% 成功率
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']
无效尝试
常见但无效的做法:
-
80% 失败
If the client is module-level or created earlier, the transport is already bound and the mock is bypassed.
-
95% 失败
No such env var; respx/pytest-httpx don't read it, so the real network is still used.
-
70% 失败
Fragile against httpx internal changes and misses async variants; can break unrelated tests.