blob: 850a894865e2ff08f0e3961b5dfb9d9c52f0c35f [file] [log] [blame]
Michael Foord944e02d2012-03-25 23:12:55 +01001:mod:`unittest.mock` --- getting started
2========================================
3
4.. module:: unittest.mock
5 :synopsis: Mock object library.
6.. moduleauthor:: Michael Foord <michael@python.org>
7.. currentmodule:: unittest.mock
8
9.. versionadded:: 3.3
10
11
12.. _getting-started:
13
14Using Mock
15----------
16
17Mock Patching Methods
18~~~~~~~~~~~~~~~~~~~~~
19
20Common uses for :class:`Mock` objects include:
21
22* Patching methods
23* Recording method calls on objects
24
25You might want to replace a method on an object to check that
26it is called with the correct arguments by another part of the system:
27
28 >>> real = SomeClass()
29 >>> real.method = MagicMock(name='method')
30 >>> real.method(3, 4, 5, key='value')
31 <MagicMock name='method()' id='...'>
32
33Once our mock has been used (`real.method` in this example) it has methods
34and attributes that allow you to make assertions about how it has been used.
35
36.. note::
37
38 In most of these examples the :class:`Mock` and :class:`MagicMock` classes
39 are interchangeable. As the `MagicMock` is the more capable class it makes
40 a sensible one to use by default.
41
42Once the mock has been called its :attr:`~Mock.called` attribute is set to
43`True`. More importantly we can use the :meth:`~Mock.assert_called_with` or
44:meth`~Mock.assert_called_once_with` method to check that it was called with
45the correct arguments.
46
47This example tests that calling `ProductionClass().method` results in a call to
48the `something` method:
49
50 >>> class ProductionClass(object):
51 ... def method(self):
52 ... self.something(1, 2, 3)
53 ... def something(self, a, b, c):
54 ... pass
55 ...
56 >>> real = ProductionClass()
57 >>> real.something = MagicMock()
58 >>> real.method()
59 >>> real.something.assert_called_once_with(1, 2, 3)
60
61
62
63Mock for Method Calls on an Object
64~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
65
66In the last example we patched a method directly on an object to check that it
67was called correctly. Another common use case is to pass an object into a
68method (or some part of the system under test) and then check that it is used
69in the correct way.
70
71The simple `ProductionClass` below has a `closer` method. If it is called with
72an object then it calls `close` on it.
73
74 >>> class ProductionClass(object):
75 ... def closer(self, something):
76 ... something.close()
77 ...
78
79So to test it we need to pass in an object with a `close` method and check
80that it was called correctly.
81
82 >>> real = ProductionClass()
83 >>> mock = Mock()
84 >>> real.closer(mock)
85 >>> mock.close.assert_called_with()
86
87We don't have to do any work to provide the 'close' method on our mock.
88Accessing close creates it. So, if 'close' hasn't already been called then
89accessing it in the test will create it, but :meth:`~Mock.assert_called_with`
90will raise a failure exception.
91
92
93Mocking Classes
94~~~~~~~~~~~~~~~
95
96A common use case is to mock out classes instantiated by your code under test.
97When you patch a class, then that class is replaced with a mock. Instances
98are created by *calling the class*. This means you access the "mock instance"
99by looking at the return value of the mocked class.
100
101In the example below we have a function `some_function` that instantiates `Foo`
102and calls a method on it. The call to `patch` replaces the class `Foo` with a
103mock. The `Foo` instance is the result of calling the mock, so it is configured
104by modify the mock :attr:`~Mock.return_value`.
105
106 >>> def some_function():
107 ... instance = module.Foo()
108 ... return instance.method()
109 ...
110 >>> with patch('module.Foo') as mock:
111 ... instance = mock.return_value
112 ... instance.method.return_value = 'the result'
113 ... result = some_function()
114 ... assert result == 'the result'
115
116
117Naming your mocks
118~~~~~~~~~~~~~~~~~
119
120It can be useful to give your mocks a name. The name is shown in the repr of
121the mock and can be helpful when the mock appears in test failure messages. The
122name is also propagated to attributes or methods of the mock:
123
124 >>> mock = MagicMock(name='foo')
125 >>> mock
126 <MagicMock name='foo' id='...'>
127 >>> mock.method
128 <MagicMock name='foo.method' id='...'>
129
130
131Tracking all Calls
132~~~~~~~~~~~~~~~~~~
133
134Often you want to track more than a single call to a method. The
135:attr:`~Mock.mock_calls` attribute records all calls
136to child attributes of the mock - and also to their children.
137
138 >>> mock = MagicMock()
139 >>> mock.method()
140 <MagicMock name='mock.method()' id='...'>
141 >>> mock.attribute.method(10, x=53)
142 <MagicMock name='mock.attribute.method()' id='...'>
143 >>> mock.mock_calls
144 [call.method(), call.attribute.method(10, x=53)]
145
146If you make an assertion about `mock_calls` and any unexpected methods
147have been called, then the assertion will fail. This is useful because as well
148as asserting that the calls you expected have been made, you are also checking
149that they were made in the right order and with no additional calls:
150
151You use the :data:`call` object to construct lists for comparing with
152`mock_calls`:
153
154 >>> expected = [call.method(), call.attribute.method(10, x=53)]
155 >>> mock.mock_calls == expected
156 True
157
158
159Setting Return Values and Attributes
160~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
161
162Setting the return values on a mock object is trivially easy:
163
164 >>> mock = Mock()
165 >>> mock.return_value = 3
166 >>> mock()
167 3
168
169Of course you can do the same for methods on the mock:
170
171 >>> mock = Mock()
172 >>> mock.method.return_value = 3
173 >>> mock.method()
174 3
175
176The return value can also be set in the constructor:
177
178 >>> mock = Mock(return_value=3)
179 >>> mock()
180 3
181
182If you need an attribute setting on your mock, just do it:
183
184 >>> mock = Mock()
185 >>> mock.x = 3
186 >>> mock.x
187 3
188
189Sometimes you want to mock up a more complex situation, like for example
190`mock.connection.cursor().execute("SELECT 1")`. If we wanted this call to
191return a list, then we have to configure the result of the nested call.
192
193We can use :data:`call` to construct the set of calls in a "chained call" like
194this for easy assertion afterwards:
195
196 >>> mock = Mock()
197 >>> cursor = mock.connection.cursor.return_value
198 >>> cursor.execute.return_value = ['foo']
199 >>> mock.connection.cursor().execute("SELECT 1")
200 ['foo']
201 >>> expected = call.connection.cursor().execute("SELECT 1").call_list()
202 >>> mock.mock_calls
203 [call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]
204 >>> mock.mock_calls == expected
205 True
206
207It is the call to `.call_list()` that turns our call object into a list of
208calls representing the chained calls.
209
210
211Raising exceptions with mocks
212~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
213
214A useful attribute is :attr:`~Mock.side_effect`. If you set this to an
215exception class or instance then the exception will be raised when the mock
216is called.
217
218 >>> mock = Mock(side_effect=Exception('Boom!'))
219 >>> mock()
220 Traceback (most recent call last):
221 ...
222 Exception: Boom!
223
224
225Side effect functions and iterables
226~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
227
228`side_effect` can also be set to a function or an iterable. The use case for
229`side_effect` as an iterable is where your mock is going to be called several
230times, and you want each call to return a different value. When you set
231`side_effect` to an iterable every call to the mock returns the next value
232from the iterable:
233
234 >>> mock = MagicMock(side_effect=[4, 5, 6])
235 >>> mock()
236 4
237 >>> mock()
238 5
239 >>> mock()
240 6
241
242
243For more advanced use cases, like dynamically varying the return values
244depending on what the mock is called with, `side_effect` can be a function.
245The function will be called with the same arguments as the mock. Whatever the
246function returns is what the call returns:
247
248 >>> vals = {(1, 2): 1, (2, 3): 2}
249 >>> def side_effect(*args):
250 ... return vals[args]
251 ...
252 >>> mock = MagicMock(side_effect=side_effect)
253 >>> mock(1, 2)
254 1
255 >>> mock(2, 3)
256 2
257
258
259Creating a Mock from an Existing Object
260~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
261
262One problem with over use of mocking is that it couples your tests to the
263implementation of your mocks rather than your real code. Suppose you have a
264class that implements `some_method`. In a test for another class, you
265provide a mock of this object that *also* provides `some_method`. If later
266you refactor the first class, so that it no longer has `some_method` - then
267your tests will continue to pass even though your code is now broken!
268
269`Mock` allows you to provide an object as a specification for the mock,
270using the `spec` keyword argument. Accessing methods / attributes on the
271mock that don't exist on your specification object will immediately raise an
272attribute error. If you change the implementation of your specification, then
273tests that use that class will start failing immediately without you having to
274instantiate the class in those tests.
275
276 >>> mock = Mock(spec=SomeClass)
277 >>> mock.old_method()
278 Traceback (most recent call last):
279 ...
280 AttributeError: object has no attribute 'old_method'
281
282If you want a stronger form of specification that prevents the setting
283of arbitrary attributes as well as the getting of them then you can use
284`spec_set` instead of `spec`.
285
286
287
288Patch Decorators
289----------------
290
291.. note::
292
293 With `patch` it matters that you patch objects in the namespace where they
294 are looked up. This is normally straightforward, but for a quick guide
295 read :ref:`where to patch <where-to-patch>`.
296
297
298A common need in tests is to patch a class attribute or a module attribute,
299for example patching a builtin or patching a class in a module to test that it
300is instantiated. Modules and classes are effectively global, so patching on
301them has to be undone after the test or the patch will persist into other
302tests and cause hard to diagnose problems.
303
304mock provides three convenient decorators for this: `patch`, `patch.object` and
305`patch.dict`. `patch` takes a single string, of the form
306`package.module.Class.attribute` to specify the attribute you are patching. It
307also optionally takes a value that you want the attribute (or class or
308whatever) to be replaced with. 'patch.object' takes an object and the name of
309the attribute you would like patched, plus optionally the value to patch it
310with.
311
312`patch.object`:
313
314 >>> original = SomeClass.attribute
315 >>> @patch.object(SomeClass, 'attribute', sentinel.attribute)
316 ... def test():
317 ... assert SomeClass.attribute == sentinel.attribute
318 ...
319 >>> test()
320 >>> assert SomeClass.attribute == original
321
322 >>> @patch('package.module.attribute', sentinel.attribute)
323 ... def test():
324 ... from package.module import attribute
325 ... assert attribute is sentinel.attribute
326 ...
327 >>> test()
328
329If you are patching a module (including `__builtin__`) then use `patch`
330instead of `patch.object`:
331
332 >>> mock = MagicMock(return_value = sentinel.file_handle)
333 >>> with patch('__builtin__.open', mock):
334 ... handle = open('filename', 'r')
335 ...
336 >>> mock.assert_called_with('filename', 'r')
337 >>> assert handle == sentinel.file_handle, "incorrect file handle returned"
338
339The module name can be 'dotted', in the form `package.module` if needed:
340
341 >>> @patch('package.module.ClassName.attribute', sentinel.attribute)
342 ... def test():
343 ... from package.module import ClassName
344 ... assert ClassName.attribute == sentinel.attribute
345 ...
346 >>> test()
347
348A nice pattern is to actually decorate test methods themselves:
349
350 >>> class MyTest(unittest2.TestCase):
351 ... @patch.object(SomeClass, 'attribute', sentinel.attribute)
352 ... def test_something(self):
353 ... self.assertEqual(SomeClass.attribute, sentinel.attribute)
354 ...
355 >>> original = SomeClass.attribute
356 >>> MyTest('test_something').test_something()
357 >>> assert SomeClass.attribute == original
358
359If you want to patch with a Mock, you can use `patch` with only one argument
360(or `patch.object` with two arguments). The mock will be created for you and
361passed into the test function / method:
362
363 >>> class MyTest(unittest2.TestCase):
364 ... @patch.object(SomeClass, 'static_method')
365 ... def test_something(self, mock_method):
366 ... SomeClass.static_method()
367 ... mock_method.assert_called_with()
368 ...
369 >>> MyTest('test_something').test_something()
370
371You can stack up multiple patch decorators using this pattern:
372
373 >>> class MyTest(unittest2.TestCase):
374 ... @patch('package.module.ClassName1')
375 ... @patch('package.module.ClassName2')
376 ... def test_something(self, MockClass2, MockClass1):
377 ... self.assertTrue(package.module.ClassName1 is MockClass1)
378 ... self.assertTrue(package.module.ClassName2 is MockClass2)
379 ...
380 >>> MyTest('test_something').test_something()
381
382When you nest patch decorators the mocks are passed in to the decorated
383function in the same order they applied (the normal *python* order that
384decorators are applied). This means from the bottom up, so in the example
385above the mock for `test_module.ClassName2` is passed in first.
386
387There is also :func:`patch.dict` for setting values in a dictionary just
388during a scope and restoring the dictionary to its original state when the test
389ends:
390
391 >>> foo = {'key': 'value'}
392 >>> original = foo.copy()
393 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
394 ... assert foo == {'newkey': 'newvalue'}
395 ...
396 >>> assert foo == original
397
398`patch`, `patch.object` and `patch.dict` can all be used as context managers.
399
400Where you use `patch` to create a mock for you, you can get a reference to the
401mock using the "as" form of the with statement:
402
403 >>> class ProductionClass(object):
404 ... def method(self):
405 ... pass
406 ...
407 >>> with patch.object(ProductionClass, 'method') as mock_method:
408 ... mock_method.return_value = None
409 ... real = ProductionClass()
410 ... real.method(1, 2, 3)
411 ...
412 >>> mock_method.assert_called_with(1, 2, 3)
413
414
415As an alternative `patch`, `patch.object` and `patch.dict` can be used as
416class decorators. When used in this way it is the same as applying the
417decorator indvidually to every method whose name starts with "test".
418
419For some more advanced examples, see the :ref:`further-examples` page.