0

假设我们有一些方法:

def sleep(self, seconds=0):
    seconds = seconds or self.wait_timer
    time.sleep(seconds)

和方法调用者:

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))

我想测试self.sleep被调用的wait_timers. 所以可能的选择:

首先是我现在使用的:patchrandom.choice总是返回第一个元素,然后使用 mock 的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)

第二种选择是观察random.choice并查看需要wait_timers的是否通过。这两个选项都要求我模拟两个对象。所以我徘徊是否unittest.mock允许检查是否某些参数之一被传递给函数以减少模拟数量,例如

>>> my_mock(20)
>>> my_mock.time.assert_called_with_one_of(10, 20, 30)
>>> True
4

0 回答 0