python函数反复调用自身_UnitTest Python模拟仅一个函数多次调用

本文介绍了如何使用Python的Mock库来模拟函数调用,特别是当需要在多个调用中控制不同行为时。通过设置side_effect属性,可以实现对特定调用返回预定义值,而其他调用则调用真实函数。示例中展示了如何让some_function在第一次和第三次调用时返回特定值,而在第二次调用时调用实际函数。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

I'm using Mock (http://www.voidspace.org.uk/python/mock/mock.html), and came across a particular mock case that I cant figure out the solution.

I have a function with multiple calls to some_function that is being Mocked.

def function():

some_function(1)

some_function(2)

some_function(3)

I only wanna mock the first and third call to some_function. The second call I wanna to be made to the real some_function.

Thanks in advance for the help.

解决方案

It seems that the wraps argument could be what you want:

wraps: Item for the mock object to wrap. If wraps is not None then calling the

Mock will pass the call through to the wrapped object (returning the

real result and ignoring return_value).

However, since you only want the second call to not be mocked, I would suggest the use of mock.side_effect.

If side_effect is an iterable then each call to the mock will return

the next value from the iterable.

If you want to return a different value for each call, it's a perfect fit :

somefunction_mock.side_effect = [10, None, 10]

Only the first and third calls to somefunction will return 10.

However, if you do need to call the real function, but not the second time, you can also pass side_effect a callable, but I find it pretty ugly (there might be a smarter to do it):

class CustomMock(object):

calls = 0

def some_function(self, arg):

calls = calls + 1

if calls != 2:

return my_real_function(arg)

else:

return DEFAULT

somefunction_mock.side_effect = CustomMock().some_function

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值