如何解决Python mock - 修改类属性的模拟类方法
我目前有以下要测试的基本 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 调用,并使用新的 step()
函数修补原始的慢 mock_step(self)
方法。
然而,这会导致一个新问题。由于 mock_step(self)
函数不是 Mock 对象,因此我无法在其上调用任何 Mock 方法(例如 assert_call() 和 call_count()):
def test(mocker):
example = Example()
mocker.patch.object(Example,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)
example.run_steps()
assert step.call_count == 4
但后来我收到了一个不同的错误,说 mock_step() missing 1 required positional argument: 'self'
。
因此,从这个阶段开始,我不确定如何断言 step()
在 run_steps()
中恰好被调用了 4 次。
解决方法
对此有多种解决方案,最简单的可能是使用具有副作用的标准模拟:
def mock_step(self):
print("skip the wasting time")
self.steps += 1
def test_step(mocker):
example = Example()
mocked = mocker.patch.object(Example,'step')
mocked.side_effect = lambda: mock_step(example)
example.run_steps()
assert mocked.call_count == 4
side_effect
可以调用可调用对象,因此您可以同时使用标准模拟和修补方法。
import unittest.mock as mock
from functools import partial
def fake_step(self):
print("faked")
self.steps += 1
def test_api():
api = Example()
with mock.patch.object(api,attribute="step",new=partial(fake_step,self=api)):
# we need to use `partial` to emulate that a real method has its `self` parameter bound at instantiation
api.run_steps()
assert api.steps == 4
正确输出 "faked"
4 次。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。