Mock vs MagicMock

What is the reason for plain Mock existing?

Mock’s author, Michael Foord, addressed a very similar question at Pycon 2011 (31:00):

Q: Why was MagicMock made a separate thing rather than just folding the ability into the default mock object?

A: One reasonable answer is that the way MagicMock works is that it preconfigures all these protocol methods by creating new Mocks and
setting them, so if every new mock created a bunch of new mocks and
set those as protocol methods and then all of those protocol methods
created a bunch more mocks and set them on their protocol methods,
you’ve got infinite recursion…

What if you want accessing your mock as a container object to be an
error — you don’t want that to work? If every mock has automatically
got every protocol method, then it becomes much more difficult to do
that. And also, MagicMock does some of this preconfiguring for you,
setting return values that might not be appropriate, so I thought it
would be better to have this convenience one that has everything
preconfigured and available for you, but you can also take a ordinary
mock object and just configure the magic methods you want to exist…

The simple answer is: just use MagicMock everywhere if that’s the
behavior you want.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)