0

How would I set the side effect to test a function that makes multiple calls to the same function?

The following shows and example, where call_it first calls subprocess.check_call is called first to check if the cmd exists, and if it exists it is called to execute the command.

def call_it(cmd, args):
    try:
       subprocess.check_call(
         ['which', cmd],
         stdout=subprocess.PIPE,
         stderr=subprocess.PIPE
       )
    except subprocess.CalledProcessError:
        print '%s not found'

    try:
       subprocess.check_call([cmd, args])
    except Exception as e:
        print 'Something went wrong'

How do I set the side_effect in a test such that I would trigger the exception on the second call to subprocess.check_call

First one is easy:

@mock.patch('MODULE_NAME.subprocess.check_call')
def testMultiNotPresent(self, mock_call):
    mock_call.side_effect = subprocess.CalledProcessError('foo', 'bar')
    self.assertIsNone(multiCall.call_it('echo', '-n'))
    mock_call.assert_called_once_with(['which', cmd],
     stdout=subprocess.PIPE,
     stderr=subprocess.PIPE
   )

But how about the second one?

I've tried creating multiple mocks as in:

@mock.patch('MODULE_NAME.subprocess.check_call')
@mock.patch('MODULE_NAME.subprocess.check_call')
def testMultiSomeError(self, mock_call1, mock_call_2):

but it turns out that only one of the mocks is active, i.e. call_count on the second mock is 2 and 0 for the first one.

So basically I am trying to associate the side_effect with the call

subprocess.check_call([cmd, args])

  • 1
    Assign an iterable to `side_effect`: `mock_call.side_effect = [subprocess.CalledProcessError('foo', 'bar'), 0]`, and the mock will raise on the first call, return `0` on the second. See the duplicate. – Martijn Pieters Oct 17 '16 at 13:13
  • Also, another note. You only mock patch once. – idjaw Oct 17 '16 at 13:16

0 Answers0