我目前有以下要测试的基本 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
。我发现这样做是可能的(从这里可以看出):
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 调用的函数,并step()
用新mock_step(self)
函数修补了原来的慢速方法。
然而,这导致了一个新的问题。由于该mock_step(self)
函数不是 Mock 对象,因此我无法在其上调用任何 Mock 方法(例如 assert_call() 和 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
为了解决这个问题,我尝试mock_step
使用参数包装一个 Mock 对象wraps
:
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()
.