python network_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-10-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.11.x active — — —
1.12.x active — — —

Root Cause

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.

generic

中文

requests_mock.Mocker 作为上下文管理器使用,但被测客户端创建了自己的 Session(或直接使用 requests.Session()),并非挂载了适配器的那个 session。

Workarounds

  1. 94% success
    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() == []
  2. 92% success
    @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() == []

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Module-level mocker still only patches the default session; code that instantiates its own Session bypasses it.

  2. 90% fail

    Falls back to the real network, which is exactly what CI cannot access; the ConnectionError persists.