Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python mock patch argument `new` vs `new_callable`

Tags:

python

mocking

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

like image 266
James Lin Avatar asked Nov 20 '14 21:11

James Lin


People also ask

What is the difference between mock and patch?

Patching vs Mocking: Patching a function is adjusting it's functionality. In the context of unit testing we patch a dependency away; so we replace the dependency. Mocking is imitating. Usually we patch a function to use a mock we control instead of a dependency we don't control.

What is the difference between mock and MagicMock?

Mock vs. So what is the difference between them? MagicMock is a subclass of Mock . It contains all magic methods pre-created and ready to use (e.g. __str__ , __len__ , etc.). Therefore, you should use MagicMock when you need magic methods, and Mock if you don't need them.

Should I use mock MagicMock?

MagicMock has "default implementations of most of the magic methods.". If you don't need to test any magic methods, Mock is adequate and doesn't bring a lot of extraneous things into your tests. If you need to test a lot of magic methods MagicMock will save you some time.

What is MagicMock Python?

MagicMock. MagicMock objects provide a simple mocking interface that allows you to set the return value or other behavior of the function or object creation call that you patched. This allows you to fully define the behavior of the call and avoid creating real objects, which can be onerous.


1 Answers

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.

like image 137
chepner Avatar answered Sep 28 '22 00:09

chepner