UnitTest Python mock only one function multiple call

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):
         self.calls += 1
         if self.calls != 2:
             return my_real_function(arg)
         else:
             return DEFAULT

somefunction_mock.side_effect = CustomMock().some_function

     

Even simpler than creating a CustomMock class :

def side_effect(*args, **kwargs):
    if side_effect.counter < 10:
        side_effect.counter += 1
        return my_real_function(arg) 
    else:
        return DEFAULT

side_effect.counter = 0
mocked_method.side_effect = side_effect