Python mock patch argument `new` vs `new_callable`

mocking, python

Solution

`new` is an actual object; `new_callable` is a callable used to create an object. The two cannot be used together (you either specify the replacement or a function to create the replacement; it's an error to use both.)

>>> foo = 6
>>> with mock.patch('__main__.foo', new=7):
...   print foo
...
7
>>> with mock.patch('__main__.foo', new_callable=lambda : 8):
...   print foo
...
8

When `new` is `mock.DEFAULT`, the mock object is a `MagicMock` instance precisely because the default value of `new_callable` is `MagicMock`.

Problem

From the documentation http://www.voidspace.org.uk/python/mock/patch.html ``` patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) ``` If new is omitted, then the target is replaced with a MagicMock. If patch is used as a decorator and new is omitted, the created mock is passed in as an extra argument to the decorated function. If patch is used as a context manager the created mock is returned by the context manager. new_callable allows you to specify a different class, or callable object, that will be called to create the new object. By default MagicMock is used. I am trying to understand the differences between the two, and what situation to use `new_callable` instead of `new`

Original source