I am mocking (using python Mock) a function where I want to return a list of values, but in some of the items in the list I want a side effect to also occur (at the point where the mocked function is called). How is this most easily done? I'm trying something like this:
import mock import socket def oddConnect(): result = mock.MagicMock() # this is where the return value would go raise socket.error # I want it assigned but also this raised socket.create_connection = mock(spec=socket.create_connection, side_effect=[oddConnect, oddConnect, mock.MagicMock(),]) # what I want: call my function twice, and on the third time return normally # what I get: two function objects returned and then the normal return for _ in xrange(3): result = None try: # this is the context in which I want the oddConnect function call # to be called (not above when creating the list) result = socket.create_connection() except socket.error: if result is not None: # I should get here twice result.close() result = None if result is not None: # happy days we have a connection # I should get here the third time pass The except clause (and it's internal if) I copied from the internals of socket and want to verify that I "test" that path through my copy of the code. (I don't understand how socket can get to that code (setting the target while still raising an exception, but that isn't my concern, only the I verify that I can replicate that code path.) That's why I want the side effect to happen when the mock is called and not when I build the list.