Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test Retry functionality provided by Python

I am using the code below to perform exponential retries. I have set the reties to 5. As part of my unit test, I am mocking the response and returning status code 503. However I do not see 5 retries being performed when I use this unit test. What changes should I make to my unit test to validate that session.get has retried 5 times?

try:
    max_retries = Retry(total=retries, backoff_factor=5, status_forcelist=[500, 502, 503, 504, 429])
    self.session.mount('https://', HTTPAdapter(max_retries=max_retries))
    # Perform GET request
    response = self.session.get(url, verify=verify)
except Exception as e:
    print(f" Exception occured {e}")
return response

Unit Test

def test_my_function_retries(self):    
    responses.add(responses.GET,
                  'https://requesturl',
                  json={}, status=503)
    request.get()
like image 604
Punter Vicky Avatar asked Jul 21 '20 03:07

Punter Vicky


People also ask

How does retry work in Python?

retrying provides a decorator called retry that you can use on top of any function or method in Python to make it retry in case of failure. By default, retry calls your function endlessly until it returns rather than raising an error. This will execute the function pick_one until 1 is returned by random.

How do you test your retry logic?

One way you can test your retry logic is to disconnect your client computer from the network while the program is running. The error is: SqlException. Number = 11001.


1 Answers

I was able to use httpretty to test the retries

@httpretty.activate
def test_my_function(self):
    httpretty.register_uri(
        httpretty.GET,
        url,           
        responses=[
            httpretty.Response(
                body='{}',
                status=503,
            ),
        ]
    )

    my_class = MyClass()
    my_class.my_function()
    print(len(httpretty.latest_requests()))
like image 185
Punter Vicky Avatar answered Oct 17 '22 05:10

Punter Vicky