I posted recently a simple introduction to the mock library. Today, I'd like to show you some of its indirect uses, that I found helpful in my everyday testing needs.
Custom patcherIt is very easy to set up mock objects to respond to events. You just access attributes and set either them or their return value. When using the patch decorator, a mock instance is provided to your test method as the last argument, so you set it up just before excercising your production code.
mock_stdin.write.return_value = "hello" # setting up mock_stdin
In this example the setting up part is really easy - just a single line. But in real-life projects, you might find yourself setting whole attribute hierarchies on mocks, repeatedly in every many test methods.
That's when a custom patcher allows you to implement the DRY principle in an elegant manner.
It's very easy to write a custom patcher.
mock_db = args[-1]
# ... perform complicated setup on mock_db
Cutting offThe cut_off patcher is useful when you need to mock out several objects, and don't care about the mock instances. Say you want to deactivate internet access in a module that uses both urllibs.
The implementation of cut_off is very simple too.
def wrapper(self, *args):
return meth(self, *args[:-len(patches)])
for obj in patches:
wrapper = mock.patch(obj)(wrapper)