Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnitTest Python mock only one function multiple call

Tags:

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.

I tried some alternatives with http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.mock_calls, but with no success.

Thanks in advance for the help.

like image 284
bslima Avatar asked Apr 01 '13 20:04

bslima


1 Answers

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        
like image 164
Antoine Lassauzay Avatar answered Sep 27 '22 23:09

Antoine Lassauzay