Working Ninja
2018-07-25T21:21:23
Mock Patch Python Side Effects

Here's the most straightforward and succinct way I've found to mock patch a function that returns different (but specific) results with each call, shamelessly copied from Python Docs:

>>> values = {'a': 1, 'b': 2, 'c': 3}
>>> def side_effect(arg):
...     return values[arg]
...
>>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, 3)

And, now that we have our side_effect function defined, we can pass new values to return:

>>> mock.side_effect = [5, 4, 3, 2, 1]
>>> mock(), mock(), mock()
(5, 4, 3)

Source: https://docs.python.org/3/library/unittest.mock.html#quick-guide