Last active
March 2, 2023 15:17
-
-
Save dvcolgan/39433d2de29ea1282bbecaf5afd73900 to your computer and use it in GitHub Desktop.
For the Python Tenacity library, mock the retry decorator for faster tests that don't actually wait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from tenacity import retry, stop_after_attempt, wait_exponential | |
@retry(reraise=True, stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=4, max=10)) | |
def do_something_flaky(succeed): | |
print('Doing something flaky') | |
if not succeed: | |
print('Failed!') | |
raise Exception('Failed!') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from unittest import TestCase, mock, skip | |
from main import do_something_flaky | |
class TestFlakyRetry(TestCase): | |
def test_succeeds_instantly(self): | |
try: | |
do_something_flaky(True) | |
except Exception: | |
self.fail('Flaky function should not have failed.') | |
def test_raises_exception_immediately_with_direct_mocking(self): | |
do_something_flaky.retry.sleep = mock.Mock() | |
with self.assertRaises(Exception): | |
do_something_flaky(False) | |
def test_raises_exception_immediately_with_indirect_mocking(self): | |
with mock.patch('main.do_something_flaky.retry.sleep'): | |
with self.assertRaises(Exception): | |
do_something_flaky(False) | |
@skip('Takes way too long to run!') | |
def test_raises_exception_after_full_retry_period(self): | |
with self.assertRaises(Exception): | |
do_something_flaky(False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one!