gpt4 book ai didi

python - UnitTest Python 仅模拟一个函数多次调用

转载 作者:太空狗 更新时间:2023-10-29 17:28:52 24 4
gpt4 key购买 nike

我正在使用模拟 ( http://www.voidspace.org.uk/python/mock/mock.html ),遇到了一个我无法找出解决方案的特定模拟案例。

我有一个函数多次调用 some_function 被模拟。

def function():
some_function(1)
some_function(2)
some_function(3)

我只想模拟对 some_function 的第一次和第三次调用。我想对真正的 some_function 进行第二次调用。

我用 http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.mock_calls 尝试了一些替代方案,但没有成功。

在此先感谢您的帮助。

最佳答案

wraps 参数似乎就是您想要的:

wraps: Item for the mock object to wrap. If wraps is not None then calling theMock will pass the call through to the wrapped object (returning thereal result and ignoring return_value).

但是,由于您只希望第二次调用不被模拟,我建议使用 mock.side_effect .

If side_effect is an iterable then each call to the mock will returnthe next value from the iterable.

如果你想为每个调用返回不同的值,这是一个完美的选择:

somefunction_mock.side_effect = [10, None, 10] 

只有第一次和第三次调用 somefunction 会返回 10。

然而,如果你确实需要调用真正的函数,但不是第二次,你也可以传递一个可调用的side_effect,但我觉得它很丑陋(可能会有更聪明的做法):

 class CustomMock(object):

calls = 0

def some_function(self, arg):
self.calls += 1
if self.calls != 2:
return my_real_function(arg)
else:
return DEFAULT

somefunction_mock.side_effect = CustomMock().some_function


关于python - UnitTest Python 仅模拟一个函数多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15751467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com