Search code examples
python-2.7mockingpython-unittest

Python Mock Autospec vs Spec


Trying to wrap my head around the difference between Spec and Autospec. They seem to be about the same. Specifically, if you look at mock.patch decorator.

Can someone explain when to use which?

https://docs.python.org/3/library/unittest.mock.html


Solution

  • spec is used as a template for your Mock object. In the words of the documentation:

    If you use the spec or spec_set arguments then only magic methods that exist in the spec will be created.

    This means that you cannot call methods on the mock object that do not exist on the object you are mocking. The documentation explains this like this:

    Note If you use the spec keyword argument to create a mock then attempting to set a magic method that isn’t in the spec will raise an AttributeError.

    autospec is basically a shorthand in patch for passing in the object your patching to the spec of the MagicMock being created. Documentation:

    If you set autospec=True then the mock with be created with a spec from the object being replaced.