1 mock is a library for testing in Python. It allows you to replace parts of
2 your system under test with mock objects and make assertions about how they
5 mock is now part of the Python standard library, available as `unittest.mock <
6 http://docs.python.org/py3k/library/unittest.mock.html#module-unittest.mock>`_
9 mock provides a core `MagicMock` class removing the need to create a host of
10 stubs throughout your test suite. After performing an action, you can make
11 assertions about which methods / attributes were used and arguments they were
12 called with. You can also specify return values and set needed attributes in
15 mock is tested on Python versions 2.4-2.7 and Python 3. mock is also tested
16 with the latest versions of Jython and pypy.
18 The mock module also provides utility functions / objects to assist with
19 testing, particularly monkey patching.
21 * `PDF documentation for 1.0 beta 1
22 <http://www.voidspace.org.uk/downloads/mock-1.0.0.pdf>`_
23 * `mock on google code (repository and issue tracker)
24 <http://code.google.com/p/mock/>`_
26 <http://www.voidspace.org.uk/python/mock/>`_
27 * `mock on PyPI <http://pypi.python.org/pypi/mock/>`_
28 * `Mailing list (testing-in-python@lists.idyll.org)
29 <http://lists.idyll.org/listinfo/testing-in-python>`_
31 Mock is very easy to use and is designed for use with
32 `unittest <http://pypi.python.org/pypi/unittest2>`_. Mock is based on
33 the 'action -> assertion' pattern instead of 'record -> replay' used by many
34 mocking frameworks. See the `mock documentation`_ for full details.
36 Mock objects create all attributes and methods as you access them and store
37 details of how they have been used. You can configure them, to specify return
38 values or limit what attributes are available, and then make assertions about
39 how they have been used::
41 >>> from mock import Mock
42 >>> real = ProductionClass()
43 >>> real.method = Mock(return_value=3)
44 >>> real.method(3, 4, 5, key='value')
46 >>> real.method.assert_called_with(3, 4, 5, key='value')
48 `side_effect` allows you to perform side effects, return different values or
49 raise an exception when a mock is called::
51 >>> mock = Mock(side_effect=KeyError('foo'))
53 Traceback (most recent call last):
56 >>> values = {'a': 1, 'b': 2, 'c': 3}
57 >>> def side_effect(arg):
58 ... return values[arg]
60 >>> mock.side_effect = side_effect
61 >>> mock('a'), mock('b'), mock('c')
63 >>> mock.side_effect = [5, 4, 3, 2, 1]
64 >>> mock(), mock(), mock()
67 Mock has many other ways you can configure it and control its behaviour. For
68 example the `spec` argument configures the mock to take its specification from
69 another object. Attempting to access attributes or methods on the mock that
70 don't exist on the spec will fail with an `AttributeError`.
72 The `patch` decorator / context manager makes it easy to mock classes or
73 objects in a module under test. The object you specify will be replaced with a
74 mock (or other object) during the test and restored when the test ends::
76 >>> from mock import patch
77 >>> @patch('test_module.ClassName1')
78 ... @patch('test_module.ClassName2')
79 ... def test(MockClass2, MockClass1):
80 ... test_module.ClassName1()
81 ... test_module.ClassName2()
83 ... assert MockClass1.called
84 ... assert MockClass2.called
90 When you nest patch decorators the mocks are passed in to the decorated
91 function in the same order they applied (the normal *python* order that
92 decorators are applied). This means from the bottom up, so in the example
93 above the mock for `test_module.ClassName2` is passed in first.
95 With `patch` it matters that you patch objects in the namespace where they
96 are looked up. This is normally straightforward, but for a quick guide
98 <http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch>`_.
100 As well as a decorator `patch` can be used as a context manager in a with
103 >>> with patch.object(ProductionClass, 'method') as mock_method:
104 ... mock_method.return_value = None
105 ... real = ProductionClass()
106 ... real.method(1, 2, 3)
108 >>> mock_method.assert_called_once_with(1, 2, 3)
110 There is also `patch.dict` for setting values in a dictionary just during the
111 scope of a test and restoring the dictionary to its original state when the
114 >>> foo = {'key': 'value'}
115 >>> original = foo.copy()
116 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
117 ... assert foo == {'newkey': 'newvalue'}
119 >>> assert foo == original
121 Mock supports the mocking of Python magic methods. The easiest way of
122 using magic methods is with the `MagicMock` class. It allows you to do
125 >>> from mock import MagicMock
126 >>> mock = MagicMock()
127 >>> mock.__str__.return_value = 'foobarbaz'
130 >>> mock.__str__.assert_called_once_with()
132 Mock allows you to assign functions (or other Mock instances) to magic methods
133 and they will be called appropriately. The MagicMock class is just a Mock
134 variant that has all of the magic methods pre-created for you (well - all the
137 The following is an example of using magic methods with the ordinary Mock
140 >>> from mock import Mock
142 >>> mock.__str__ = Mock(return_value = 'wheeeeee')
146 For ensuring that the mock objects your tests use have the same api as the
147 objects they are replacing, you can use "auto-speccing". Auto-speccing can
148 be done through the `autospec` argument to patch, or the `create_autospec`
149 function. Auto-speccing creates mock objects that have the same attributes
150 and methods as the objects they are replacing, and any functions and methods
151 (including constructors) have the same call signature as the real object.
153 This ensures that your mocks will fail in the same way as your production
154 code if they are used incorrectly::
156 >>> from mock import create_autospec
157 >>> def function(a, b, c):
160 >>> mock_function = create_autospec(function, return_value='fishy')
161 >>> mock_function(1, 2, 3)
163 >>> mock_function.assert_called_once_with(1, 2, 3)
164 >>> mock_function('wrong arguments')
165 Traceback (most recent call last):
167 TypeError: <lambda>() takes exactly 3 arguments (1 given)
169 `create_autospec` can also be used on classes, where it copies the signature of
170 the `__init__` method, and on callable objects where it copies the signature of
171 the `__call__` method.
173 The distribution contains tests and documentation. The tests require
174 `unittest2 <http://pypi.python.org/pypi/unittest2>`_ to run.
176 Docs from the in-development version of `mock` can be found at
177 `mock.readthedocs.org <http://mock.readthedocs.org>`_.