【发布时间】:2021-06-02 02:21:28
【问题描述】:
我目前有以下要测试的基本 Python 类:
class Example:
def run_steps(self):
self.steps = 0
while self.steps < 4:
self.step()
def step(self):
# some expensive API call
print("wasting time...")
time.sleep(1000)
self.steps += 1
如您所见,step() 方法包含一个昂贵的 API 调用,因此我想使用另一个函数来模拟它,以避免昂贵的 API 调用但仍会递增 self.steps。我发现这样做是可能的(从here可以看出):
def mock_step(self):
print("skip the wasting time")
self.steps += 1
# This code works!
def test(mocker):
example = Example()
mocker.patch.object(Example, 'step', mock_step)
example.run_steps()
我只是创建了一个名为 mock_step(self) 的函数来避免 API 调用,并使用新的 mock_step(self) 函数修补原来的慢速 step() 方法。
但是,这会导致一个新问题。由于mock_step(self)函数不是Mock对象,我不能调用它上面的任何Mock方法(比如assert_called()和call_count()):
def test(mocker):
example = Example()
mocker.patch.object(Example, 'step', mock_step)
example.run_steps()
# this line doesn't work
assert mock_step.call_count == 4
为了解决这个问题,我尝试使用wraps 参数将mock_step 包装成一个Mock 对象:
def test(mocker):
example = Example()
# this doesn't work
step = mocker.Mock(wraps=mock_step)
mocker.patch.object(Example, 'step', step)
example.run_steps()
assert step.call_count == 4
然后我得到一个不同的错误说mock_step() missing 1 required positional argument: 'self'。
所以从这个阶段开始,我不确定如何断言 step() 在 run_steps() 中被调用了 4 次。
【问题讨论】:
标签: python unit-testing mocking python-unittest.mock pytest-mock