blob: 60db4c2ba4dacdf344e0a5e788dd5bb17bfc6fd5 [file] [log] [blame]
Michael Foorda9e6fb22012-03-28 14:36:02 +01001:mod:`unittest.mock` --- getting started
2========================================
Michael Foord944e02d2012-03-25 23:12:55 +01003
Michael Foord944e02d2012-03-25 23:12:55 +01004.. moduleauthor:: Michael Foord <michael@python.org>
5.. currentmodule:: unittest.mock
6
7.. versionadded:: 3.3
8
9
Michael Foorda9e6fb22012-03-28 14:36:02 +010010.. _getting-started:
11
Stéphane Wirtel859c0682018-10-12 09:51:05 +020012
13.. testsetup::
14
15 import unittest
16 from unittest.mock import Mock, MagicMock, patch, call, sentinel
17
18 class SomeClass:
19 attribute = 'this is a doctest'
20
21 @staticmethod
22 def static_method():
23 pass
24
Michael Foorda9e6fb22012-03-28 14:36:02 +010025Using Mock
26----------
27
28Mock Patching Methods
29~~~~~~~~~~~~~~~~~~~~~
30
31Common uses for :class:`Mock` objects include:
32
33* Patching methods
34* Recording method calls on objects
35
36You might want to replace a method on an object to check that
37it is called with the correct arguments by another part of the system:
38
39 >>> real = SomeClass()
40 >>> real.method = MagicMock(name='method')
41 >>> real.method(3, 4, 5, key='value')
42 <MagicMock name='method()' id='...'>
43
Georg Brandl7ad3df62014-10-31 07:59:37 +010044Once our mock has been used (``real.method`` in this example) it has methods
Michael Foorda9e6fb22012-03-28 14:36:02 +010045and attributes that allow you to make assertions about how it has been used.
46
47.. note::
48
49 In most of these examples the :class:`Mock` and :class:`MagicMock` classes
Georg Brandl7ad3df62014-10-31 07:59:37 +010050 are interchangeable. As the ``MagicMock`` is the more capable class it makes
Michael Foorda9e6fb22012-03-28 14:36:02 +010051 a sensible one to use by default.
52
53Once the mock has been called its :attr:`~Mock.called` attribute is set to
Georg Brandl7ad3df62014-10-31 07:59:37 +010054``True``. More importantly we can use the :meth:`~Mock.assert_called_with` or
Georg Brandl24891672012-04-01 13:48:26 +020055:meth:`~Mock.assert_called_once_with` method to check that it was called with
Michael Foorda9e6fb22012-03-28 14:36:02 +010056the correct arguments.
57
Georg Brandl7ad3df62014-10-31 07:59:37 +010058This example tests that calling ``ProductionClass().method`` results in a call to
59the ``something`` method:
Michael Foorda9e6fb22012-03-28 14:36:02 +010060
Ezio Melottic9cfcf12013-03-11 09:42:40 +020061 >>> class ProductionClass:
Michael Foorda9e6fb22012-03-28 14:36:02 +010062 ... def method(self):
63 ... self.something(1, 2, 3)
64 ... def something(self, a, b, c):
65 ... pass
66 ...
67 >>> real = ProductionClass()
68 >>> real.something = MagicMock()
69 >>> real.method()
70 >>> real.something.assert_called_once_with(1, 2, 3)
71
72
73
74Mock for Method Calls on an Object
75~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
76
77In the last example we patched a method directly on an object to check that it
78was called correctly. Another common use case is to pass an object into a
79method (or some part of the system under test) and then check that it is used
80in the correct way.
81
Georg Brandl7ad3df62014-10-31 07:59:37 +010082The simple ``ProductionClass`` below has a ``closer`` method. If it is called with
83an object then it calls ``close`` on it.
Michael Foorda9e6fb22012-03-28 14:36:02 +010084
Ezio Melottic9cfcf12013-03-11 09:42:40 +020085 >>> class ProductionClass:
Michael Foorda9e6fb22012-03-28 14:36:02 +010086 ... def closer(self, something):
87 ... something.close()
88 ...
89
Georg Brandl7ad3df62014-10-31 07:59:37 +010090So to test it we need to pass in an object with a ``close`` method and check
Michael Foorda9e6fb22012-03-28 14:36:02 +010091that it was called correctly.
92
93 >>> real = ProductionClass()
94 >>> mock = Mock()
95 >>> real.closer(mock)
96 >>> mock.close.assert_called_with()
97
98We don't have to do any work to provide the 'close' method on our mock.
99Accessing close creates it. So, if 'close' hasn't already been called then
100accessing it in the test will create it, but :meth:`~Mock.assert_called_with`
101will raise a failure exception.
102
103
104Mocking Classes
105~~~~~~~~~~~~~~~
106
107A common use case is to mock out classes instantiated by your code under test.
108When you patch a class, then that class is replaced with a mock. Instances
109are created by *calling the class*. This means you access the "mock instance"
110by looking at the return value of the mocked class.
111
Georg Brandl7ad3df62014-10-31 07:59:37 +0100112In the example below we have a function ``some_function`` that instantiates ``Foo``
113and calls a method on it. The call to :func:`patch` replaces the class ``Foo`` with a
114mock. The ``Foo`` instance is the result of calling the mock, so it is configured
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200115by modifying the mock :attr:`~Mock.return_value`. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +0100116
117 >>> def some_function():
118 ... instance = module.Foo()
119 ... return instance.method()
120 ...
121 >>> with patch('module.Foo') as mock:
122 ... instance = mock.return_value
123 ... instance.method.return_value = 'the result'
124 ... result = some_function()
125 ... assert result == 'the result'
126
127
128Naming your mocks
129~~~~~~~~~~~~~~~~~
130
131It can be useful to give your mocks a name. The name is shown in the repr of
132the mock and can be helpful when the mock appears in test failure messages. The
133name is also propagated to attributes or methods of the mock:
134
135 >>> mock = MagicMock(name='foo')
136 >>> mock
137 <MagicMock name='foo' id='...'>
138 >>> mock.method
139 <MagicMock name='foo.method' id='...'>
140
141
142Tracking all Calls
143~~~~~~~~~~~~~~~~~~
144
145Often you want to track more than a single call to a method. The
146:attr:`~Mock.mock_calls` attribute records all calls
147to child attributes of the mock - and also to their children.
148
149 >>> mock = MagicMock()
150 >>> mock.method()
151 <MagicMock name='mock.method()' id='...'>
152 >>> mock.attribute.method(10, x=53)
153 <MagicMock name='mock.attribute.method()' id='...'>
154 >>> mock.mock_calls
155 [call.method(), call.attribute.method(10, x=53)]
156
Georg Brandl7ad3df62014-10-31 07:59:37 +0100157If you make an assertion about ``mock_calls`` and any unexpected methods
Michael Foorda9e6fb22012-03-28 14:36:02 +0100158have been called, then the assertion will fail. This is useful because as well
159as asserting that the calls you expected have been made, you are also checking
160that they were made in the right order and with no additional calls:
161
162You use the :data:`call` object to construct lists for comparing with
Georg Brandl7ad3df62014-10-31 07:59:37 +0100163``mock_calls``:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100164
165 >>> expected = [call.method(), call.attribute.method(10, x=53)]
166 >>> mock.mock_calls == expected
167 True
168
169
170Setting Return Values and Attributes
171~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
172
173Setting the return values on a mock object is trivially easy:
174
175 >>> mock = Mock()
176 >>> mock.return_value = 3
177 >>> mock()
178 3
179
180Of course you can do the same for methods on the mock:
181
182 >>> mock = Mock()
183 >>> mock.method.return_value = 3
184 >>> mock.method()
185 3
186
187The return value can also be set in the constructor:
188
189 >>> mock = Mock(return_value=3)
190 >>> mock()
191 3
192
193If you need an attribute setting on your mock, just do it:
194
195 >>> mock = Mock()
196 >>> mock.x = 3
197 >>> mock.x
198 3
199
200Sometimes you want to mock up a more complex situation, like for example
Georg Brandl7ad3df62014-10-31 07:59:37 +0100201``mock.connection.cursor().execute("SELECT 1")``. If we wanted this call to
Michael Foorda9e6fb22012-03-28 14:36:02 +0100202return a list, then we have to configure the result of the nested call.
203
204We can use :data:`call` to construct the set of calls in a "chained call" like
205this for easy assertion afterwards:
206
207 >>> mock = Mock()
208 >>> cursor = mock.connection.cursor.return_value
209 >>> cursor.execute.return_value = ['foo']
210 >>> mock.connection.cursor().execute("SELECT 1")
211 ['foo']
212 >>> expected = call.connection.cursor().execute("SELECT 1").call_list()
213 >>> mock.mock_calls
214 [call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]
215 >>> mock.mock_calls == expected
216 True
217
Georg Brandl7ad3df62014-10-31 07:59:37 +0100218It is the call to ``.call_list()`` that turns our call object into a list of
Michael Foorda9e6fb22012-03-28 14:36:02 +0100219calls representing the chained calls.
220
221
222Raising exceptions with mocks
223~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
224
225A useful attribute is :attr:`~Mock.side_effect`. If you set this to an
226exception class or instance then the exception will be raised when the mock
227is called.
228
229 >>> mock = Mock(side_effect=Exception('Boom!'))
230 >>> mock()
231 Traceback (most recent call last):
232 ...
233 Exception: Boom!
234
235
236Side effect functions and iterables
237~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
238
Georg Brandl7ad3df62014-10-31 07:59:37 +0100239``side_effect`` can also be set to a function or an iterable. The use case for
240``side_effect`` as an iterable is where your mock is going to be called several
Michael Foorda9e6fb22012-03-28 14:36:02 +0100241times, and you want each call to return a different value. When you set
Georg Brandl7ad3df62014-10-31 07:59:37 +0100242``side_effect`` to an iterable every call to the mock returns the next value
Michael Foorda9e6fb22012-03-28 14:36:02 +0100243from the iterable:
244
245 >>> mock = MagicMock(side_effect=[4, 5, 6])
246 >>> mock()
247 4
248 >>> mock()
249 5
250 >>> mock()
251 6
252
253
254For more advanced use cases, like dynamically varying the return values
Georg Brandl7ad3df62014-10-31 07:59:37 +0100255depending on what the mock is called with, ``side_effect`` can be a function.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100256The function will be called with the same arguments as the mock. Whatever the
257function returns is what the call returns:
258
259 >>> vals = {(1, 2): 1, (2, 3): 2}
260 >>> def side_effect(*args):
261 ... return vals[args]
262 ...
263 >>> mock = MagicMock(side_effect=side_effect)
264 >>> mock(1, 2)
265 1
266 >>> mock(2, 3)
267 2
268
269
270Creating a Mock from an Existing Object
271~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
272
273One problem with over use of mocking is that it couples your tests to the
274implementation of your mocks rather than your real code. Suppose you have a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100275class that implements ``some_method``. In a test for another class, you
276provide a mock of this object that *also* provides ``some_method``. If later
277you refactor the first class, so that it no longer has ``some_method`` - then
Michael Foorda9e6fb22012-03-28 14:36:02 +0100278your tests will continue to pass even though your code is now broken!
279
Georg Brandl7ad3df62014-10-31 07:59:37 +0100280:class:`Mock` allows you to provide an object as a specification for the mock,
281using the *spec* keyword argument. Accessing methods / attributes on the
Michael Foorda9e6fb22012-03-28 14:36:02 +0100282mock that don't exist on your specification object will immediately raise an
283attribute error. If you change the implementation of your specification, then
284tests that use that class will start failing immediately without you having to
285instantiate the class in those tests.
286
287 >>> mock = Mock(spec=SomeClass)
288 >>> mock.old_method()
289 Traceback (most recent call last):
290 ...
291 AttributeError: object has no attribute 'old_method'
292
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100293Using a specification also enables a smarter matching of calls made to the
294mock, regardless of whether some parameters were passed as positional or
295named arguments::
296
297 >>> def f(a, b, c): pass
298 ...
299 >>> mock = Mock(spec=f)
300 >>> mock(1, 2, 3)
301 <Mock name='mock()' id='140161580456576'>
302 >>> mock.assert_called_with(a=1, b=2, c=3)
303
304If you want this smarter matching to also work with method calls on the mock,
305you can use :ref:`auto-speccing <auto-speccing>`.
306
Michael Foorda9e6fb22012-03-28 14:36:02 +0100307If you want a stronger form of specification that prevents the setting
308of arbitrary attributes as well as the getting of them then you can use
Georg Brandl7ad3df62014-10-31 07:59:37 +0100309*spec_set* instead of *spec*.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100310
311
312
313Patch Decorators
314----------------
315
316.. note::
317
Georg Brandl7ad3df62014-10-31 07:59:37 +0100318 With :func:`patch` it matters that you patch objects in the namespace where
319 they are looked up. This is normally straightforward, but for a quick guide
Michael Foorda9e6fb22012-03-28 14:36:02 +0100320 read :ref:`where to patch <where-to-patch>`.
321
322
323A common need in tests is to patch a class attribute or a module attribute,
324for example patching a builtin or patching a class in a module to test that it
325is instantiated. Modules and classes are effectively global, so patching on
326them has to be undone after the test or the patch will persist into other
327tests and cause hard to diagnose problems.
328
Georg Brandl7ad3df62014-10-31 07:59:37 +0100329mock provides three convenient decorators for this: :func:`patch`, :func:`patch.object` and
330:func:`patch.dict`. ``patch`` takes a single string, of the form
331``package.module.Class.attribute`` to specify the attribute you are patching. It
Michael Foorda9e6fb22012-03-28 14:36:02 +0100332also optionally takes a value that you want the attribute (or class or
333whatever) to be replaced with. 'patch.object' takes an object and the name of
334the attribute you would like patched, plus optionally the value to patch it
335with.
336
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200337``patch.object``::
Michael Foorda9e6fb22012-03-28 14:36:02 +0100338
339 >>> original = SomeClass.attribute
340 >>> @patch.object(SomeClass, 'attribute', sentinel.attribute)
341 ... def test():
342 ... assert SomeClass.attribute == sentinel.attribute
343 ...
344 >>> test()
345 >>> assert SomeClass.attribute == original
346
347 >>> @patch('package.module.attribute', sentinel.attribute)
348 ... def test():
349 ... from package.module import attribute
350 ... assert attribute is sentinel.attribute
351 ...
352 >>> test()
353
Georg Brandl7ad3df62014-10-31 07:59:37 +0100354If you are patching a module (including :mod:`builtins`) then use :func:`patch`
355instead of :func:`patch.object`:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100356
Ezio Melottib40a2202013-03-30 05:55:52 +0200357 >>> mock = MagicMock(return_value=sentinel.file_handle)
358 >>> with patch('builtins.open', mock):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100359 ... handle = open('filename', 'r')
360 ...
361 >>> mock.assert_called_with('filename', 'r')
362 >>> assert handle == sentinel.file_handle, "incorrect file handle returned"
363
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200364The module name can be 'dotted', in the form ``package.module`` if needed::
Michael Foorda9e6fb22012-03-28 14:36:02 +0100365
366 >>> @patch('package.module.ClassName.attribute', sentinel.attribute)
367 ... def test():
368 ... from package.module import ClassName
369 ... assert ClassName.attribute == sentinel.attribute
370 ...
371 >>> test()
372
373A nice pattern is to actually decorate test methods themselves:
374
Berker Peksagb31daff2016-04-02 04:32:06 +0300375 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100376 ... @patch.object(SomeClass, 'attribute', sentinel.attribute)
377 ... def test_something(self):
378 ... self.assertEqual(SomeClass.attribute, sentinel.attribute)
379 ...
380 >>> original = SomeClass.attribute
381 >>> MyTest('test_something').test_something()
382 >>> assert SomeClass.attribute == original
383
Georg Brandl7ad3df62014-10-31 07:59:37 +0100384If you want to patch with a Mock, you can use :func:`patch` with only one argument
385(or :func:`patch.object` with two arguments). The mock will be created for you and
Michael Foorda9e6fb22012-03-28 14:36:02 +0100386passed into the test function / method:
387
Berker Peksagb31daff2016-04-02 04:32:06 +0300388 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100389 ... @patch.object(SomeClass, 'static_method')
390 ... def test_something(self, mock_method):
391 ... SomeClass.static_method()
392 ... mock_method.assert_called_with()
393 ...
394 >>> MyTest('test_something').test_something()
395
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200396You can stack up multiple patch decorators using this pattern::
Michael Foorda9e6fb22012-03-28 14:36:02 +0100397
Berker Peksagb31daff2016-04-02 04:32:06 +0300398 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100399 ... @patch('package.module.ClassName1')
400 ... @patch('package.module.ClassName2')
401 ... def test_something(self, MockClass2, MockClass1):
Ezio Melottie2123702013-01-10 03:43:33 +0200402 ... self.assertIs(package.module.ClassName1, MockClass1)
403 ... self.assertIs(package.module.ClassName2, MockClass2)
Michael Foorda9e6fb22012-03-28 14:36:02 +0100404 ...
405 >>> MyTest('test_something').test_something()
406
407When you nest patch decorators the mocks are passed in to the decorated
Andrés Delfino271818f2018-09-14 14:13:09 -0300408function in the same order they applied (the normal *Python* order that
Michael Foorda9e6fb22012-03-28 14:36:02 +0100409decorators are applied). This means from the bottom up, so in the example
Georg Brandl7ad3df62014-10-31 07:59:37 +0100410above the mock for ``test_module.ClassName2`` is passed in first.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100411
412There is also :func:`patch.dict` for setting values in a dictionary just
413during a scope and restoring the dictionary to its original state when the test
414ends:
415
416 >>> foo = {'key': 'value'}
417 >>> original = foo.copy()
418 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
419 ... assert foo == {'newkey': 'newvalue'}
420 ...
421 >>> assert foo == original
422
Georg Brandl7ad3df62014-10-31 07:59:37 +0100423``patch``, ``patch.object`` and ``patch.dict`` can all be used as context managers.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100424
Georg Brandl7ad3df62014-10-31 07:59:37 +0100425Where you use :func:`patch` to create a mock for you, you can get a reference to the
Michael Foorda9e6fb22012-03-28 14:36:02 +0100426mock using the "as" form of the with statement:
427
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200428 >>> class ProductionClass:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100429 ... def method(self):
430 ... pass
431 ...
432 >>> with patch.object(ProductionClass, 'method') as mock_method:
433 ... mock_method.return_value = None
434 ... real = ProductionClass()
435 ... real.method(1, 2, 3)
436 ...
437 >>> mock_method.assert_called_with(1, 2, 3)
438
439
Georg Brandl7ad3df62014-10-31 07:59:37 +0100440As an alternative ``patch``, ``patch.object`` and ``patch.dict`` can be used as
Michael Foorda9e6fb22012-03-28 14:36:02 +0100441class decorators. When used in this way it is the same as applying the
Larry Hastings3732ed22014-03-15 21:13:56 -0700442decorator individually to every method whose name starts with "test".
Michael Foorda9e6fb22012-03-28 14:36:02 +0100443
444
445.. _further-examples:
446
447Further Examples
Georg Brandl7fc972a2013-02-03 14:00:04 +0100448----------------
Michael Foorda9e6fb22012-03-28 14:36:02 +0100449
450
451Here are some more examples for some slightly more advanced scenarios.
Michael Foord944e02d2012-03-25 23:12:55 +0100452
453
454Mocking chained calls
Georg Brandl7fc972a2013-02-03 14:00:04 +0100455~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100456
457Mocking chained calls is actually straightforward with mock once you
458understand the :attr:`~Mock.return_value` attribute. When a mock is called for
Georg Brandl7ad3df62014-10-31 07:59:37 +0100459the first time, or you fetch its ``return_value`` before it has been called, a
460new :class:`Mock` is created.
Michael Foord944e02d2012-03-25 23:12:55 +0100461
462This means that you can see how the object returned from a call to a mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +0100463object has been used by interrogating the ``return_value`` mock:
Michael Foord944e02d2012-03-25 23:12:55 +0100464
465 >>> mock = Mock()
466 >>> mock().foo(a=2, b=3)
467 <Mock name='mock().foo()' id='...'>
468 >>> mock.return_value.foo.assert_called_with(a=2, b=3)
469
470From here it is a simple step to configure and then make assertions about
471chained calls. Of course another alternative is writing your code in a more
472testable way in the first place...
473
474So, suppose we have some code that looks a little bit like this:
475
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200476 >>> class Something:
Michael Foord944e02d2012-03-25 23:12:55 +0100477 ... def __init__(self):
478 ... self.backend = BackendProvider()
479 ... def method(self):
480 ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
481 ... # more code
482
Georg Brandl7ad3df62014-10-31 07:59:37 +0100483Assuming that ``BackendProvider`` is already well tested, how do we test
484``method()``? Specifically, we want to test that the code section ``# more
485code`` uses the response object in the correct way.
Michael Foord944e02d2012-03-25 23:12:55 +0100486
487As this chain of calls is made from an instance attribute we can monkey patch
Georg Brandl7ad3df62014-10-31 07:59:37 +0100488the ``backend`` attribute on a ``Something`` instance. In this particular case
Michael Foord944e02d2012-03-25 23:12:55 +0100489we are only interested in the return value from the final call to
Georg Brandl7ad3df62014-10-31 07:59:37 +0100490``start_call`` so we don't have much configuration to do. Let's assume the
Michael Foord944e02d2012-03-25 23:12:55 +0100491object it returns is 'file-like', so we'll ensure that our response object
Georg Brandl7ad3df62014-10-31 07:59:37 +0100492uses the builtin :func:`open` as its ``spec``.
Michael Foord944e02d2012-03-25 23:12:55 +0100493
494To do this we create a mock instance as our mock backend and create a mock
495response object for it. To set the response as the return value for that final
Georg Brandl7ad3df62014-10-31 07:59:37 +0100496``start_call`` we could do this::
Michael Foord944e02d2012-03-25 23:12:55 +0100497
Georg Brandl7ad3df62014-10-31 07:59:37 +0100498 mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response
Michael Foord944e02d2012-03-25 23:12:55 +0100499
500We can do that in a slightly nicer way using the :meth:`~Mock.configure_mock`
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200501method to directly set the return value for us::
Michael Foord944e02d2012-03-25 23:12:55 +0100502
503 >>> something = Something()
Terry Jan Reedy30ffe7e2014-01-21 00:01:51 -0500504 >>> mock_response = Mock(spec=open)
Michael Foord944e02d2012-03-25 23:12:55 +0100505 >>> mock_backend = Mock()
506 >>> config = {'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response}
507 >>> mock_backend.configure_mock(**config)
508
509With these we monkey patch the "mock backend" in place and can make the real
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200510call::
Michael Foord944e02d2012-03-25 23:12:55 +0100511
512 >>> something.backend = mock_backend
513 >>> something.method()
514
515Using :attr:`~Mock.mock_calls` we can check the chained call with a single
516assert. A chained call is several calls in one line of code, so there will be
Georg Brandl7ad3df62014-10-31 07:59:37 +0100517several entries in ``mock_calls``. We can use :meth:`call.call_list` to create
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200518this list of calls for us::
Michael Foord944e02d2012-03-25 23:12:55 +0100519
520 >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
521 >>> call_list = chained.call_list()
522 >>> assert mock_backend.mock_calls == call_list
523
524
525Partial mocking
Georg Brandl7fc972a2013-02-03 14:00:04 +0100526~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100527
Georg Brandl7ad3df62014-10-31 07:59:37 +0100528In some tests I wanted to mock out a call to :meth:`datetime.date.today`
Georg Brandl728e4de2014-10-29 09:00:30 +0100529to return a known date, but I didn't want to prevent the code under test from
Georg Brandl7ad3df62014-10-31 07:59:37 +0100530creating new date objects. Unfortunately :class:`datetime.date` is written in C, and
531so I couldn't just monkey-patch out the static :meth:`date.today` method.
Michael Foord944e02d2012-03-25 23:12:55 +0100532
533I found a simple way of doing this that involved effectively wrapping the date
534class with a mock, but passing through calls to the constructor to the real
535class (and returning real instances).
536
537The :func:`patch decorator <patch>` is used here to
Georg Brandl7ad3df62014-10-31 07:59:37 +0100538mock out the ``date`` class in the module under test. The :attr:`side_effect`
Michael Foord944e02d2012-03-25 23:12:55 +0100539attribute on the mock date class is then set to a lambda function that returns
540a real date. When the mock date class is called a real date will be
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200541constructed and returned by ``side_effect``. ::
Michael Foord944e02d2012-03-25 23:12:55 +0100542
543 >>> from datetime import date
544 >>> with patch('mymodule.date') as mock_date:
545 ... mock_date.today.return_value = date(2010, 10, 8)
546 ... mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
547 ...
548 ... assert mymodule.date.today() == date(2010, 10, 8)
549 ... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
Michael Foord944e02d2012-03-25 23:12:55 +0100550
Georg Brandl7ad3df62014-10-31 07:59:37 +0100551Note that we don't patch :class:`datetime.date` globally, we patch ``date`` in the
Michael Foord944e02d2012-03-25 23:12:55 +0100552module that *uses* it. See :ref:`where to patch <where-to-patch>`.
553
Georg Brandl7ad3df62014-10-31 07:59:37 +0100554When ``date.today()`` is called a known date is returned, but calls to the
555``date(...)`` constructor still return normal dates. Without this you can find
Michael Foord944e02d2012-03-25 23:12:55 +0100556yourself having to calculate an expected result using exactly the same
557algorithm as the code under test, which is a classic testing anti-pattern.
558
Georg Brandl7ad3df62014-10-31 07:59:37 +0100559Calls to the date constructor are recorded in the ``mock_date`` attributes
560(``call_count`` and friends) which may also be useful for your tests.
Michael Foord944e02d2012-03-25 23:12:55 +0100561
562An alternative way of dealing with mocking dates, or other builtin classes,
563is discussed in `this blog entry
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300564<https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/>`_.
Michael Foord944e02d2012-03-25 23:12:55 +0100565
566
567Mocking a Generator Method
Georg Brandl7fc972a2013-02-03 14:00:04 +0100568~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100569
Georg Brandl728e4de2014-10-29 09:00:30 +0100570A Python generator is a function or method that uses the :keyword:`yield` statement
571to return a series of values when iterated over [#]_.
Michael Foord944e02d2012-03-25 23:12:55 +0100572
573A generator method / function is called to return the generator object. It is
574the generator object that is then iterated over. The protocol method for
Georg Brandl728e4de2014-10-29 09:00:30 +0100575iteration is :meth:`~container.__iter__`, so we can
Georg Brandl7ad3df62014-10-31 07:59:37 +0100576mock this using a :class:`MagicMock`.
Michael Foord944e02d2012-03-25 23:12:55 +0100577
578Here's an example class with an "iter" method implemented as a generator:
579
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200580 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100581 ... def iter(self):
582 ... for i in [1, 2, 3]:
583 ... yield i
584 ...
585 >>> foo = Foo()
586 >>> list(foo.iter())
587 [1, 2, 3]
588
589
590How would we mock this class, and in particular its "iter" method?
591
592To configure the values returned from the iteration (implicit in the call to
Georg Brandl7ad3df62014-10-31 07:59:37 +0100593:class:`list`), we need to configure the object returned by the call to ``foo.iter()``.
Michael Foord944e02d2012-03-25 23:12:55 +0100594
595 >>> mock_foo = MagicMock()
596 >>> mock_foo.iter.return_value = iter([1, 2, 3])
597 >>> list(mock_foo.iter())
598 [1, 2, 3]
599
600.. [#] There are also generator expressions and more `advanced uses
601 <http://www.dabeaz.com/coroutines/index.html>`_ of generators, but we aren't
602 concerned about them here. A very good introduction to generators and how
603 powerful they are is: `Generator Tricks for Systems Programmers
604 <http://www.dabeaz.com/generators/>`_.
605
606
607Applying the same patch to every test method
Georg Brandl7fc972a2013-02-03 14:00:04 +0100608~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100609
610If you want several patches in place for multiple test methods the obvious way
611is to apply the patch decorators to every method. This can feel like unnecessary
Georg Brandl7ad3df62014-10-31 07:59:37 +0100612repetition. For Python 2.6 or more recent you can use :func:`patch` (in all its
Michael Foord944e02d2012-03-25 23:12:55 +0100613various forms) as a class decorator. This applies the patches to all test
614methods on the class. A test method is identified by methods whose names start
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200615with ``test``::
Michael Foord944e02d2012-03-25 23:12:55 +0100616
617 >>> @patch('mymodule.SomeClass')
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200618 ... class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100619 ...
620 ... def test_one(self, MockSomeClass):
Ezio Melottie2123702013-01-10 03:43:33 +0200621 ... self.assertIs(mymodule.SomeClass, MockSomeClass)
Michael Foord944e02d2012-03-25 23:12:55 +0100622 ...
623 ... def test_two(self, MockSomeClass):
Ezio Melottie2123702013-01-10 03:43:33 +0200624 ... self.assertIs(mymodule.SomeClass, MockSomeClass)
Michael Foord944e02d2012-03-25 23:12:55 +0100625 ...
626 ... def not_a_test(self):
627 ... return 'something'
628 ...
629 >>> MyTest('test_one').test_one()
630 >>> MyTest('test_two').test_two()
631 >>> MyTest('test_two').not_a_test()
632 'something'
633
634An alternative way of managing patches is to use the :ref:`start-and-stop`.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100635These allow you to move the patching into your ``setUp`` and ``tearDown`` methods.
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200636::
Michael Foord944e02d2012-03-25 23:12:55 +0100637
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200638 >>> class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100639 ... def setUp(self):
640 ... self.patcher = patch('mymodule.foo')
641 ... self.mock_foo = self.patcher.start()
642 ...
643 ... def test_foo(self):
Ezio Melottie2123702013-01-10 03:43:33 +0200644 ... self.assertIs(mymodule.foo, self.mock_foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100645 ...
646 ... def tearDown(self):
647 ... self.patcher.stop()
648 ...
649 >>> MyTest('test_foo').run()
650
651If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +0100652calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foord944e02d2012-03-25 23:12:55 +0100653exception is raised in the setUp then tearDown is not called.
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200654:meth:`unittest.TestCase.addCleanup` makes this easier::
Michael Foord944e02d2012-03-25 23:12:55 +0100655
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200656 >>> class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100657 ... def setUp(self):
658 ... patcher = patch('mymodule.foo')
659 ... self.addCleanup(patcher.stop)
660 ... self.mock_foo = patcher.start()
661 ...
662 ... def test_foo(self):
Ezio Melottie2123702013-01-10 03:43:33 +0200663 ... self.assertIs(mymodule.foo, self.mock_foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100664 ...
665 >>> MyTest('test_foo').run()
666
667
668Mocking Unbound Methods
Georg Brandl7fc972a2013-02-03 14:00:04 +0100669~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100670
671Whilst writing tests today I needed to patch an *unbound method* (patching the
672method on the class rather than on the instance). I needed self to be passed
673in as the first argument because I want to make asserts about which objects
674were calling this particular method. The issue is that you can't patch with a
675mock for this, because if you replace an unbound method with a mock it doesn't
676become a bound method when fetched from the instance, and so it doesn't get
677self passed in. The workaround is to patch the unbound method with a real
678function instead. The :func:`patch` decorator makes it so simple to
679patch out methods with a mock that having to create a real function becomes a
680nuisance.
681
Georg Brandl7ad3df62014-10-31 07:59:37 +0100682If you pass ``autospec=True`` to patch then it does the patching with a
Michael Foord944e02d2012-03-25 23:12:55 +0100683*real* function object. This function object has the same signature as the one
684it is replacing, but delegates to a mock under the hood. You still get your
685mock auto-created in exactly the same way as before. What it means though, is
686that if you use it to patch out an unbound method on a class the mocked
687function will be turned into a bound method if it is fetched from an instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100688It will have ``self`` passed in as the first argument, which is exactly what I
Michael Foord944e02d2012-03-25 23:12:55 +0100689wanted:
690
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200691 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100692 ... def foo(self):
693 ... pass
694 ...
695 >>> with patch.object(Foo, 'foo', autospec=True) as mock_foo:
696 ... mock_foo.return_value = 'foo'
697 ... foo = Foo()
698 ... foo.foo()
699 ...
700 'foo'
701 >>> mock_foo.assert_called_once_with(foo)
702
Georg Brandl7ad3df62014-10-31 07:59:37 +0100703If we don't use ``autospec=True`` then the unbound method is patched out
704with a Mock instance instead, and isn't called with ``self``.
Michael Foord944e02d2012-03-25 23:12:55 +0100705
706
707Checking multiple calls with mock
Georg Brandl7fc972a2013-02-03 14:00:04 +0100708~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100709
710mock has a nice API for making assertions about how your mock objects are used.
711
712 >>> mock = Mock()
713 >>> mock.foo_bar.return_value = None
714 >>> mock.foo_bar('baz', spam='eggs')
715 >>> mock.foo_bar.assert_called_with('baz', spam='eggs')
716
717If your mock is only being called once you can use the
718:meth:`assert_called_once_with` method that also asserts that the
719:attr:`call_count` is one.
720
721 >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
722 >>> mock.foo_bar()
723 >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
724 Traceback (most recent call last):
725 ...
726 AssertionError: Expected to be called once. Called 2 times.
727
Georg Brandl7ad3df62014-10-31 07:59:37 +0100728Both ``assert_called_with`` and ``assert_called_once_with`` make assertions about
Michael Foord944e02d2012-03-25 23:12:55 +0100729the *most recent* call. If your mock is going to be called several times, and
730you want to make assertions about *all* those calls you can use
731:attr:`~Mock.call_args_list`:
732
733 >>> mock = Mock(return_value=None)
734 >>> mock(1, 2, 3)
735 >>> mock(4, 5, 6)
736 >>> mock()
737 >>> mock.call_args_list
738 [call(1, 2, 3), call(4, 5, 6), call()]
739
740The :data:`call` helper makes it easy to make assertions about these calls. You
Georg Brandl7ad3df62014-10-31 07:59:37 +0100741can build up a list of expected calls and compare it to ``call_args_list``. This
742looks remarkably similar to the repr of the ``call_args_list``:
Michael Foord944e02d2012-03-25 23:12:55 +0100743
744 >>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
745 >>> mock.call_args_list == expected
746 True
747
748
749Coping with mutable arguments
Georg Brandl7fc972a2013-02-03 14:00:04 +0100750~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100751
752Another situation is rare, but can bite you, is when your mock is called with
Georg Brandl7ad3df62014-10-31 07:59:37 +0100753mutable arguments. ``call_args`` and ``call_args_list`` store *references* to the
Michael Foord944e02d2012-03-25 23:12:55 +0100754arguments. If the arguments are mutated by the code under test then you can no
755longer make assertions about what the values were when the mock was called.
756
757Here's some example code that shows the problem. Imagine the following functions
758defined in 'mymodule'::
759
760 def frob(val):
761 pass
762
763 def grob(val):
764 "First frob and then clear val"
765 frob(val)
766 val.clear()
767
Georg Brandl7ad3df62014-10-31 07:59:37 +0100768When we try to test that ``grob`` calls ``frob`` with the correct argument look
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200769what happens::
Michael Foord944e02d2012-03-25 23:12:55 +0100770
771 >>> with patch('mymodule.frob') as mock_frob:
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200772 ... val = {6}
Michael Foord944e02d2012-03-25 23:12:55 +0100773 ... mymodule.grob(val)
774 ...
775 >>> val
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200776 set()
777 >>> mock_frob.assert_called_with({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100778 Traceback (most recent call last):
779 ...
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200780 AssertionError: Expected: (({6},), {})
781 Called with: ((set(),), {})
Michael Foord944e02d2012-03-25 23:12:55 +0100782
783One possibility would be for mock to copy the arguments you pass in. This
784could then cause problems if you do assertions that rely on object identity
785for equality.
786
787Here's one solution that uses the :attr:`side_effect`
Georg Brandl7ad3df62014-10-31 07:59:37 +0100788functionality. If you provide a ``side_effect`` function for a mock then
789``side_effect`` will be called with the same args as the mock. This gives us an
Michael Foord944e02d2012-03-25 23:12:55 +0100790opportunity to copy the arguments and store them for later assertions. In this
791example I'm using *another* mock to store the arguments so that I can use the
792mock methods for doing the assertion. Again a helper function sets this up for
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200793me. ::
Michael Foord944e02d2012-03-25 23:12:55 +0100794
795 >>> from copy import deepcopy
796 >>> from unittest.mock import Mock, patch, DEFAULT
797 >>> def copy_call_args(mock):
798 ... new_mock = Mock()
799 ... def side_effect(*args, **kwargs):
800 ... args = deepcopy(args)
801 ... kwargs = deepcopy(kwargs)
802 ... new_mock(*args, **kwargs)
803 ... return DEFAULT
804 ... mock.side_effect = side_effect
805 ... return new_mock
806 ...
807 >>> with patch('mymodule.frob') as mock_frob:
808 ... new_mock = copy_call_args(mock_frob)
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200809 ... val = {6}
Michael Foord944e02d2012-03-25 23:12:55 +0100810 ... mymodule.grob(val)
811 ...
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200812 >>> new_mock.assert_called_with({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100813 >>> new_mock.call_args
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200814 call({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100815
Georg Brandl7ad3df62014-10-31 07:59:37 +0100816``copy_call_args`` is called with the mock that will be called. It returns a new
817mock that we do the assertion on. The ``side_effect`` function makes a copy of
818the args and calls our ``new_mock`` with the copy.
Michael Foord944e02d2012-03-25 23:12:55 +0100819
820.. note::
821
822 If your mock is only going to be used once there is an easier way of
823 checking arguments at the point they are called. You can simply do the
Georg Brandl7ad3df62014-10-31 07:59:37 +0100824 checking inside a ``side_effect`` function.
Michael Foord944e02d2012-03-25 23:12:55 +0100825
826 >>> def side_effect(arg):
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200827 ... assert arg == {6}
Michael Foord944e02d2012-03-25 23:12:55 +0100828 ...
829 >>> mock = Mock(side_effect=side_effect)
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200830 >>> mock({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100831 >>> mock(set())
832 Traceback (most recent call last):
833 ...
834 AssertionError
835
Georg Brandl7ad3df62014-10-31 07:59:37 +0100836An alternative approach is to create a subclass of :class:`Mock` or
837:class:`MagicMock` that copies (using :func:`copy.deepcopy`) the arguments.
Michael Foord944e02d2012-03-25 23:12:55 +0100838Here's an example implementation:
839
840 >>> from copy import deepcopy
841 >>> class CopyingMock(MagicMock):
842 ... def __call__(self, *args, **kwargs):
843 ... args = deepcopy(args)
844 ... kwargs = deepcopy(kwargs)
845 ... return super(CopyingMock, self).__call__(*args, **kwargs)
846 ...
847 >>> c = CopyingMock(return_value=None)
848 >>> arg = set()
849 >>> c(arg)
850 >>> arg.add(1)
851 >>> c.assert_called_with(set())
852 >>> c.assert_called_with(arg)
853 Traceback (most recent call last):
854 ...
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200855 AssertionError: Expected call: mock({1})
856 Actual call: mock(set())
Michael Foord944e02d2012-03-25 23:12:55 +0100857 >>> c.foo
858 <CopyingMock name='mock.foo' id='...'>
859
Georg Brandl7ad3df62014-10-31 07:59:37 +0100860When you subclass ``Mock`` or ``MagicMock`` all dynamically created attributes,
861and the ``return_value`` will use your subclass automatically. That means all
862children of a ``CopyingMock`` will also have the type ``CopyingMock``.
Michael Foord944e02d2012-03-25 23:12:55 +0100863
864
Michael Foord944e02d2012-03-25 23:12:55 +0100865Nesting Patches
Georg Brandl7fc972a2013-02-03 14:00:04 +0100866~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100867
868Using patch as a context manager is nice, but if you do multiple patches you
869can end up with nested with statements indenting further and further to the
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200870right::
Michael Foord944e02d2012-03-25 23:12:55 +0100871
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200872 >>> class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100873 ...
874 ... def test_foo(self):
875 ... with patch('mymodule.Foo') as mock_foo:
876 ... with patch('mymodule.Bar') as mock_bar:
877 ... with patch('mymodule.Spam') as mock_spam:
878 ... assert mymodule.Foo is mock_foo
879 ... assert mymodule.Bar is mock_bar
880 ... assert mymodule.Spam is mock_spam
881 ...
882 >>> original = mymodule.Foo
883 >>> MyTest('test_foo').test_foo()
884 >>> assert mymodule.Foo is original
885
Georg Brandl7ad3df62014-10-31 07:59:37 +0100886With unittest ``cleanup`` functions and the :ref:`start-and-stop` we can
Michael Foord944e02d2012-03-25 23:12:55 +0100887achieve the same effect without the nested indentation. A simple helper
Georg Brandl7ad3df62014-10-31 07:59:37 +0100888method, ``create_patch``, puts the patch in place and returns the created mock
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200889for us::
Michael Foord944e02d2012-03-25 23:12:55 +0100890
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200891 >>> class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100892 ...
893 ... def create_patch(self, name):
894 ... patcher = patch(name)
895 ... thing = patcher.start()
896 ... self.addCleanup(patcher.stop)
897 ... return thing
898 ...
899 ... def test_foo(self):
900 ... mock_foo = self.create_patch('mymodule.Foo')
901 ... mock_bar = self.create_patch('mymodule.Bar')
902 ... mock_spam = self.create_patch('mymodule.Spam')
903 ...
904 ... assert mymodule.Foo is mock_foo
905 ... assert mymodule.Bar is mock_bar
906 ... assert mymodule.Spam is mock_spam
907 ...
908 >>> original = mymodule.Foo
909 >>> MyTest('test_foo').run()
910 >>> assert mymodule.Foo is original
911
912
913Mocking a dictionary with MagicMock
Georg Brandl7fc972a2013-02-03 14:00:04 +0100914~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100915
916You may want to mock a dictionary, or other container object, recording all
917access to it whilst having it still behave like a dictionary.
918
919We can do this with :class:`MagicMock`, which will behave like a dictionary,
920and using :data:`~Mock.side_effect` to delegate dictionary access to a real
921underlying dictionary that is under our control.
922
Georg Brandl7ad3df62014-10-31 07:59:37 +0100923When the :meth:`__getitem__` and :meth:`__setitem__` methods of our ``MagicMock`` are called
924(normal dictionary access) then ``side_effect`` is called with the key (and in
925the case of ``__setitem__`` the value too). We can also control what is returned.
Michael Foord944e02d2012-03-25 23:12:55 +0100926
Georg Brandl7ad3df62014-10-31 07:59:37 +0100927After the ``MagicMock`` has been used we can use attributes like
Michael Foord944e02d2012-03-25 23:12:55 +0100928:data:`~Mock.call_args_list` to assert about how the dictionary was used:
929
930 >>> my_dict = {'a': 1, 'b': 2, 'c': 3}
931 >>> def getitem(name):
932 ... return my_dict[name]
933 ...
934 >>> def setitem(name, val):
935 ... my_dict[name] = val
936 ...
937 >>> mock = MagicMock()
938 >>> mock.__getitem__.side_effect = getitem
939 >>> mock.__setitem__.side_effect = setitem
940
941.. note::
942
Georg Brandl7ad3df62014-10-31 07:59:37 +0100943 An alternative to using ``MagicMock`` is to use ``Mock`` and *only* provide
Michael Foord944e02d2012-03-25 23:12:55 +0100944 the magic methods you specifically want:
945
946 >>> mock = Mock()
Éric Araujo0b1be1a2014-03-17 16:48:13 -0400947 >>> mock.__getitem__ = Mock(side_effect=getitem)
948 >>> mock.__setitem__ = Mock(side_effect=setitem)
Michael Foord944e02d2012-03-25 23:12:55 +0100949
Georg Brandl7ad3df62014-10-31 07:59:37 +0100950 A *third* option is to use ``MagicMock`` but passing in ``dict`` as the *spec*
951 (or *spec_set*) argument so that the ``MagicMock`` created only has
Michael Foord944e02d2012-03-25 23:12:55 +0100952 dictionary magic methods available:
953
954 >>> mock = MagicMock(spec_set=dict)
955 >>> mock.__getitem__.side_effect = getitem
956 >>> mock.__setitem__.side_effect = setitem
957
Georg Brandl7ad3df62014-10-31 07:59:37 +0100958With these side effect functions in place, the ``mock`` will behave like a normal
959dictionary but recording the access. It even raises a :exc:`KeyError` if you try
Michael Foord944e02d2012-03-25 23:12:55 +0100960to access a key that doesn't exist.
961
962 >>> mock['a']
963 1
964 >>> mock['c']
965 3
966 >>> mock['d']
967 Traceback (most recent call last):
968 ...
969 KeyError: 'd'
970 >>> mock['b'] = 'fish'
971 >>> mock['d'] = 'eggs'
972 >>> mock['b']
973 'fish'
974 >>> mock['d']
975 'eggs'
976
977After it has been used you can make assertions about the access using the normal
978mock methods and attributes:
979
980 >>> mock.__getitem__.call_args_list
981 [call('a'), call('c'), call('d'), call('b'), call('d')]
982 >>> mock.__setitem__.call_args_list
983 [call('b', 'fish'), call('d', 'eggs')]
984 >>> my_dict
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200985 {'a': 1, 'b': 'fish', 'c': 3, 'd': 'eggs'}
Michael Foord944e02d2012-03-25 23:12:55 +0100986
987
988Mock subclasses and their attributes
Georg Brandl7fc972a2013-02-03 14:00:04 +0100989~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100990
Georg Brandl7ad3df62014-10-31 07:59:37 +0100991There are various reasons why you might want to subclass :class:`Mock`. One
992reason might be to add helper methods. Here's a silly example:
Michael Foord944e02d2012-03-25 23:12:55 +0100993
994 >>> class MyMock(MagicMock):
995 ... def has_been_called(self):
996 ... return self.called
997 ...
998 >>> mymock = MyMock(return_value=None)
999 >>> mymock
1000 <MyMock id='...'>
1001 >>> mymock.has_been_called()
1002 False
1003 >>> mymock()
1004 >>> mymock.has_been_called()
1005 True
1006
Georg Brandl7ad3df62014-10-31 07:59:37 +01001007The standard behaviour for ``Mock`` instances is that attributes and the return
Michael Foord944e02d2012-03-25 23:12:55 +01001008value mocks are of the same type as the mock they are accessed on. This ensures
Georg Brandl7ad3df62014-10-31 07:59:37 +01001009that ``Mock`` attributes are ``Mocks`` and ``MagicMock`` attributes are ``MagicMocks``
Michael Foord944e02d2012-03-25 23:12:55 +01001010[#]_. So if you're subclassing to add helper methods then they'll also be
1011available on the attributes and return value mock of instances of your
1012subclass.
1013
1014 >>> mymock.foo
1015 <MyMock name='mock.foo' id='...'>
1016 >>> mymock.foo.has_been_called()
1017 False
1018 >>> mymock.foo()
1019 <MyMock name='mock.foo()' id='...'>
1020 >>> mymock.foo.has_been_called()
1021 True
1022
1023Sometimes this is inconvenient. For example, `one user
Sanyam Khurana338cd832018-01-20 05:55:37 +05301024<https://code.google.com/archive/p/mock/issues/105>`_ is subclassing mock to
Michael Foord944e02d2012-03-25 23:12:55 +01001025created a `Twisted adaptor
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001026<https://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html>`_.
Michael Foord944e02d2012-03-25 23:12:55 +01001027Having this applied to attributes too actually causes errors.
1028
Georg Brandl7ad3df62014-10-31 07:59:37 +01001029``Mock`` (in all its flavours) uses a method called ``_get_child_mock`` to create
Michael Foord944e02d2012-03-25 23:12:55 +01001030these "sub-mocks" for attributes and return values. You can prevent your
1031subclass being used for attributes by overriding this method. The signature is
Georg Brandl7ad3df62014-10-31 07:59:37 +01001032that it takes arbitrary keyword arguments (``**kwargs``) which are then passed
Michael Foord944e02d2012-03-25 23:12:55 +01001033onto the mock constructor:
1034
1035 >>> class Subclass(MagicMock):
1036 ... def _get_child_mock(self, **kwargs):
1037 ... return MagicMock(**kwargs)
1038 ...
1039 >>> mymock = Subclass()
1040 >>> mymock.foo
1041 <MagicMock name='mock.foo' id='...'>
1042 >>> assert isinstance(mymock, Subclass)
1043 >>> assert not isinstance(mymock.foo, Subclass)
1044 >>> assert not isinstance(mymock(), Subclass)
1045
1046.. [#] An exception to this rule are the non-callable mocks. Attributes use the
1047 callable variant because otherwise non-callable mocks couldn't have callable
1048 methods.
1049
1050
1051Mocking imports with patch.dict
Georg Brandl7fc972a2013-02-03 14:00:04 +01001052~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001053
1054One situation where mocking can be hard is where you have a local import inside
1055a function. These are harder to mock because they aren't using an object from
1056the module namespace that we can patch out.
1057
1058Generally local imports are to be avoided. They are sometimes done to prevent
1059circular dependencies, for which there is *usually* a much better way to solve
1060the problem (refactor the code) or to prevent "up front costs" by delaying the
1061import. This can also be solved in better ways than an unconditional local
1062import (store the module as a class or module attribute and only do the import
1063on first use).
1064
Georg Brandl7ad3df62014-10-31 07:59:37 +01001065That aside there is a way to use ``mock`` to affect the results of an import.
1066Importing fetches an *object* from the :data:`sys.modules` dictionary. Note that it
Michael Foord944e02d2012-03-25 23:12:55 +01001067fetches an *object*, which need not be a module. Importing a module for the
1068first time results in a module object being put in `sys.modules`, so usually
1069when you import something you get a module back. This need not be the case
1070however.
1071
1072This means you can use :func:`patch.dict` to *temporarily* put a mock in place
Georg Brandl7ad3df62014-10-31 07:59:37 +01001073in :data:`sys.modules`. Any imports whilst this patch is active will fetch the mock.
Michael Foord944e02d2012-03-25 23:12:55 +01001074When the patch is complete (the decorated function exits, the with statement
Georg Brandl7ad3df62014-10-31 07:59:37 +01001075body is complete or ``patcher.stop()`` is called) then whatever was there
Michael Foord944e02d2012-03-25 23:12:55 +01001076previously will be restored safely.
1077
1078Here's an example that mocks out the 'fooble' module.
1079
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001080 >>> import sys
Michael Foord944e02d2012-03-25 23:12:55 +01001081 >>> mock = Mock()
1082 >>> with patch.dict('sys.modules', {'fooble': mock}):
1083 ... import fooble
1084 ... fooble.blob()
1085 ...
1086 <Mock name='mock.blob()' id='...'>
1087 >>> assert 'fooble' not in sys.modules
1088 >>> mock.blob.assert_called_once_with()
1089
Georg Brandl7ad3df62014-10-31 07:59:37 +01001090As you can see the ``import fooble`` succeeds, but on exit there is no 'fooble'
1091left in :data:`sys.modules`.
Michael Foord944e02d2012-03-25 23:12:55 +01001092
Georg Brandl7ad3df62014-10-31 07:59:37 +01001093This also works for the ``from module import name`` form:
Michael Foord944e02d2012-03-25 23:12:55 +01001094
1095 >>> mock = Mock()
1096 >>> with patch.dict('sys.modules', {'fooble': mock}):
1097 ... from fooble import blob
1098 ... blob.blip()
1099 ...
1100 <Mock name='mock.blob.blip()' id='...'>
1101 >>> mock.blob.blip.assert_called_once_with()
1102
1103With slightly more work you can also mock package imports:
1104
1105 >>> mock = Mock()
1106 >>> modules = {'package': mock, 'package.module': mock.module}
1107 >>> with patch.dict('sys.modules', modules):
1108 ... from package.module import fooble
1109 ... fooble()
1110 ...
1111 <Mock name='mock.module.fooble()' id='...'>
1112 >>> mock.module.fooble.assert_called_once_with()
1113
1114
1115Tracking order of calls and less verbose call assertions
Georg Brandl7fc972a2013-02-03 14:00:04 +01001116~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001117
1118The :class:`Mock` class allows you to track the *order* of method calls on
1119your mock objects through the :attr:`~Mock.method_calls` attribute. This
1120doesn't allow you to track the order of calls between separate mock objects,
1121however we can use :attr:`~Mock.mock_calls` to achieve the same effect.
1122
Georg Brandl7ad3df62014-10-31 07:59:37 +01001123Because mocks track calls to child mocks in ``mock_calls``, and accessing an
Michael Foord944e02d2012-03-25 23:12:55 +01001124arbitrary attribute of a mock creates a child mock, we can create our separate
1125mocks from a parent one. Calls to those child mock will then all be recorded,
Georg Brandl7ad3df62014-10-31 07:59:37 +01001126in order, in the ``mock_calls`` of the parent:
Michael Foord944e02d2012-03-25 23:12:55 +01001127
1128 >>> manager = Mock()
1129 >>> mock_foo = manager.foo
1130 >>> mock_bar = manager.bar
1131
1132 >>> mock_foo.something()
1133 <Mock name='mock.foo.something()' id='...'>
1134 >>> mock_bar.other.thing()
1135 <Mock name='mock.bar.other.thing()' id='...'>
1136
1137 >>> manager.mock_calls
1138 [call.foo.something(), call.bar.other.thing()]
1139
1140We can then assert about the calls, including the order, by comparing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01001141the ``mock_calls`` attribute on the manager mock:
Michael Foord944e02d2012-03-25 23:12:55 +01001142
1143 >>> expected_calls = [call.foo.something(), call.bar.other.thing()]
1144 >>> manager.mock_calls == expected_calls
1145 True
1146
Georg Brandl7ad3df62014-10-31 07:59:37 +01001147If ``patch`` is creating, and putting in place, your mocks then you can attach
Michael Foord944e02d2012-03-25 23:12:55 +01001148them to a manager mock using the :meth:`~Mock.attach_mock` method. After
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001149attaching calls will be recorded in ``mock_calls`` of the manager. ::
Michael Foord944e02d2012-03-25 23:12:55 +01001150
1151 >>> manager = MagicMock()
1152 >>> with patch('mymodule.Class1') as MockClass1:
1153 ... with patch('mymodule.Class2') as MockClass2:
1154 ... manager.attach_mock(MockClass1, 'MockClass1')
1155 ... manager.attach_mock(MockClass2, 'MockClass2')
1156 ... MockClass1().foo()
1157 ... MockClass2().bar()
Michael Foord944e02d2012-03-25 23:12:55 +01001158 <MagicMock name='mock.MockClass1().foo()' id='...'>
1159 <MagicMock name='mock.MockClass2().bar()' id='...'>
1160 >>> manager.mock_calls
1161 [call.MockClass1(),
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001162 call.MockClass1().foo(),
1163 call.MockClass2(),
1164 call.MockClass2().bar()]
Michael Foord944e02d2012-03-25 23:12:55 +01001165
1166If many calls have been made, but you're only interested in a particular
1167sequence of them then an alternative is to use the
1168:meth:`~Mock.assert_has_calls` method. This takes a list of calls (constructed
1169with the :data:`call` object). If that sequence of calls are in
1170:attr:`~Mock.mock_calls` then the assert succeeds.
1171
1172 >>> m = MagicMock()
1173 >>> m().foo().bar().baz()
1174 <MagicMock name='mock().foo().bar().baz()' id='...'>
1175 >>> m.one().two().three()
1176 <MagicMock name='mock.one().two().three()' id='...'>
1177 >>> calls = call.one().two().three().call_list()
1178 >>> m.assert_has_calls(calls)
1179
Georg Brandl7ad3df62014-10-31 07:59:37 +01001180Even though the chained call ``m.one().two().three()`` aren't the only calls that
Michael Foord944e02d2012-03-25 23:12:55 +01001181have been made to the mock, the assert still succeeds.
1182
1183Sometimes a mock may have several calls made to it, and you are only interested
1184in asserting about *some* of those calls. You may not even care about the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001185order. In this case you can pass ``any_order=True`` to ``assert_has_calls``:
Michael Foord944e02d2012-03-25 23:12:55 +01001186
1187 >>> m = MagicMock()
1188 >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
1189 (...)
1190 >>> calls = [call.fifty('50'), call(1), call.seven(7)]
1191 >>> m.assert_has_calls(calls, any_order=True)
1192
1193
1194More complex argument matching
Georg Brandl7fc972a2013-02-03 14:00:04 +01001195~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001196
1197Using the same basic concept as :data:`ANY` we can implement matchers to do more
1198complex assertions on objects used as arguments to mocks.
1199
1200Suppose we expect some object to be passed to a mock that by default
1201compares equal based on object identity (which is the Python default for user
1202defined classes). To use :meth:`~Mock.assert_called_with` we would need to pass
1203in the exact same object. If we are only interested in some of the attributes
1204of this object then we can create a matcher that will check these attributes
1205for us.
1206
Georg Brandl7ad3df62014-10-31 07:59:37 +01001207You can see in this example how a 'standard' call to ``assert_called_with`` isn't
Michael Foord944e02d2012-03-25 23:12:55 +01001208sufficient:
1209
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001210 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +01001211 ... def __init__(self, a, b):
1212 ... self.a, self.b = a, b
1213 ...
1214 >>> mock = Mock(return_value=None)
1215 >>> mock(Foo(1, 2))
1216 >>> mock.assert_called_with(Foo(1, 2))
1217 Traceback (most recent call last):
1218 ...
1219 AssertionError: Expected: call(<__main__.Foo object at 0x...>)
1220 Actual call: call(<__main__.Foo object at 0x...>)
1221
Georg Brandl7ad3df62014-10-31 07:59:37 +01001222A comparison function for our ``Foo`` class might look something like this:
Michael Foord944e02d2012-03-25 23:12:55 +01001223
1224 >>> def compare(self, other):
1225 ... if not type(self) == type(other):
1226 ... return False
1227 ... if self.a != other.a:
1228 ... return False
1229 ... if self.b != other.b:
1230 ... return False
1231 ... return True
1232 ...
1233
1234And a matcher object that can use comparison functions like this for its
1235equality operation would look something like this:
1236
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001237 >>> class Matcher:
Michael Foord944e02d2012-03-25 23:12:55 +01001238 ... def __init__(self, compare, some_obj):
1239 ... self.compare = compare
1240 ... self.some_obj = some_obj
1241 ... def __eq__(self, other):
1242 ... return self.compare(self.some_obj, other)
1243 ...
1244
1245Putting all this together:
1246
1247 >>> match_foo = Matcher(compare, Foo(1, 2))
1248 >>> mock.assert_called_with(match_foo)
1249
Georg Brandl7ad3df62014-10-31 07:59:37 +01001250The ``Matcher`` is instantiated with our compare function and the ``Foo`` object
1251we want to compare against. In ``assert_called_with`` the ``Matcher`` equality
Michael Foord944e02d2012-03-25 23:12:55 +01001252method will be called, which compares the object the mock was called with
1253against the one we created our matcher with. If they match then
Georg Brandl7ad3df62014-10-31 07:59:37 +01001254``assert_called_with`` passes, and if they don't an :exc:`AssertionError` is raised:
Michael Foord944e02d2012-03-25 23:12:55 +01001255
1256 >>> match_wrong = Matcher(compare, Foo(3, 4))
1257 >>> mock.assert_called_with(match_wrong)
1258 Traceback (most recent call last):
1259 ...
1260 AssertionError: Expected: ((<Matcher object at 0x...>,), {})
1261 Called with: ((<Foo object at 0x...>,), {})
1262
1263With a bit of tweaking you could have the comparison function raise the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001264:exc:`AssertionError` directly and provide a more useful failure message.
Michael Foord944e02d2012-03-25 23:12:55 +01001265
1266As of version 1.5, the Python testing library `PyHamcrest
Sanyam Khurana338cd832018-01-20 05:55:37 +05301267<https://pyhamcrest.readthedocs.io/>`_ provides similar functionality,
Michael Foord944e02d2012-03-25 23:12:55 +01001268that may be useful here, in the form of its equality matcher
1269(`hamcrest.library.integration.match_equality
Sanyam Khurana338cd832018-01-20 05:55:37 +05301270<https://pyhamcrest.readthedocs.io/en/release-1.8/integration/#module-hamcrest.library.integration.match_equality>`_).