pycon logo

PyCon 2011 Atlanta

March 9th–17th

Log in or Sign Up

Testing with mock

log in to bookmark this presentaton

Novice / Talk
March 11th 10:25 a.m. – 10:55 a.m.
mock is a Python testing library. It has the goal of making mocking in tests brain dead simple! mock provides the Mock class and the patch decorator for safely patching out the objects you are mocking in your tests. This talk will cover standard mocking patterns. We'll also look at some of the newer features in the latest release, including support for mocking magic methods.


mock provides a core Mock class that removes the need to create a host of trivial stubs throughout your test suite. After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. You can also specify return values and set specific attributes in the normal way.

The mock module also provides a patch() decorator that handles safely patching out the things you are mocking during your test.

We'll cover standard mocking patterns, and how mock makes them easy. We'll also be looking at some of the newer features in the latest release, including the magic method support that can be used (for example) for mocking out objects used as context managers.

mock is designed for "unit test style" testing, but is used with Python testing libraries like nose and py.test.

There will be some emphasis on how *not* to use mocking in testing, and why 'over mocking' is bad (and makes for brittle tests).