Skip to content

Commit

Permalink
Replace nap.sleep with a method to allow mocking after import
Browse files Browse the repository at this point in the history
Fixes #228
  • Loading branch information
asqui committed Jun 7, 2020
1 parent 196332c commit 0cf2154
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
6 changes: 4 additions & 2 deletions tenacity/nap.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@

import time

#: Default sleep strategy.
sleep = time.sleep

def sleep(seconds):
"""Default sleep strategy. """
time.sleep(seconds)


class sleep_using_event(object):
Expand Down
37 changes: 36 additions & 1 deletion tenacity/tests/test_tenacity.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import warnings
from contextlib import contextmanager
from copy import copy
from unittest.mock import patch

import pytest

Expand Down Expand Up @@ -1441,5 +1442,39 @@ def reports_deprecation_warning():
warnings.filters = oldfilters


if __name__ == '__main__':
@patch.object(tenacity.nap.time, "sleep")
class TestMockingSleep(unittest.TestCase):
RETRY_ARGS = dict(
wait=tenacity.wait_fixed(0.1),
stop=tenacity.stop_after_attempt(5),
)

def _fail(self):
raise NotImplementedError()

@retry(**RETRY_ARGS)
def _decorated_fail(self):
self._fail()

def test_call(self, mock_sleep):
retrying = Retrying(**self.RETRY_ARGS)
with pytest.raises(RetryError):
retrying.call(self._fail)
self.assertEqual(mock_sleep.call_count, 4)

def test_decorated(self, mock_sleep):
with pytest.raises(RetryError):
self._decorated_fail()
self.assertEqual(mock_sleep.call_count, 4)

def test_decorated_retry_with(self, mock_sleep):
fail_faster = self._decorated_fail.retry_with(
stop=tenacity.stop_after_attempt(2),
)
with pytest.raises(RetryError):
fail_faster()
self.assertEqual(mock_sleep.call_count, 1)


if __name__ == "__main__":
unittest.main()

0 comments on commit 0cf2154

Please sign in to comment.