blob: 677faf9912303d8170ad5b90389b25e60f642f81 [file] [log] [blame]
Michael Foord1e68bec2012-03-03 22:24:30 +00001mock is a library for testing in Python. It allows you to replace parts of
2your system under test with mock objects and make assertions about how they
3have been used.
4
Michael Foorddc1458a2012-10-07 18:43:23 +01005mock 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>`_
Michael Foord2df66112012-10-07 18:33:12 +01007in Python 3.3 onwards.
8
Michael Foord1e68bec2012-03-03 22:24:30 +00009mock provides a core `MagicMock` class removing the need to create a host of
10stubs throughout your test suite. After performing an action, you can make
11assertions about which methods / attributes were used and arguments they were
12called with. You can also specify return values and set needed attributes in
13the normal way.
14
Michael Foord81fe9d52012-11-05 22:23:30 +000015mock is tested on Python versions 2.5-2.7 and Python 3. mock is also tested
Michael Foord1e68bec2012-03-03 22:24:30 +000016with the latest versions of Jython and pypy.
17
18The mock module also provides utility functions / objects to assist with
19testing, particularly monkey patching.
20
Michael Foord3860ed42012-11-05 21:38:05 +000021* `PDF documentation for 1.0.1
22 <http://www.voidspace.org.uk/downloads/mock-1.0.1.pdf>`_
Michael Foord1e68bec2012-03-03 22:24:30 +000023* `mock on google code (repository and issue tracker)
24 <http://code.google.com/p/mock/>`_
25* `mock documentation
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>`_
30
31Mock is very easy to use and is designed for use with
32`unittest <http://pypi.python.org/pypi/unittest2>`_. Mock is based on
33the 'action -> assertion' pattern instead of 'record -> replay' used by many
34mocking frameworks. See the `mock documentation`_ for full details.
35
36Mock objects create all attributes and methods as you access them and store
37details of how they have been used. You can configure them, to specify return
38values or limit what attributes are available, and then make assertions about
39how they have been used::
40
41 >>> from mock import Mock
42 >>> real = ProductionClass()
43 >>> real.method = Mock(return_value=3)
44 >>> real.method(3, 4, 5, key='value')
45 3
46 >>> real.method.assert_called_with(3, 4, 5, key='value')
47
48`side_effect` allows you to perform side effects, return different values or
49raise an exception when a mock is called::
50
51 >>> mock = Mock(side_effect=KeyError('foo'))
52 >>> mock()
53 Traceback (most recent call last):
54 ...
55 KeyError: 'foo'
56 >>> values = {'a': 1, 'b': 2, 'c': 3}
57 >>> def side_effect(arg):
58 ... return values[arg]
59 ...
60 >>> mock.side_effect = side_effect
61 >>> mock('a'), mock('b'), mock('c')
62 (3, 2, 1)
63 >>> mock.side_effect = [5, 4, 3, 2, 1]
64 >>> mock(), mock(), mock()
65 (5, 4, 3)
66
67Mock has many other ways you can configure it and control its behaviour. For
68example the `spec` argument configures the mock to take its specification from
69another object. Attempting to access attributes or methods on the mock that
70don't exist on the spec will fail with an `AttributeError`.
71
72The `patch` decorator / context manager makes it easy to mock classes or
73objects in a module under test. The object you specify will be replaced with a
74mock (or other object) during the test and restored when the test ends::
75
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()
82
83 ... assert MockClass1.called
84 ... assert MockClass2.called
85 ...
86 >>> test()
87
88.. note::
89
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.
94
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
97 read `where to patch
98 <http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch>`_.
99
100As well as a decorator `patch` can be used as a context manager in a with
101statement::
102
103 >>> with patch.object(ProductionClass, 'method') as mock_method:
104 ... mock_method.return_value = None
105 ... real = ProductionClass()
106 ... real.method(1, 2, 3)
107 ...
108 >>> mock_method.assert_called_once_with(1, 2, 3)
109
110There is also `patch.dict` for setting values in a dictionary just during the
111scope of a test and restoring the dictionary to its original state when the
112test ends::
113
114 >>> foo = {'key': 'value'}
115 >>> original = foo.copy()
116 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
117 ... assert foo == {'newkey': 'newvalue'}
118 ...
119 >>> assert foo == original
120
121Mock supports the mocking of Python magic methods. The easiest way of
122using magic methods is with the `MagicMock` class. It allows you to do
123things like::
124
125 >>> from mock import MagicMock
126 >>> mock = MagicMock()
127 >>> mock.__str__.return_value = 'foobarbaz'
128 >>> str(mock)
129 'foobarbaz'
130 >>> mock.__str__.assert_called_once_with()
131
132Mock allows you to assign functions (or other Mock instances) to magic methods
133and they will be called appropriately. The MagicMock class is just a Mock
134variant that has all of the magic methods pre-created for you (well - all the
135useful ones anyway).
136
137The following is an example of using magic methods with the ordinary Mock
138class::
139
140 >>> from mock import Mock
141 >>> mock = Mock()
142 >>> mock.__str__ = Mock(return_value = 'wheeeeee')
143 >>> str(mock)
144 'wheeeeee'
145
146For ensuring that the mock objects your tests use have the same api as the
147objects they are replacing, you can use "auto-speccing". Auto-speccing can
148be done through the `autospec` argument to patch, or the `create_autospec`
149function. Auto-speccing creates mock objects that have the same attributes
150and methods as the objects they are replacing, and any functions and methods
151(including constructors) have the same call signature as the real object.
152
153This ensures that your mocks will fail in the same way as your production
154code if they are used incorrectly::
155
156 >>> from mock import create_autospec
157 >>> def function(a, b, c):
158 ... pass
159 ...
160 >>> mock_function = create_autospec(function, return_value='fishy')
161 >>> mock_function(1, 2, 3)
162 'fishy'
163 >>> mock_function.assert_called_once_with(1, 2, 3)
164 >>> mock_function('wrong arguments')
165 Traceback (most recent call last):
166 ...
167 TypeError: <lambda>() takes exactly 3 arguments (1 given)
168
169`create_autospec` can also be used on classes, where it copies the signature of
170the `__init__` method, and on callable objects where it copies the signature of
171the `__call__` method.
172
173The distribution contains tests and documentation. The tests require
Michael Foordb1079532012-11-07 17:08:38 +0000174`unittest2 <http://pypi.python.org/pypi/unittest2>`_ to run on Python 2.5, 2.6
175or 3.1. For Python 2.7 and 3.2 they can be run with
176`python -m unittest discover`.
Michael Foord1e68bec2012-03-03 22:24:30 +0000177
178Docs from the in-development version of `mock` can be found at
179`mock.readthedocs.org <http://mock.readthedocs.org>`_.