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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值