Let's say we have some method:
def sleep(self, seconds=0):
seconds = seconds or self.wait_timer
time.sleep(seconds)
And method-caller:
def _sleep_before_next(self, number: int) -> None:
for counter, wait_timers in self.SLEEPING_RANGES.items():
if number % counter == 0:
self.sleep(random.choice(wait_timers))
I want to test that self.sleep
being called with one of wait_timers
. So possible options:
First is which I'm using now: patch random.choice
to always return first element and then use mock's assert_has_calls
.
@mock.patch('random.choice', lambda iterable: iterable[0])
@mock.patch.object(MyClass, 'sleep')
def test_sleep_before_next_calling_time_sleep_with_correct_time(self, mock_time):
self.my_class_instance._sleep_before_next(30)
assert mock_time.call_count == 3
calls = [mock.call(2), mock.call(3), mock.call(10)]
mock_time.assert_has_calls(calls, any_order=True)
Second option is to observe on random.choice
and see that needed wait_timers
were passed. Both of this options required me to mock two objects. So I wander if unittest.mock
allows to check if one of some params being passed to function to reduce number of mocks, e.g.
>>> my_mock(20)
>>> my_mock.time.assert_called_with_one_of(10, 20, 30)
>>> True
Aucun commentaire:
Enregistrer un commentaire