| Author: | Michael Foord |
|---|---|
| Version: | Mock 0.3.1 |
| Date: | 2007/12/03 |
| Homepage: | Mock Homepage |
| License: | BSD License |
| Support: | fuzzyman@voidspace.org.uk |
There are already several Python mocking libraries available, so why another one?
Most mocking libraries follow the 'record -> replay' pattern of mocking. I prefer the 'action -> assertion' pattern, which is more readable and intuitive particularly when working with the Python unittest module. For a discussion of the merits of the two approaches, see Mocking, Patching, Stubbing: all that Stuff.
mock provides a core Mock class that is intended to reduce 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 needed attributes in the normal way.
This approach is inspired by the testing patterns used at Resolver Systems.
It also provides utility functions / objects to assist with testing, particularly monkey patching.
The current version is 0.3.1, dated 3rd December 2007. Mock is still experimental. The API may change or it may never get used! If you find bugs or have suggestions for improvements / extensions then please email me.
You can checkout the latest development version from the Google Code Subversion repository with the following command:
svn checkout http://mock.googlecode.com/svn/trunk/ mock-read-only
Mock objects can be used for:
There are various ways of configuring the mock, including setting return values on the mock and its methods.
It also provides a useful sentinel object for providing unique objects in your tests:
There is also a decorator for doing module and class level patching. As modules and classes are effectively globals any patching has to be undone (or it persists into other tests). These decorators make it easier to test with module and class level patching:
If you don't want to call the decorated test function yourself, you can add apply as a decorator on top:
A nice pattern is to actually decorate test methods themselves:
If you want to patch with a Mock, you can use patch with only two arguments. The mock will be created for you and passed into the test function / method:
Mock has two optional arguments:
Mock objects are callable. The call will return the value set as the return_value attribute.
Calls made to the object will be recorded in the attributes.
The reset method resets all the call attributes on a mock object.
This can be useful where you want to make a series of assertions that reuse the same object. Note that reset also clears the return value and any child attributes. Attributes you have set using normal assignment will be left in place.
A boolean representing whether or not the mock object has been called.
Set this to configure the value returned by calling the mock.
This is either None (if the mock hasn't been called), or the arguments that the mock was last called with. This will in the form of a tuple: the first member is any ordered arguments the mock was called with (or an empty tuple) and the second member is any keyword arguments (or an empty dictionary):
This is a list of all the calls made to the mock object in sequence. Before any calls have been made it is an empty list.
As well as tracking calls to themselves, mocks also track calls to methods and attributes, and their methods and attributes:
The sentinel object provides a convenient way of providing unique objects for your tests. See Sentinel Examples.
Attributes are created on demand when you access them by name. Accessing the same attribute will always return the same object. The objects returned have a sensible repr so that test failure messages are readable.
patch decorates a function. Inside the body of the function, the target has attribute patched with a new object. When the function exits the patch is undone (which of course is done in a try-finally).
If you want to perform multiple patches then you can simply stack up the decorators on a function if you particularly feel the need.
If target is string, then patch will use it as a module name. The module is imported and the specified attribute patched with the new object. When the function exits the patch is undone (which of course is done in a try-finally). The module name can be dotted, e.g. package.module.
If new is omitted, then a new Mock instance is supplied for you.
For further examples, see the unit tests included in the full distribution.
Mock is callable. If it is called then it sets a called attribute to True.
This example tests that calling method results in a call to something:
If you want to catch the arguments then there is other information exposed:
Checking call_args_list tests how many times the mock was called, and the arguments for each call, in a single assertion.
We don't have to do any work to provide the 'close' method on our mock. Accessing close creates it. So, if 'close' hasn't already been called then accessing it in the test will create it - but called will be False.
As close is a mock object is has all the attributes from the previous example.
The disadvantage of the approach above is that all method access creates a new mock. This means that you can't tell if any methods were called that shouldn't have been. There are two ways round this. The first is by restricting the methods available on your mock.
If closer calls any methods on mock other than close, then an AttributeError will be raised.
An alternative way to verify that only the expected methods have been accessed is to use the method_calls attribute of the mock. This records all calls to child attributes of the mock - and also to their children.
This is useful if you have a mock where you expect an attribute method to be called. You could access the attribute directly, but method_calls provides a convenient way of looking at all method calls:
If you make an assertion about method_calls and any unexpected methods have been called, then the assertion will fail.
Setting the return values on a mock object is trivially easy:
Of course you can do the same for methods on the mock:
If you need an attribute setting on your mock, just do it:
Sometimes you want to mock up a more complex situation, like for example mock.connection.cursor().execute("SELECT 1"):
One problem with over use of mocking is that it couples your tests to the implementation of your mocks rather than your real code. Suppose you have a class that implements some_method. In a test for another class, you provide a mock of this object that also provides some_method. If later you refactor the first class, so that it no longer has some_method - then your tests will continue to pass even though your code is now broken!
Mock allows you to provide an object as a specification for the mock, using the spec keyword argument. Accessing methods / attributes on the mock that don't exist on your specification object will immediately raise an attribute error. If you change the implementation of your specification, then tests that use that class will start failing immediately without you having to instantiate the class in those tests.
Sometimes when testing you need to test that a specific object is passed as an argument to another method, or returned. It can be common to create named sentinel objects to test this. sentinel provides a convenient way of creating and testing the identity of objects like this.
In this example we monkey patch method to return sentinel.ReturnValue. We want to test that this is the value returned when we call something.
A common need in tests is to patch a class attribute or a module attribute, for example patching a builtin or patching a class in a module to test that it is instantiated. Modules and classes are effectively global, so patching on them has to be undone after the test or the patch will persist into other tests and cause hard to diagnose problems.
The patch provides a convenient way of doing this.
The decorator is applied to a function (called test above). The patching only applies inside the body of the function. You have to call the function explicitly, this can be useful as the test function can take arguments and be used to implement several tests, it can also return values.
They can be stacked to perform multiple simultaneous patches:
If you are patching a module (including __builtin__) then supply a module name instead of an object to patch:
The module name can be 'dotted', in the form package.module if needed.
If you don't want to call the decorated test function yourself, you can add apply as a decorator on top:
A nice pattern is to actually decorate test methods themselves:
If you omit the third argument to patch then the attribute will be patched with a mock for you. The mock will be passed in as extra argument(s) to the function / method under test:
You can stack up multiple patch decorators using this pattern:
There are various disadvantages and things that Mock doesn't (yet) do.
patch maintains the name of decorated functions for compatibility with nose test autodiscovery.
Tests decorated with path that use the two argument form (implicit mock creation) will receive the mock(s) passed in as extra arguments.
Thanks to Kevin Dangoor for these changes.
Removed patch_module. patch can now take a string as the first argument for patching modules.
The third argument to patch is optional - a mock will be created by default if it is not passed in.
Bug fix, allows reuse of functions decorated with patch and patch_module.
Added spec keyword argument for creating Mock objects from a specification object.
Added patch and patch_module monkey patching decorators.
Added sentinel for convenient access to unique objects.
Distribution includes unit tests.
Initial release.