blob: 16690f349822ecf8a5704ab8d41d8c6560a73562 [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
Chris Withers8ca0fa92018-12-03 21:31:37 +0000169However, parameters to calls that return mocks are not recorded, which means it is not
170possible to track nested calls where the parameters used to create ancestors are important:
171
172 >>> m = Mock()
173 >>> m.factory(important=True).deliver()
174 <Mock name='mock.factory().deliver()' id='...'>
175 >>> m.mock_calls[-1] == call.factory(important=False).deliver()
176 True
177
Michael Foorda9e6fb22012-03-28 14:36:02 +0100178
179Setting Return Values and Attributes
180~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
181
182Setting the return values on a mock object is trivially easy:
183
184 >>> mock = Mock()
185 >>> mock.return_value = 3
186 >>> mock()
187 3
188
189Of course you can do the same for methods on the mock:
190
191 >>> mock = Mock()
192 >>> mock.method.return_value = 3
193 >>> mock.method()
194 3
195
196The return value can also be set in the constructor:
197
198 >>> mock = Mock(return_value=3)
199 >>> mock()
200 3
201
202If you need an attribute setting on your mock, just do it:
203
204 >>> mock = Mock()
205 >>> mock.x = 3
206 >>> mock.x
207 3
208
209Sometimes you want to mock up a more complex situation, like for example
Georg Brandl7ad3df62014-10-31 07:59:37 +0100210``mock.connection.cursor().execute("SELECT 1")``. If we wanted this call to
Michael Foorda9e6fb22012-03-28 14:36:02 +0100211return a list, then we have to configure the result of the nested call.
212
213We can use :data:`call` to construct the set of calls in a "chained call" like
214this for easy assertion afterwards:
215
216 >>> mock = Mock()
217 >>> cursor = mock.connection.cursor.return_value
218 >>> cursor.execute.return_value = ['foo']
219 >>> mock.connection.cursor().execute("SELECT 1")
220 ['foo']
221 >>> expected = call.connection.cursor().execute("SELECT 1").call_list()
222 >>> mock.mock_calls
223 [call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]
224 >>> mock.mock_calls == expected
225 True
226
Georg Brandl7ad3df62014-10-31 07:59:37 +0100227It is the call to ``.call_list()`` that turns our call object into a list of
Michael Foorda9e6fb22012-03-28 14:36:02 +0100228calls representing the chained calls.
229
230
231Raising exceptions with mocks
232~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
233
234A useful attribute is :attr:`~Mock.side_effect`. If you set this to an
235exception class or instance then the exception will be raised when the mock
236is called.
237
238 >>> mock = Mock(side_effect=Exception('Boom!'))
239 >>> mock()
240 Traceback (most recent call last):
241 ...
242 Exception: Boom!
243
244
245Side effect functions and iterables
246~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
247
Georg Brandl7ad3df62014-10-31 07:59:37 +0100248``side_effect`` can also be set to a function or an iterable. The use case for
249``side_effect`` as an iterable is where your mock is going to be called several
Michael Foorda9e6fb22012-03-28 14:36:02 +0100250times, and you want each call to return a different value. When you set
Georg Brandl7ad3df62014-10-31 07:59:37 +0100251``side_effect`` to an iterable every call to the mock returns the next value
Michael Foorda9e6fb22012-03-28 14:36:02 +0100252from the iterable:
253
254 >>> mock = MagicMock(side_effect=[4, 5, 6])
255 >>> mock()
256 4
257 >>> mock()
258 5
259 >>> mock()
260 6
261
262
263For more advanced use cases, like dynamically varying the return values
Georg Brandl7ad3df62014-10-31 07:59:37 +0100264depending on what the mock is called with, ``side_effect`` can be a function.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100265The function will be called with the same arguments as the mock. Whatever the
266function returns is what the call returns:
267
268 >>> vals = {(1, 2): 1, (2, 3): 2}
269 >>> def side_effect(*args):
270 ... return vals[args]
271 ...
272 >>> mock = MagicMock(side_effect=side_effect)
273 >>> mock(1, 2)
274 1
275 >>> mock(2, 3)
276 2
277
278
279Creating a Mock from an Existing Object
280~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
281
282One problem with over use of mocking is that it couples your tests to the
283implementation of your mocks rather than your real code. Suppose you have a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100284class that implements ``some_method``. In a test for another class, you
285provide a mock of this object that *also* provides ``some_method``. If later
286you refactor the first class, so that it no longer has ``some_method`` - then
Michael Foorda9e6fb22012-03-28 14:36:02 +0100287your tests will continue to pass even though your code is now broken!
288
Georg Brandl7ad3df62014-10-31 07:59:37 +0100289:class:`Mock` allows you to provide an object as a specification for the mock,
290using the *spec* keyword argument. Accessing methods / attributes on the
Michael Foorda9e6fb22012-03-28 14:36:02 +0100291mock that don't exist on your specification object will immediately raise an
292attribute error. If you change the implementation of your specification, then
293tests that use that class will start failing immediately without you having to
294instantiate the class in those tests.
295
296 >>> mock = Mock(spec=SomeClass)
297 >>> mock.old_method()
298 Traceback (most recent call last):
299 ...
300 AttributeError: object has no attribute 'old_method'
301
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100302Using a specification also enables a smarter matching of calls made to the
303mock, regardless of whether some parameters were passed as positional or
304named arguments::
305
306 >>> def f(a, b, c): pass
307 ...
308 >>> mock = Mock(spec=f)
309 >>> mock(1, 2, 3)
310 <Mock name='mock()' id='140161580456576'>
311 >>> mock.assert_called_with(a=1, b=2, c=3)
312
313If you want this smarter matching to also work with method calls on the mock,
314you can use :ref:`auto-speccing <auto-speccing>`.
315
Michael Foorda9e6fb22012-03-28 14:36:02 +0100316If you want a stronger form of specification that prevents the setting
317of arbitrary attributes as well as the getting of them then you can use
Georg Brandl7ad3df62014-10-31 07:59:37 +0100318*spec_set* instead of *spec*.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100319
320
321
322Patch Decorators
323----------------
324
325.. note::
326
Georg Brandl7ad3df62014-10-31 07:59:37 +0100327 With :func:`patch` it matters that you patch objects in the namespace where
328 they are looked up. This is normally straightforward, but for a quick guide
Michael Foorda9e6fb22012-03-28 14:36:02 +0100329 read :ref:`where to patch <where-to-patch>`.
330
331
332A common need in tests is to patch a class attribute or a module attribute,
333for example patching a builtin or patching a class in a module to test that it
334is instantiated. Modules and classes are effectively global, so patching on
335them has to be undone after the test or the patch will persist into other
336tests and cause hard to diagnose problems.
337
Georg Brandl7ad3df62014-10-31 07:59:37 +0100338mock provides three convenient decorators for this: :func:`patch`, :func:`patch.object` and
339:func:`patch.dict`. ``patch`` takes a single string, of the form
340``package.module.Class.attribute`` to specify the attribute you are patching. It
Michael Foorda9e6fb22012-03-28 14:36:02 +0100341also optionally takes a value that you want the attribute (or class or
342whatever) to be replaced with. 'patch.object' takes an object and the name of
343the attribute you would like patched, plus optionally the value to patch it
344with.
345
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200346``patch.object``::
Michael Foorda9e6fb22012-03-28 14:36:02 +0100347
348 >>> original = SomeClass.attribute
349 >>> @patch.object(SomeClass, 'attribute', sentinel.attribute)
350 ... def test():
351 ... assert SomeClass.attribute == sentinel.attribute
352 ...
353 >>> test()
354 >>> assert SomeClass.attribute == original
355
356 >>> @patch('package.module.attribute', sentinel.attribute)
357 ... def test():
358 ... from package.module import attribute
359 ... assert attribute is sentinel.attribute
360 ...
361 >>> test()
362
Georg Brandl7ad3df62014-10-31 07:59:37 +0100363If you are patching a module (including :mod:`builtins`) then use :func:`patch`
364instead of :func:`patch.object`:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100365
Ezio Melottib40a2202013-03-30 05:55:52 +0200366 >>> mock = MagicMock(return_value=sentinel.file_handle)
367 >>> with patch('builtins.open', mock):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100368 ... handle = open('filename', 'r')
369 ...
370 >>> mock.assert_called_with('filename', 'r')
371 >>> assert handle == sentinel.file_handle, "incorrect file handle returned"
372
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200373The module name can be 'dotted', in the form ``package.module`` if needed::
Michael Foorda9e6fb22012-03-28 14:36:02 +0100374
375 >>> @patch('package.module.ClassName.attribute', sentinel.attribute)
376 ... def test():
377 ... from package.module import ClassName
378 ... assert ClassName.attribute == sentinel.attribute
379 ...
380 >>> test()
381
382A nice pattern is to actually decorate test methods themselves:
383
Berker Peksagb31daff2016-04-02 04:32:06 +0300384 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100385 ... @patch.object(SomeClass, 'attribute', sentinel.attribute)
386 ... def test_something(self):
387 ... self.assertEqual(SomeClass.attribute, sentinel.attribute)
388 ...
389 >>> original = SomeClass.attribute
390 >>> MyTest('test_something').test_something()
391 >>> assert SomeClass.attribute == original
392
Georg Brandl7ad3df62014-10-31 07:59:37 +0100393If you want to patch with a Mock, you can use :func:`patch` with only one argument
394(or :func:`patch.object` with two arguments). The mock will be created for you and
Michael Foorda9e6fb22012-03-28 14:36:02 +0100395passed into the test function / method:
396
Berker Peksagb31daff2016-04-02 04:32:06 +0300397 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100398 ... @patch.object(SomeClass, 'static_method')
399 ... def test_something(self, mock_method):
400 ... SomeClass.static_method()
401 ... mock_method.assert_called_with()
402 ...
403 >>> MyTest('test_something').test_something()
404
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200405You can stack up multiple patch decorators using this pattern::
Michael Foorda9e6fb22012-03-28 14:36:02 +0100406
Berker Peksagb31daff2016-04-02 04:32:06 +0300407 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100408 ... @patch('package.module.ClassName1')
409 ... @patch('package.module.ClassName2')
410 ... def test_something(self, MockClass2, MockClass1):
Ezio Melottie2123702013-01-10 03:43:33 +0200411 ... self.assertIs(package.module.ClassName1, MockClass1)
412 ... self.assertIs(package.module.ClassName2, MockClass2)
Michael Foorda9e6fb22012-03-28 14:36:02 +0100413 ...
414 >>> MyTest('test_something').test_something()
415
416When you nest patch decorators the mocks are passed in to the decorated
Andrés Delfino271818f2018-09-14 14:13:09 -0300417function in the same order they applied (the normal *Python* order that
Michael Foorda9e6fb22012-03-28 14:36:02 +0100418decorators are applied). This means from the bottom up, so in the example
Georg Brandl7ad3df62014-10-31 07:59:37 +0100419above the mock for ``test_module.ClassName2`` is passed in first.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100420
421There is also :func:`patch.dict` for setting values in a dictionary just
422during a scope and restoring the dictionary to its original state when the test
423ends:
424
425 >>> foo = {'key': 'value'}
426 >>> original = foo.copy()
427 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
428 ... assert foo == {'newkey': 'newvalue'}
429 ...
430 >>> assert foo == original
431
Georg Brandl7ad3df62014-10-31 07:59:37 +0100432``patch``, ``patch.object`` and ``patch.dict`` can all be used as context managers.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100433
Georg Brandl7ad3df62014-10-31 07:59:37 +0100434Where you use :func:`patch` to create a mock for you, you can get a reference to the
Michael Foorda9e6fb22012-03-28 14:36:02 +0100435mock using the "as" form of the with statement:
436
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200437 >>> class ProductionClass:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100438 ... def method(self):
439 ... pass
440 ...
441 >>> with patch.object(ProductionClass, 'method') as mock_method:
442 ... mock_method.return_value = None
443 ... real = ProductionClass()
444 ... real.method(1, 2, 3)
445 ...
446 >>> mock_method.assert_called_with(1, 2, 3)
447
448
Georg Brandl7ad3df62014-10-31 07:59:37 +0100449As an alternative ``patch``, ``patch.object`` and ``patch.dict`` can be used as
Michael Foorda9e6fb22012-03-28 14:36:02 +0100450class decorators. When used in this way it is the same as applying the
Larry Hastings3732ed22014-03-15 21:13:56 -0700451decorator individually to every method whose name starts with "test".
Michael Foorda9e6fb22012-03-28 14:36:02 +0100452
453
454.. _further-examples:
455
456Further Examples
Georg Brandl7fc972a2013-02-03 14:00:04 +0100457----------------
Michael Foorda9e6fb22012-03-28 14:36:02 +0100458
459
460Here are some more examples for some slightly more advanced scenarios.
Michael Foord944e02d2012-03-25 23:12:55 +0100461
462
463Mocking chained calls
Georg Brandl7fc972a2013-02-03 14:00:04 +0100464~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100465
466Mocking chained calls is actually straightforward with mock once you
467understand the :attr:`~Mock.return_value` attribute. When a mock is called for
Georg Brandl7ad3df62014-10-31 07:59:37 +0100468the first time, or you fetch its ``return_value`` before it has been called, a
469new :class:`Mock` is created.
Michael Foord944e02d2012-03-25 23:12:55 +0100470
471This means that you can see how the object returned from a call to a mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +0100472object has been used by interrogating the ``return_value`` mock:
Michael Foord944e02d2012-03-25 23:12:55 +0100473
474 >>> mock = Mock()
475 >>> mock().foo(a=2, b=3)
476 <Mock name='mock().foo()' id='...'>
477 >>> mock.return_value.foo.assert_called_with(a=2, b=3)
478
479From here it is a simple step to configure and then make assertions about
480chained calls. Of course another alternative is writing your code in a more
481testable way in the first place...
482
483So, suppose we have some code that looks a little bit like this:
484
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200485 >>> class Something:
Michael Foord944e02d2012-03-25 23:12:55 +0100486 ... def __init__(self):
487 ... self.backend = BackendProvider()
488 ... def method(self):
489 ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
490 ... # more code
491
Georg Brandl7ad3df62014-10-31 07:59:37 +0100492Assuming that ``BackendProvider`` is already well tested, how do we test
493``method()``? Specifically, we want to test that the code section ``# more
494code`` uses the response object in the correct way.
Michael Foord944e02d2012-03-25 23:12:55 +0100495
496As this chain of calls is made from an instance attribute we can monkey patch
Georg Brandl7ad3df62014-10-31 07:59:37 +0100497the ``backend`` attribute on a ``Something`` instance. In this particular case
Michael Foord944e02d2012-03-25 23:12:55 +0100498we are only interested in the return value from the final call to
Georg Brandl7ad3df62014-10-31 07:59:37 +0100499``start_call`` so we don't have much configuration to do. Let's assume the
Michael Foord944e02d2012-03-25 23:12:55 +0100500object it returns is 'file-like', so we'll ensure that our response object
Georg Brandl7ad3df62014-10-31 07:59:37 +0100501uses the builtin :func:`open` as its ``spec``.
Michael Foord944e02d2012-03-25 23:12:55 +0100502
503To do this we create a mock instance as our mock backend and create a mock
504response object for it. To set the response as the return value for that final
Georg Brandl7ad3df62014-10-31 07:59:37 +0100505``start_call`` we could do this::
Michael Foord944e02d2012-03-25 23:12:55 +0100506
Georg Brandl7ad3df62014-10-31 07:59:37 +0100507 mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response
Michael Foord944e02d2012-03-25 23:12:55 +0100508
509We can do that in a slightly nicer way using the :meth:`~Mock.configure_mock`
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200510method to directly set the return value for us::
Michael Foord944e02d2012-03-25 23:12:55 +0100511
512 >>> something = Something()
Terry Jan Reedy30ffe7e2014-01-21 00:01:51 -0500513 >>> mock_response = Mock(spec=open)
Michael Foord944e02d2012-03-25 23:12:55 +0100514 >>> mock_backend = Mock()
515 >>> config = {'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response}
516 >>> mock_backend.configure_mock(**config)
517
518With these we monkey patch the "mock backend" in place and can make the real
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200519call::
Michael Foord944e02d2012-03-25 23:12:55 +0100520
521 >>> something.backend = mock_backend
522 >>> something.method()
523
524Using :attr:`~Mock.mock_calls` we can check the chained call with a single
525assert. A chained call is several calls in one line of code, so there will be
Georg Brandl7ad3df62014-10-31 07:59:37 +0100526several entries in ``mock_calls``. We can use :meth:`call.call_list` to create
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200527this list of calls for us::
Michael Foord944e02d2012-03-25 23:12:55 +0100528
529 >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
530 >>> call_list = chained.call_list()
531 >>> assert mock_backend.mock_calls == call_list
532
533
534Partial mocking
Georg Brandl7fc972a2013-02-03 14:00:04 +0100535~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100536
Georg Brandl7ad3df62014-10-31 07:59:37 +0100537In some tests I wanted to mock out a call to :meth:`datetime.date.today`
Georg Brandl728e4de2014-10-29 09:00:30 +0100538to return a known date, but I didn't want to prevent the code under test from
Georg Brandl7ad3df62014-10-31 07:59:37 +0100539creating new date objects. Unfortunately :class:`datetime.date` is written in C, and
540so I couldn't just monkey-patch out the static :meth:`date.today` method.
Michael Foord944e02d2012-03-25 23:12:55 +0100541
542I found a simple way of doing this that involved effectively wrapping the date
543class with a mock, but passing through calls to the constructor to the real
544class (and returning real instances).
545
546The :func:`patch decorator <patch>` is used here to
Georg Brandl7ad3df62014-10-31 07:59:37 +0100547mock out the ``date`` class in the module under test. The :attr:`side_effect`
Michael Foord944e02d2012-03-25 23:12:55 +0100548attribute on the mock date class is then set to a lambda function that returns
549a real date. When the mock date class is called a real date will be
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200550constructed and returned by ``side_effect``. ::
Michael Foord944e02d2012-03-25 23:12:55 +0100551
552 >>> from datetime import date
553 >>> with patch('mymodule.date') as mock_date:
554 ... mock_date.today.return_value = date(2010, 10, 8)
555 ... mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
556 ...
557 ... assert mymodule.date.today() == date(2010, 10, 8)
558 ... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
Michael Foord944e02d2012-03-25 23:12:55 +0100559
Georg Brandl7ad3df62014-10-31 07:59:37 +0100560Note that we don't patch :class:`datetime.date` globally, we patch ``date`` in the
Michael Foord944e02d2012-03-25 23:12:55 +0100561module that *uses* it. See :ref:`where to patch <where-to-patch>`.
562
Georg Brandl7ad3df62014-10-31 07:59:37 +0100563When ``date.today()`` is called a known date is returned, but calls to the
564``date(...)`` constructor still return normal dates. Without this you can find
Michael Foord944e02d2012-03-25 23:12:55 +0100565yourself having to calculate an expected result using exactly the same
566algorithm as the code under test, which is a classic testing anti-pattern.
567
Georg Brandl7ad3df62014-10-31 07:59:37 +0100568Calls to the date constructor are recorded in the ``mock_date`` attributes
569(``call_count`` and friends) which may also be useful for your tests.
Michael Foord944e02d2012-03-25 23:12:55 +0100570
571An alternative way of dealing with mocking dates, or other builtin classes,
572is discussed in `this blog entry
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300573<https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/>`_.
Michael Foord944e02d2012-03-25 23:12:55 +0100574
575
576Mocking a Generator Method
Georg Brandl7fc972a2013-02-03 14:00:04 +0100577~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100578
Georg Brandl728e4de2014-10-29 09:00:30 +0100579A Python generator is a function or method that uses the :keyword:`yield` statement
580to return a series of values when iterated over [#]_.
Michael Foord944e02d2012-03-25 23:12:55 +0100581
582A generator method / function is called to return the generator object. It is
583the generator object that is then iterated over. The protocol method for
Georg Brandl728e4de2014-10-29 09:00:30 +0100584iteration is :meth:`~container.__iter__`, so we can
Georg Brandl7ad3df62014-10-31 07:59:37 +0100585mock this using a :class:`MagicMock`.
Michael Foord944e02d2012-03-25 23:12:55 +0100586
587Here's an example class with an "iter" method implemented as a generator:
588
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200589 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100590 ... def iter(self):
591 ... for i in [1, 2, 3]:
592 ... yield i
593 ...
594 >>> foo = Foo()
595 >>> list(foo.iter())
596 [1, 2, 3]
597
598
599How would we mock this class, and in particular its "iter" method?
600
601To configure the values returned from the iteration (implicit in the call to
Georg Brandl7ad3df62014-10-31 07:59:37 +0100602:class:`list`), we need to configure the object returned by the call to ``foo.iter()``.
Michael Foord944e02d2012-03-25 23:12:55 +0100603
604 >>> mock_foo = MagicMock()
605 >>> mock_foo.iter.return_value = iter([1, 2, 3])
606 >>> list(mock_foo.iter())
607 [1, 2, 3]
608
609.. [#] There are also generator expressions and more `advanced uses
610 <http://www.dabeaz.com/coroutines/index.html>`_ of generators, but we aren't
611 concerned about them here. A very good introduction to generators and how
612 powerful they are is: `Generator Tricks for Systems Programmers
613 <http://www.dabeaz.com/generators/>`_.
614
615
616Applying the same patch to every test method
Georg Brandl7fc972a2013-02-03 14:00:04 +0100617~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100618
619If you want several patches in place for multiple test methods the obvious way
620is to apply the patch decorators to every method. This can feel like unnecessary
Georg Brandl7ad3df62014-10-31 07:59:37 +0100621repetition. For Python 2.6 or more recent you can use :func:`patch` (in all its
Michael Foord944e02d2012-03-25 23:12:55 +0100622various forms) as a class decorator. This applies the patches to all test
623methods on the class. A test method is identified by methods whose names start
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200624with ``test``::
Michael Foord944e02d2012-03-25 23:12:55 +0100625
626 >>> @patch('mymodule.SomeClass')
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200627 ... class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100628 ...
629 ... def test_one(self, MockSomeClass):
Ezio Melottie2123702013-01-10 03:43:33 +0200630 ... self.assertIs(mymodule.SomeClass, MockSomeClass)
Michael Foord944e02d2012-03-25 23:12:55 +0100631 ...
632 ... def test_two(self, MockSomeClass):
Ezio Melottie2123702013-01-10 03:43:33 +0200633 ... self.assertIs(mymodule.SomeClass, MockSomeClass)
Michael Foord944e02d2012-03-25 23:12:55 +0100634 ...
635 ... def not_a_test(self):
636 ... return 'something'
637 ...
638 >>> MyTest('test_one').test_one()
639 >>> MyTest('test_two').test_two()
640 >>> MyTest('test_two').not_a_test()
641 'something'
642
643An alternative way of managing patches is to use the :ref:`start-and-stop`.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100644These allow you to move the patching into your ``setUp`` and ``tearDown`` methods.
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200645::
Michael Foord944e02d2012-03-25 23:12:55 +0100646
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200647 >>> class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100648 ... def setUp(self):
649 ... self.patcher = patch('mymodule.foo')
650 ... self.mock_foo = self.patcher.start()
651 ...
652 ... def test_foo(self):
Ezio Melottie2123702013-01-10 03:43:33 +0200653 ... self.assertIs(mymodule.foo, self.mock_foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100654 ...
655 ... def tearDown(self):
656 ... self.patcher.stop()
657 ...
658 >>> MyTest('test_foo').run()
659
660If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +0100661calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foord944e02d2012-03-25 23:12:55 +0100662exception is raised in the setUp then tearDown is not called.
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200663:meth:`unittest.TestCase.addCleanup` makes this easier::
Michael Foord944e02d2012-03-25 23:12:55 +0100664
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200665 >>> class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100666 ... def setUp(self):
667 ... patcher = patch('mymodule.foo')
668 ... self.addCleanup(patcher.stop)
669 ... self.mock_foo = patcher.start()
670 ...
671 ... def test_foo(self):
Ezio Melottie2123702013-01-10 03:43:33 +0200672 ... self.assertIs(mymodule.foo, self.mock_foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100673 ...
674 >>> MyTest('test_foo').run()
675
676
677Mocking Unbound Methods
Georg Brandl7fc972a2013-02-03 14:00:04 +0100678~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100679
680Whilst writing tests today I needed to patch an *unbound method* (patching the
681method on the class rather than on the instance). I needed self to be passed
682in as the first argument because I want to make asserts about which objects
683were calling this particular method. The issue is that you can't patch with a
684mock for this, because if you replace an unbound method with a mock it doesn't
685become a bound method when fetched from the instance, and so it doesn't get
686self passed in. The workaround is to patch the unbound method with a real
687function instead. The :func:`patch` decorator makes it so simple to
688patch out methods with a mock that having to create a real function becomes a
689nuisance.
690
Georg Brandl7ad3df62014-10-31 07:59:37 +0100691If you pass ``autospec=True`` to patch then it does the patching with a
Michael Foord944e02d2012-03-25 23:12:55 +0100692*real* function object. This function object has the same signature as the one
693it is replacing, but delegates to a mock under the hood. You still get your
694mock auto-created in exactly the same way as before. What it means though, is
695that if you use it to patch out an unbound method on a class the mocked
696function will be turned into a bound method if it is fetched from an instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100697It will have ``self`` passed in as the first argument, which is exactly what I
Michael Foord944e02d2012-03-25 23:12:55 +0100698wanted:
699
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200700 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100701 ... def foo(self):
702 ... pass
703 ...
704 >>> with patch.object(Foo, 'foo', autospec=True) as mock_foo:
705 ... mock_foo.return_value = 'foo'
706 ... foo = Foo()
707 ... foo.foo()
708 ...
709 'foo'
710 >>> mock_foo.assert_called_once_with(foo)
711
Georg Brandl7ad3df62014-10-31 07:59:37 +0100712If we don't use ``autospec=True`` then the unbound method is patched out
713with a Mock instance instead, and isn't called with ``self``.
Michael Foord944e02d2012-03-25 23:12:55 +0100714
715
716Checking multiple calls with mock
Georg Brandl7fc972a2013-02-03 14:00:04 +0100717~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100718
719mock has a nice API for making assertions about how your mock objects are used.
720
721 >>> mock = Mock()
722 >>> mock.foo_bar.return_value = None
723 >>> mock.foo_bar('baz', spam='eggs')
724 >>> mock.foo_bar.assert_called_with('baz', spam='eggs')
725
726If your mock is only being called once you can use the
727:meth:`assert_called_once_with` method that also asserts that the
728:attr:`call_count` is one.
729
730 >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
731 >>> mock.foo_bar()
732 >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
733 Traceback (most recent call last):
734 ...
735 AssertionError: Expected to be called once. Called 2 times.
736
Georg Brandl7ad3df62014-10-31 07:59:37 +0100737Both ``assert_called_with`` and ``assert_called_once_with`` make assertions about
Michael Foord944e02d2012-03-25 23:12:55 +0100738the *most recent* call. If your mock is going to be called several times, and
739you want to make assertions about *all* those calls you can use
740:attr:`~Mock.call_args_list`:
741
742 >>> mock = Mock(return_value=None)
743 >>> mock(1, 2, 3)
744 >>> mock(4, 5, 6)
745 >>> mock()
746 >>> mock.call_args_list
747 [call(1, 2, 3), call(4, 5, 6), call()]
748
749The :data:`call` helper makes it easy to make assertions about these calls. You
Georg Brandl7ad3df62014-10-31 07:59:37 +0100750can build up a list of expected calls and compare it to ``call_args_list``. This
751looks remarkably similar to the repr of the ``call_args_list``:
Michael Foord944e02d2012-03-25 23:12:55 +0100752
753 >>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
754 >>> mock.call_args_list == expected
755 True
756
757
758Coping with mutable arguments
Georg Brandl7fc972a2013-02-03 14:00:04 +0100759~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100760
761Another situation is rare, but can bite you, is when your mock is called with
Georg Brandl7ad3df62014-10-31 07:59:37 +0100762mutable arguments. ``call_args`` and ``call_args_list`` store *references* to the
Michael Foord944e02d2012-03-25 23:12:55 +0100763arguments. If the arguments are mutated by the code under test then you can no
764longer make assertions about what the values were when the mock was called.
765
766Here's some example code that shows the problem. Imagine the following functions
767defined in 'mymodule'::
768
769 def frob(val):
770 pass
771
772 def grob(val):
773 "First frob and then clear val"
774 frob(val)
775 val.clear()
776
Georg Brandl7ad3df62014-10-31 07:59:37 +0100777When we try to test that ``grob`` calls ``frob`` with the correct argument look
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200778what happens::
Michael Foord944e02d2012-03-25 23:12:55 +0100779
780 >>> with patch('mymodule.frob') as mock_frob:
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200781 ... val = {6}
Michael Foord944e02d2012-03-25 23:12:55 +0100782 ... mymodule.grob(val)
783 ...
784 >>> val
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200785 set()
786 >>> mock_frob.assert_called_with({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100787 Traceback (most recent call last):
788 ...
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200789 AssertionError: Expected: (({6},), {})
790 Called with: ((set(),), {})
Michael Foord944e02d2012-03-25 23:12:55 +0100791
792One possibility would be for mock to copy the arguments you pass in. This
793could then cause problems if you do assertions that rely on object identity
794for equality.
795
796Here's one solution that uses the :attr:`side_effect`
Georg Brandl7ad3df62014-10-31 07:59:37 +0100797functionality. If you provide a ``side_effect`` function for a mock then
798``side_effect`` will be called with the same args as the mock. This gives us an
Michael Foord944e02d2012-03-25 23:12:55 +0100799opportunity to copy the arguments and store them for later assertions. In this
800example I'm using *another* mock to store the arguments so that I can use the
801mock methods for doing the assertion. Again a helper function sets this up for
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200802me. ::
Michael Foord944e02d2012-03-25 23:12:55 +0100803
804 >>> from copy import deepcopy
805 >>> from unittest.mock import Mock, patch, DEFAULT
806 >>> def copy_call_args(mock):
807 ... new_mock = Mock()
808 ... def side_effect(*args, **kwargs):
809 ... args = deepcopy(args)
810 ... kwargs = deepcopy(kwargs)
811 ... new_mock(*args, **kwargs)
812 ... return DEFAULT
813 ... mock.side_effect = side_effect
814 ... return new_mock
815 ...
816 >>> with patch('mymodule.frob') as mock_frob:
817 ... new_mock = copy_call_args(mock_frob)
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200818 ... val = {6}
Michael Foord944e02d2012-03-25 23:12:55 +0100819 ... mymodule.grob(val)
820 ...
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200821 >>> new_mock.assert_called_with({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100822 >>> new_mock.call_args
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200823 call({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100824
Georg Brandl7ad3df62014-10-31 07:59:37 +0100825``copy_call_args`` is called with the mock that will be called. It returns a new
826mock that we do the assertion on. The ``side_effect`` function makes a copy of
827the args and calls our ``new_mock`` with the copy.
Michael Foord944e02d2012-03-25 23:12:55 +0100828
829.. note::
830
831 If your mock is only going to be used once there is an easier way of
832 checking arguments at the point they are called. You can simply do the
Georg Brandl7ad3df62014-10-31 07:59:37 +0100833 checking inside a ``side_effect`` function.
Michael Foord944e02d2012-03-25 23:12:55 +0100834
835 >>> def side_effect(arg):
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200836 ... assert arg == {6}
Michael Foord944e02d2012-03-25 23:12:55 +0100837 ...
838 >>> mock = Mock(side_effect=side_effect)
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200839 >>> mock({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100840 >>> mock(set())
841 Traceback (most recent call last):
842 ...
843 AssertionError
844
Georg Brandl7ad3df62014-10-31 07:59:37 +0100845An alternative approach is to create a subclass of :class:`Mock` or
846:class:`MagicMock` that copies (using :func:`copy.deepcopy`) the arguments.
Michael Foord944e02d2012-03-25 23:12:55 +0100847Here's an example implementation:
848
849 >>> from copy import deepcopy
850 >>> class CopyingMock(MagicMock):
851 ... def __call__(self, *args, **kwargs):
852 ... args = deepcopy(args)
853 ... kwargs = deepcopy(kwargs)
854 ... return super(CopyingMock, self).__call__(*args, **kwargs)
855 ...
856 >>> c = CopyingMock(return_value=None)
857 >>> arg = set()
858 >>> c(arg)
859 >>> arg.add(1)
860 >>> c.assert_called_with(set())
861 >>> c.assert_called_with(arg)
862 Traceback (most recent call last):
863 ...
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200864 AssertionError: Expected call: mock({1})
865 Actual call: mock(set())
Michael Foord944e02d2012-03-25 23:12:55 +0100866 >>> c.foo
867 <CopyingMock name='mock.foo' id='...'>
868
Georg Brandl7ad3df62014-10-31 07:59:37 +0100869When you subclass ``Mock`` or ``MagicMock`` all dynamically created attributes,
870and the ``return_value`` will use your subclass automatically. That means all
871children of a ``CopyingMock`` will also have the type ``CopyingMock``.
Michael Foord944e02d2012-03-25 23:12:55 +0100872
873
Michael Foord944e02d2012-03-25 23:12:55 +0100874Nesting Patches
Georg Brandl7fc972a2013-02-03 14:00:04 +0100875~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100876
877Using patch as a context manager is nice, but if you do multiple patches you
878can end up with nested with statements indenting further and further to the
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200879right::
Michael Foord944e02d2012-03-25 23:12:55 +0100880
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200881 >>> class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100882 ...
883 ... def test_foo(self):
884 ... with patch('mymodule.Foo') as mock_foo:
885 ... with patch('mymodule.Bar') as mock_bar:
886 ... with patch('mymodule.Spam') as mock_spam:
887 ... assert mymodule.Foo is mock_foo
888 ... assert mymodule.Bar is mock_bar
889 ... assert mymodule.Spam is mock_spam
890 ...
891 >>> original = mymodule.Foo
892 >>> MyTest('test_foo').test_foo()
893 >>> assert mymodule.Foo is original
894
Georg Brandl7ad3df62014-10-31 07:59:37 +0100895With unittest ``cleanup`` functions and the :ref:`start-and-stop` we can
Michael Foord944e02d2012-03-25 23:12:55 +0100896achieve the same effect without the nested indentation. A simple helper
Georg Brandl7ad3df62014-10-31 07:59:37 +0100897method, ``create_patch``, puts the patch in place and returns the created mock
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200898for us::
Michael Foord944e02d2012-03-25 23:12:55 +0100899
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200900 >>> class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100901 ...
902 ... def create_patch(self, name):
903 ... patcher = patch(name)
904 ... thing = patcher.start()
905 ... self.addCleanup(patcher.stop)
906 ... return thing
907 ...
908 ... def test_foo(self):
909 ... mock_foo = self.create_patch('mymodule.Foo')
910 ... mock_bar = self.create_patch('mymodule.Bar')
911 ... mock_spam = self.create_patch('mymodule.Spam')
912 ...
913 ... assert mymodule.Foo is mock_foo
914 ... assert mymodule.Bar is mock_bar
915 ... assert mymodule.Spam is mock_spam
916 ...
917 >>> original = mymodule.Foo
918 >>> MyTest('test_foo').run()
919 >>> assert mymodule.Foo is original
920
921
922Mocking a dictionary with MagicMock
Georg Brandl7fc972a2013-02-03 14:00:04 +0100923~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100924
925You may want to mock a dictionary, or other container object, recording all
926access to it whilst having it still behave like a dictionary.
927
928We can do this with :class:`MagicMock`, which will behave like a dictionary,
929and using :data:`~Mock.side_effect` to delegate dictionary access to a real
930underlying dictionary that is under our control.
931
Georg Brandl7ad3df62014-10-31 07:59:37 +0100932When the :meth:`__getitem__` and :meth:`__setitem__` methods of our ``MagicMock`` are called
933(normal dictionary access) then ``side_effect`` is called with the key (and in
934the case of ``__setitem__`` the value too). We can also control what is returned.
Michael Foord944e02d2012-03-25 23:12:55 +0100935
Georg Brandl7ad3df62014-10-31 07:59:37 +0100936After the ``MagicMock`` has been used we can use attributes like
Michael Foord944e02d2012-03-25 23:12:55 +0100937:data:`~Mock.call_args_list` to assert about how the dictionary was used:
938
939 >>> my_dict = {'a': 1, 'b': 2, 'c': 3}
940 >>> def getitem(name):
941 ... return my_dict[name]
942 ...
943 >>> def setitem(name, val):
944 ... my_dict[name] = val
945 ...
946 >>> mock = MagicMock()
947 >>> mock.__getitem__.side_effect = getitem
948 >>> mock.__setitem__.side_effect = setitem
949
950.. note::
951
Georg Brandl7ad3df62014-10-31 07:59:37 +0100952 An alternative to using ``MagicMock`` is to use ``Mock`` and *only* provide
Michael Foord944e02d2012-03-25 23:12:55 +0100953 the magic methods you specifically want:
954
955 >>> mock = Mock()
Éric Araujo0b1be1a2014-03-17 16:48:13 -0400956 >>> mock.__getitem__ = Mock(side_effect=getitem)
957 >>> mock.__setitem__ = Mock(side_effect=setitem)
Michael Foord944e02d2012-03-25 23:12:55 +0100958
Georg Brandl7ad3df62014-10-31 07:59:37 +0100959 A *third* option is to use ``MagicMock`` but passing in ``dict`` as the *spec*
960 (or *spec_set*) argument so that the ``MagicMock`` created only has
Michael Foord944e02d2012-03-25 23:12:55 +0100961 dictionary magic methods available:
962
963 >>> mock = MagicMock(spec_set=dict)
964 >>> mock.__getitem__.side_effect = getitem
965 >>> mock.__setitem__.side_effect = setitem
966
Georg Brandl7ad3df62014-10-31 07:59:37 +0100967With these side effect functions in place, the ``mock`` will behave like a normal
968dictionary but recording the access. It even raises a :exc:`KeyError` if you try
Michael Foord944e02d2012-03-25 23:12:55 +0100969to access a key that doesn't exist.
970
971 >>> mock['a']
972 1
973 >>> mock['c']
974 3
975 >>> mock['d']
976 Traceback (most recent call last):
977 ...
978 KeyError: 'd'
979 >>> mock['b'] = 'fish'
980 >>> mock['d'] = 'eggs'
981 >>> mock['b']
982 'fish'
983 >>> mock['d']
984 'eggs'
985
986After it has been used you can make assertions about the access using the normal
987mock methods and attributes:
988
989 >>> mock.__getitem__.call_args_list
990 [call('a'), call('c'), call('d'), call('b'), call('d')]
991 >>> mock.__setitem__.call_args_list
992 [call('b', 'fish'), call('d', 'eggs')]
993 >>> my_dict
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200994 {'a': 1, 'b': 'fish', 'c': 3, 'd': 'eggs'}
Michael Foord944e02d2012-03-25 23:12:55 +0100995
996
997Mock subclasses and their attributes
Georg Brandl7fc972a2013-02-03 14:00:04 +0100998~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100999
Georg Brandl7ad3df62014-10-31 07:59:37 +01001000There are various reasons why you might want to subclass :class:`Mock`. One
1001reason might be to add helper methods. Here's a silly example:
Michael Foord944e02d2012-03-25 23:12:55 +01001002
1003 >>> class MyMock(MagicMock):
1004 ... def has_been_called(self):
1005 ... return self.called
1006 ...
1007 >>> mymock = MyMock(return_value=None)
1008 >>> mymock
1009 <MyMock id='...'>
1010 >>> mymock.has_been_called()
1011 False
1012 >>> mymock()
1013 >>> mymock.has_been_called()
1014 True
1015
Georg Brandl7ad3df62014-10-31 07:59:37 +01001016The standard behaviour for ``Mock`` instances is that attributes and the return
Michael Foord944e02d2012-03-25 23:12:55 +01001017value mocks are of the same type as the mock they are accessed on. This ensures
Georg Brandl7ad3df62014-10-31 07:59:37 +01001018that ``Mock`` attributes are ``Mocks`` and ``MagicMock`` attributes are ``MagicMocks``
Michael Foord944e02d2012-03-25 23:12:55 +01001019[#]_. So if you're subclassing to add helper methods then they'll also be
1020available on the attributes and return value mock of instances of your
1021subclass.
1022
1023 >>> mymock.foo
1024 <MyMock name='mock.foo' id='...'>
1025 >>> mymock.foo.has_been_called()
1026 False
1027 >>> mymock.foo()
1028 <MyMock name='mock.foo()' id='...'>
1029 >>> mymock.foo.has_been_called()
1030 True
1031
1032Sometimes this is inconvenient. For example, `one user
Sanyam Khurana338cd832018-01-20 05:55:37 +05301033<https://code.google.com/archive/p/mock/issues/105>`_ is subclassing mock to
Michael Foord944e02d2012-03-25 23:12:55 +01001034created a `Twisted adaptor
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001035<https://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html>`_.
Michael Foord944e02d2012-03-25 23:12:55 +01001036Having this applied to attributes too actually causes errors.
1037
Georg Brandl7ad3df62014-10-31 07:59:37 +01001038``Mock`` (in all its flavours) uses a method called ``_get_child_mock`` to create
Michael Foord944e02d2012-03-25 23:12:55 +01001039these "sub-mocks" for attributes and return values. You can prevent your
1040subclass being used for attributes by overriding this method. The signature is
Georg Brandl7ad3df62014-10-31 07:59:37 +01001041that it takes arbitrary keyword arguments (``**kwargs``) which are then passed
Michael Foord944e02d2012-03-25 23:12:55 +01001042onto the mock constructor:
1043
1044 >>> class Subclass(MagicMock):
1045 ... def _get_child_mock(self, **kwargs):
1046 ... return MagicMock(**kwargs)
1047 ...
1048 >>> mymock = Subclass()
1049 >>> mymock.foo
1050 <MagicMock name='mock.foo' id='...'>
1051 >>> assert isinstance(mymock, Subclass)
1052 >>> assert not isinstance(mymock.foo, Subclass)
1053 >>> assert not isinstance(mymock(), Subclass)
1054
1055.. [#] An exception to this rule are the non-callable mocks. Attributes use the
1056 callable variant because otherwise non-callable mocks couldn't have callable
1057 methods.
1058
1059
1060Mocking imports with patch.dict
Georg Brandl7fc972a2013-02-03 14:00:04 +01001061~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001062
1063One situation where mocking can be hard is where you have a local import inside
1064a function. These are harder to mock because they aren't using an object from
1065the module namespace that we can patch out.
1066
1067Generally local imports are to be avoided. They are sometimes done to prevent
1068circular dependencies, for which there is *usually* a much better way to solve
1069the problem (refactor the code) or to prevent "up front costs" by delaying the
1070import. This can also be solved in better ways than an unconditional local
1071import (store the module as a class or module attribute and only do the import
1072on first use).
1073
Georg Brandl7ad3df62014-10-31 07:59:37 +01001074That aside there is a way to use ``mock`` to affect the results of an import.
1075Importing fetches an *object* from the :data:`sys.modules` dictionary. Note that it
Michael Foord944e02d2012-03-25 23:12:55 +01001076fetches an *object*, which need not be a module. Importing a module for the
1077first time results in a module object being put in `sys.modules`, so usually
1078when you import something you get a module back. This need not be the case
1079however.
1080
1081This means you can use :func:`patch.dict` to *temporarily* put a mock in place
Georg Brandl7ad3df62014-10-31 07:59:37 +01001082in :data:`sys.modules`. Any imports whilst this patch is active will fetch the mock.
Michael Foord944e02d2012-03-25 23:12:55 +01001083When the patch is complete (the decorated function exits, the with statement
Georg Brandl7ad3df62014-10-31 07:59:37 +01001084body is complete or ``patcher.stop()`` is called) then whatever was there
Michael Foord944e02d2012-03-25 23:12:55 +01001085previously will be restored safely.
1086
1087Here's an example that mocks out the 'fooble' module.
1088
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001089 >>> import sys
Michael Foord944e02d2012-03-25 23:12:55 +01001090 >>> mock = Mock()
1091 >>> with patch.dict('sys.modules', {'fooble': mock}):
1092 ... import fooble
1093 ... fooble.blob()
1094 ...
1095 <Mock name='mock.blob()' id='...'>
1096 >>> assert 'fooble' not in sys.modules
1097 >>> mock.blob.assert_called_once_with()
1098
Georg Brandl7ad3df62014-10-31 07:59:37 +01001099As you can see the ``import fooble`` succeeds, but on exit there is no 'fooble'
1100left in :data:`sys.modules`.
Michael Foord944e02d2012-03-25 23:12:55 +01001101
Georg Brandl7ad3df62014-10-31 07:59:37 +01001102This also works for the ``from module import name`` form:
Michael Foord944e02d2012-03-25 23:12:55 +01001103
1104 >>> mock = Mock()
1105 >>> with patch.dict('sys.modules', {'fooble': mock}):
1106 ... from fooble import blob
1107 ... blob.blip()
1108 ...
1109 <Mock name='mock.blob.blip()' id='...'>
1110 >>> mock.blob.blip.assert_called_once_with()
1111
1112With slightly more work you can also mock package imports:
1113
1114 >>> mock = Mock()
1115 >>> modules = {'package': mock, 'package.module': mock.module}
1116 >>> with patch.dict('sys.modules', modules):
1117 ... from package.module import fooble
1118 ... fooble()
1119 ...
1120 <Mock name='mock.module.fooble()' id='...'>
1121 >>> mock.module.fooble.assert_called_once_with()
1122
1123
1124Tracking order of calls and less verbose call assertions
Georg Brandl7fc972a2013-02-03 14:00:04 +01001125~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001126
1127The :class:`Mock` class allows you to track the *order* of method calls on
1128your mock objects through the :attr:`~Mock.method_calls` attribute. This
1129doesn't allow you to track the order of calls between separate mock objects,
1130however we can use :attr:`~Mock.mock_calls` to achieve the same effect.
1131
Georg Brandl7ad3df62014-10-31 07:59:37 +01001132Because mocks track calls to child mocks in ``mock_calls``, and accessing an
Michael Foord944e02d2012-03-25 23:12:55 +01001133arbitrary attribute of a mock creates a child mock, we can create our separate
1134mocks from a parent one. Calls to those child mock will then all be recorded,
Georg Brandl7ad3df62014-10-31 07:59:37 +01001135in order, in the ``mock_calls`` of the parent:
Michael Foord944e02d2012-03-25 23:12:55 +01001136
1137 >>> manager = Mock()
1138 >>> mock_foo = manager.foo
1139 >>> mock_bar = manager.bar
1140
1141 >>> mock_foo.something()
1142 <Mock name='mock.foo.something()' id='...'>
1143 >>> mock_bar.other.thing()
1144 <Mock name='mock.bar.other.thing()' id='...'>
1145
1146 >>> manager.mock_calls
1147 [call.foo.something(), call.bar.other.thing()]
1148
1149We can then assert about the calls, including the order, by comparing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01001150the ``mock_calls`` attribute on the manager mock:
Michael Foord944e02d2012-03-25 23:12:55 +01001151
1152 >>> expected_calls = [call.foo.something(), call.bar.other.thing()]
1153 >>> manager.mock_calls == expected_calls
1154 True
1155
Georg Brandl7ad3df62014-10-31 07:59:37 +01001156If ``patch`` is creating, and putting in place, your mocks then you can attach
Michael Foord944e02d2012-03-25 23:12:55 +01001157them to a manager mock using the :meth:`~Mock.attach_mock` method. After
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001158attaching calls will be recorded in ``mock_calls`` of the manager. ::
Michael Foord944e02d2012-03-25 23:12:55 +01001159
1160 >>> manager = MagicMock()
1161 >>> with patch('mymodule.Class1') as MockClass1:
1162 ... with patch('mymodule.Class2') as MockClass2:
1163 ... manager.attach_mock(MockClass1, 'MockClass1')
1164 ... manager.attach_mock(MockClass2, 'MockClass2')
1165 ... MockClass1().foo()
1166 ... MockClass2().bar()
Michael Foord944e02d2012-03-25 23:12:55 +01001167 <MagicMock name='mock.MockClass1().foo()' id='...'>
1168 <MagicMock name='mock.MockClass2().bar()' id='...'>
1169 >>> manager.mock_calls
1170 [call.MockClass1(),
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001171 call.MockClass1().foo(),
1172 call.MockClass2(),
1173 call.MockClass2().bar()]
Michael Foord944e02d2012-03-25 23:12:55 +01001174
1175If many calls have been made, but you're only interested in a particular
1176sequence of them then an alternative is to use the
1177:meth:`~Mock.assert_has_calls` method. This takes a list of calls (constructed
1178with the :data:`call` object). If that sequence of calls are in
1179:attr:`~Mock.mock_calls` then the assert succeeds.
1180
1181 >>> m = MagicMock()
1182 >>> m().foo().bar().baz()
1183 <MagicMock name='mock().foo().bar().baz()' id='...'>
1184 >>> m.one().two().three()
1185 <MagicMock name='mock.one().two().three()' id='...'>
1186 >>> calls = call.one().two().three().call_list()
1187 >>> m.assert_has_calls(calls)
1188
Georg Brandl7ad3df62014-10-31 07:59:37 +01001189Even though the chained call ``m.one().two().three()`` aren't the only calls that
Michael Foord944e02d2012-03-25 23:12:55 +01001190have been made to the mock, the assert still succeeds.
1191
1192Sometimes a mock may have several calls made to it, and you are only interested
1193in asserting about *some* of those calls. You may not even care about the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001194order. In this case you can pass ``any_order=True`` to ``assert_has_calls``:
Michael Foord944e02d2012-03-25 23:12:55 +01001195
1196 >>> m = MagicMock()
1197 >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
1198 (...)
1199 >>> calls = [call.fifty('50'), call(1), call.seven(7)]
1200 >>> m.assert_has_calls(calls, any_order=True)
1201
1202
1203More complex argument matching
Georg Brandl7fc972a2013-02-03 14:00:04 +01001204~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001205
1206Using the same basic concept as :data:`ANY` we can implement matchers to do more
1207complex assertions on objects used as arguments to mocks.
1208
1209Suppose we expect some object to be passed to a mock that by default
1210compares equal based on object identity (which is the Python default for user
1211defined classes). To use :meth:`~Mock.assert_called_with` we would need to pass
1212in the exact same object. If we are only interested in some of the attributes
1213of this object then we can create a matcher that will check these attributes
1214for us.
1215
Georg Brandl7ad3df62014-10-31 07:59:37 +01001216You can see in this example how a 'standard' call to ``assert_called_with`` isn't
Michael Foord944e02d2012-03-25 23:12:55 +01001217sufficient:
1218
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001219 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +01001220 ... def __init__(self, a, b):
1221 ... self.a, self.b = a, b
1222 ...
1223 >>> mock = Mock(return_value=None)
1224 >>> mock(Foo(1, 2))
1225 >>> mock.assert_called_with(Foo(1, 2))
1226 Traceback (most recent call last):
1227 ...
1228 AssertionError: Expected: call(<__main__.Foo object at 0x...>)
1229 Actual call: call(<__main__.Foo object at 0x...>)
1230
Georg Brandl7ad3df62014-10-31 07:59:37 +01001231A comparison function for our ``Foo`` class might look something like this:
Michael Foord944e02d2012-03-25 23:12:55 +01001232
1233 >>> def compare(self, other):
1234 ... if not type(self) == type(other):
1235 ... return False
1236 ... if self.a != other.a:
1237 ... return False
1238 ... if self.b != other.b:
1239 ... return False
1240 ... return True
1241 ...
1242
1243And a matcher object that can use comparison functions like this for its
1244equality operation would look something like this:
1245
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001246 >>> class Matcher:
Michael Foord944e02d2012-03-25 23:12:55 +01001247 ... def __init__(self, compare, some_obj):
1248 ... self.compare = compare
1249 ... self.some_obj = some_obj
1250 ... def __eq__(self, other):
1251 ... return self.compare(self.some_obj, other)
1252 ...
1253
1254Putting all this together:
1255
1256 >>> match_foo = Matcher(compare, Foo(1, 2))
1257 >>> mock.assert_called_with(match_foo)
1258
Georg Brandl7ad3df62014-10-31 07:59:37 +01001259The ``Matcher`` is instantiated with our compare function and the ``Foo`` object
1260we want to compare against. In ``assert_called_with`` the ``Matcher`` equality
Michael Foord944e02d2012-03-25 23:12:55 +01001261method will be called, which compares the object the mock was called with
1262against the one we created our matcher with. If they match then
Georg Brandl7ad3df62014-10-31 07:59:37 +01001263``assert_called_with`` passes, and if they don't an :exc:`AssertionError` is raised:
Michael Foord944e02d2012-03-25 23:12:55 +01001264
1265 >>> match_wrong = Matcher(compare, Foo(3, 4))
1266 >>> mock.assert_called_with(match_wrong)
1267 Traceback (most recent call last):
1268 ...
1269 AssertionError: Expected: ((<Matcher object at 0x...>,), {})
1270 Called with: ((<Foo object at 0x...>,), {})
1271
1272With a bit of tweaking you could have the comparison function raise the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001273:exc:`AssertionError` directly and provide a more useful failure message.
Michael Foord944e02d2012-03-25 23:12:55 +01001274
1275As of version 1.5, the Python testing library `PyHamcrest
Sanyam Khurana338cd832018-01-20 05:55:37 +05301276<https://pyhamcrest.readthedocs.io/>`_ provides similar functionality,
Michael Foord944e02d2012-03-25 23:12:55 +01001277that may be useful here, in the form of its equality matcher
1278(`hamcrest.library.integration.match_equality
Sanyam Khurana338cd832018-01-20 05:55:37 +05301279<https://pyhamcrest.readthedocs.io/en/release-1.8/integration/#module-hamcrest.library.integration.match_equality>`_).