Testing with Mock

There is a Python library called mock (by Michael Foord) that you should know about. It's small, powerful, and you need it when writing unit tests.

The library is built around the Mock class. This is an object that can take any shape you need. Its purpose is to trick the code-being-tested that it's running in a production environment, calling real functions on real objects and getting real results back. As part of the unit test's set-up, you configure a number of mocks; then you call the method that's being tested, and afterwards make assertions on the mocks, to make sure the tested method worked correctly.

When you're testing a bit of functionality, you want to keep things simple. Don't check anything else in that one unit test. Mock helps you isolate the bit of code being tested, so that it doesn't go calling on some other code, that you're not interested in checking right now.

If the code is well-factored, you will only need to mock a very few number of things in each test. Heavy mocking, and complex test set-up, is a good indicator of tightly coupled code, so doing test-driven development with mocks tends to encourage simple, straightforward interfaces between objects.

After each test there is some cleanup. Ideally, the only cleanup you need is performed automatically by the runtime: objects go out of scope and are deallocated. Sometimes you need to mock a bit of global functionality (like datetime.now()) and you want it restored; there is a handy decorator named patch, part of mock, that does this. If you find yourself doing anything more complex, something is wrong.

So I highly recommend writing unit tests with Mock. It makes testing easier and helps you spot poorly organised code.