python
network_error
ai_generated
true
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.example.com', port=443): 超过最大重试次数,URL: /v1/items(由 NewConnectionError(...) 引起)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded with url: /v1/items (Caused by NewConnectionError(...))
ID: python/pytest-requests-mock-adapter-not-active
80%修复率
85%置信度
0证据数
2024-10-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.11.x | active | — | — | — |
| 1.12.x | active | — | — | — |
根因分析
requests_mock.Mocker 作为上下文管理器使用,但被测客户端创建了自己的 Session(或直接使用 requests.Session()),并非挂载了适配器的那个 session。
English
requests_mock.Mocker was used as a context manager but the client under test creates its own Session (or uses requests.Session() directly), which is not the session the adapter was mounted on.
解决方案
-
94% 成功率
import requests, requests_mock def test_fetch(): session = requests.Session() with requests_mock.Mocker(session=session) as m: m.get('https://api.example.com/v1/items', json=[]) client = MyClient(session=session) assert client.fetch_items() == [] -
92% 成功率
@pytest.fixture def mocked_session(): s = requests.Session() with requests_mock.Mocker(session=s) as m: yield s, m def test_x(mocked_session): s, m = mocked_session m.get('https://api.example.com/v1/items', json=[]) assert MyClient(session=s).fetch_items() == []
无效尝试
常见但无效的做法:
-
85% 失败
Module-level mocker still only patches the default session; code that instantiates its own Session bypasses it.
-
90% 失败
Falls back to the real network, which is exactly what CI cannot access; the ConnectionError persists.