python network_error ai_generated true

requests.exceptions.ConnectionError: HTTPConnectionPool(host='api.example.com', port=80): 超过最大重试次数

requests.exceptions.ConnectionError: HTTPConnectionPool(host='api.example.com', port=80): Max retries exceeded

ID: python/pytest-requests-mock-not-active

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

版本兼容性

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

根因分析

测试使用 requests_mock 但 mock 未激活或不匹配请求。这导致尝试真实的 HTTP 请求,从而引发连接错误。

English

The test uses requests_mock but the mock is not active or does not match the request. This causes the real HTTP request to be attempted, leading to a connection error.

generic

解决方案

  1. 98% 成功率
    def test_api(requests_mock):
        requests_mock.get('http://api.example.com/data', json={'key': 'value'})
        response = requests.get('http://api.example.com/data')
        assert response.json() == {'key': 'value'}
  2. 95% 成功率
    with requests_mock.Mocker() as m:
        m.get('http://api.example.com/data', text='ok')
        requests.get('http://api.example.com/data')
  3. 90% 成功率
    Print the request URL in the test to ensure it matches the mock's URL.

无效尝试

常见但无效的做法:

  1. 90% 失败

    This makes tests flaky and dependent on external services.

  2. 95% 失败

    Mocks are synchronous; sleeping does not activate them.

  3. 80% 失败

    This prevents the error but the test still fails because the request is not mocked.