0

I have a retry funtion in my code.

def retry(retry_times=4, wait_time=1):
"""
Function to use as a decorator to retry any method certain number of times
:param retry_times: number of times to retry a function
:param wait_time: delay between each retry
:return: returns expected return value from the function on success else raises exception
"""
def decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        for _ in range(retry_times):
            try:
                if func(*args, **kwargs):
                    return
            except Exception as e:
                raise e
            time.sleep(secs=wait_time)
    return wrapper
return decorator

And I am using it on some function like this:-

retry(retry_times=RETRY_TIMES, wait_time=RETRY_WAIT_TIME)
def get_something(self, some_id):
    ....
    return something or raise exception( just assume)

Where RETRY_TIMES, and WAIT_TIME are some constants. Now my funtion get_something() either returns a value or raises an exception.

Now my question is that I want to write a test case to test my retry function with nose, How can I write unit test to test my retry funtion?

1 Answers1

0

Finally got the answer:- class RetryTest(BaseTestCase):

def test_retry(self):
    random_value = {'some_key': 5}

    class TestRetry:
        def __init__(self):
            self.call_count = 0

        @retry(retry_times=3, wait_time=1)
        def some_function(self):

            try:
                self.call_count += 1
                if random_value.get('non_existing_key'):
                    return True
            except KeyError:
                return False

    retry_class_object = TestRetry()
    retry_class_object.some_function()
    self.assertEqual(retry_class_object.call_count, 3)