Mocking a function with a certain argument in Python
<p>I have a module a.py:</p>

<pre><code>def add(x, y):
    return x + y

def do_math(x):

    sum1 = add(x, 1)
    sum2 = add(x, 2)
    sum3 = add(x, 3)

    return sum1 + sum2 + sum3
</code></pre>

<p>Running the do_math function in a test results in the following:</p>

<pre><code>print a.do_math(1)
9
</code></pre>

<p>I want to mock the add function when y is 2.  However, the following results in an infinite loop:</p>

<pre><code>def mock_add(*args, **kwargs):
    x = args[0]
    y = args[1]
    if y == 2:
        return 4
    else:
        a.add(x, y)

with patch('a.add', side_effect=mock_add):
    a.do_math(1)
</code></pre>

<p>Here is a portion of my error message:</p>

<pre><code>  File "E:\somepath\mock-1.3.0\mock\mock.py", line 1062, in __call__
    return _mock_self._mock_call(*args, **kwargs)
  File "E:\somepath\mock-1.3.0\mock\mock.py", line 1067, in _mock_call
    self.called = True
RuntimeError: maximum recursion depth exceeded while calling a Python object
</code></pre>

<p>I should have known better.  I was already mocking add with mock_add.  Any ideas on how to do this?</p>