[Python] How to test urllib3 retry adapter for connection errors

Discussão em 'Python' iniciado por Stack, Outubro 24, 2024.

  1. Stack

    Stack Membro Participativo

    my Retry class is

    class RetryRequest:
    """
    Module for Retry logic on requests API requests
    """

    def __init__(self):
    # Retry Logic
    retry_server_errors = requests.adapters.Retry(
    total=20,
    connect=10,
    status_forcelist=list(range(500, 512)),
    status=10,
    backoff_factor=0.1,
    allowed_methods=['GET', 'PATCH', 'DELETE'],
    )
    adapter = requests.adapters.HTTPAdapter(max_retries=retry_server_errors)
    s = requests.Session()
    s.mount("https://", adapter)
    s.mount("http://", adapter)
    self.session = s


    my test is

    @patch('requests.adapters.HTTPAdapter.send', side_effect=ConnectionError)
    def test_retry_on_connection_error(mock_send):
    """
    Test to verify that the RetryRequest retries when a connection error occurs.
    """
    retry_request = RetryRequest()
    request_session = retry_request.session

    # Make the request and expect a ConnectionError
    with pytest.raises(ConnectionError):
    request_session.get('https://example.com/test')

    # Ensure that the request was retried 10 times
    assert mock_send.call_count == 10, "Expected 10 retries on connection error"


    but it only gets called once, so the retry for 10 on connect is not working

    Continue reading...

Compartilhe esta Página