MagicMock With Spec

Thanks to @immoralist I’ve learned a new Python testing trick. I didn’t know about the “spec” argument for MagicMock. m(
Let’s see an example:

Here we create a mock object which mimics the interface of  SomeModel  as we would expect, returning mock values for things we access.

Let’s see what happens if we call something else:

It will fail loudly while a mock object without a spec would have returned a mock value as it did in the previous example.

But the magic doesn’t end there. You can still set additional attributes/methods “by hand” and have them not fail even if they aren’t part of the original spec.

Learning new things makes me happy. 😀

Leave a Reply

Your email address will not be published. Required fields are marked *