blob: 00b9bc166a7f36ebfc8f3a0d6bd375816c9ca421 [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
12Using Mock
13----------
14
15Mock Patching Methods
16~~~~~~~~~~~~~~~~~~~~~
17
18Common uses for :class:`Mock` objects include:
19
20* Patching methods
21* Recording method calls on objects
22
23You might want to replace a method on an object to check that
24it is called with the correct arguments by another part of the system:
25
26 >>> real = SomeClass()
27 >>> real.method = MagicMock(name='method')
28 >>> real.method(3, 4, 5, key='value')
29 <MagicMock name='method()' id='...'>
30
Georg Brandl7ad3df62014-10-31 07:59:37 +010031Once our mock has been used (``real.method`` in this example) it has methods
Michael Foorda9e6fb22012-03-28 14:36:02 +010032and attributes that allow you to make assertions about how it has been used.
33
34.. note::
35
36 In most of these examples the :class:`Mock` and :class:`MagicMock` classes
Georg Brandl7ad3df62014-10-31 07:59:37 +010037 are interchangeable. As the ``MagicMock`` is the more capable class it makes
Michael Foorda9e6fb22012-03-28 14:36:02 +010038 a sensible one to use by default.
39
40Once the mock has been called its :attr:`~Mock.called` attribute is set to
Georg Brandl7ad3df62014-10-31 07:59:37 +010041``True``. More importantly we can use the :meth:`~Mock.assert_called_with` or
Georg Brandl24891672012-04-01 13:48:26 +020042:meth:`~Mock.assert_called_once_with` method to check that it was called with
Michael Foorda9e6fb22012-03-28 14:36:02 +010043the correct arguments.
44
Georg Brandl7ad3df62014-10-31 07:59:37 +010045This example tests that calling ``ProductionClass().method`` results in a call to
46the ``something`` method:
Michael Foorda9e6fb22012-03-28 14:36:02 +010047
Ezio Melottic9cfcf12013-03-11 09:42:40 +020048 >>> class ProductionClass:
Michael Foorda9e6fb22012-03-28 14:36:02 +010049 ... def method(self):
50 ... self.something(1, 2, 3)
51 ... def something(self, a, b, c):
52 ... pass
53 ...
54 >>> real = ProductionClass()
55 >>> real.something = MagicMock()
56 >>> real.method()
57 >>> real.something.assert_called_once_with(1, 2, 3)
58
59
60
61Mock for Method Calls on an Object
62~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
63
64In the last example we patched a method directly on an object to check that it
65was called correctly. Another common use case is to pass an object into a
66method (or some part of the system under test) and then check that it is used
67in the correct way.
68
Georg Brandl7ad3df62014-10-31 07:59:37 +010069The simple ``ProductionClass`` below has a ``closer`` method. If it is called with
70an object then it calls ``close`` on it.
Michael Foorda9e6fb22012-03-28 14:36:02 +010071
Ezio Melottic9cfcf12013-03-11 09:42:40 +020072 >>> class ProductionClass:
Michael Foorda9e6fb22012-03-28 14:36:02 +010073 ... def closer(self, something):
74 ... something.close()
75 ...
76
Georg Brandl7ad3df62014-10-31 07:59:37 +010077So to test it we need to pass in an object with a ``close`` method and check
Michael Foorda9e6fb22012-03-28 14:36:02 +010078that it was called correctly.
79
80 >>> real = ProductionClass()
81 >>> mock = Mock()
82 >>> real.closer(mock)
83 >>> mock.close.assert_called_with()
84
85We don't have to do any work to provide the 'close' method on our mock.
86Accessing close creates it. So, if 'close' hasn't already been called then
87accessing it in the test will create it, but :meth:`~Mock.assert_called_with`
88will raise a failure exception.
89
90
91Mocking Classes
92~~~~~~~~~~~~~~~
93
94A common use case is to mock out classes instantiated by your code under test.
95When you patch a class, then that class is replaced with a mock. Instances
96are created by *calling the class*. This means you access the "mock instance"
97by looking at the return value of the mocked class.
98
Georg Brandl7ad3df62014-10-31 07:59:37 +010099In the example below we have a function ``some_function`` that instantiates ``Foo``
100and calls a method on it. The call to :func:`patch` replaces the class ``Foo`` with a
101mock. The ``Foo`` instance is the result of calling the mock, so it is configured
Michael Foord0682a0c2012-04-13 20:51:20 +0100102by modifying the mock :attr:`~Mock.return_value`.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100103
104 >>> def some_function():
105 ... instance = module.Foo()
106 ... return instance.method()
107 ...
108 >>> with patch('module.Foo') as mock:
109 ... instance = mock.return_value
110 ... instance.method.return_value = 'the result'
111 ... result = some_function()
112 ... assert result == 'the result'
113
114
115Naming your mocks
116~~~~~~~~~~~~~~~~~
117
118It can be useful to give your mocks a name. The name is shown in the repr of
119the mock and can be helpful when the mock appears in test failure messages. The
120name is also propagated to attributes or methods of the mock:
121
122 >>> mock = MagicMock(name='foo')
123 >>> mock
124 <MagicMock name='foo' id='...'>
125 >>> mock.method
126 <MagicMock name='foo.method' id='...'>
127
128
129Tracking all Calls
130~~~~~~~~~~~~~~~~~~
131
132Often you want to track more than a single call to a method. The
133:attr:`~Mock.mock_calls` attribute records all calls
134to child attributes of the mock - and also to their children.
135
136 >>> mock = MagicMock()
137 >>> mock.method()
138 <MagicMock name='mock.method()' id='...'>
139 >>> mock.attribute.method(10, x=53)
140 <MagicMock name='mock.attribute.method()' id='...'>
141 >>> mock.mock_calls
142 [call.method(), call.attribute.method(10, x=53)]
143
Georg Brandl7ad3df62014-10-31 07:59:37 +0100144If you make an assertion about ``mock_calls`` and any unexpected methods
Michael Foorda9e6fb22012-03-28 14:36:02 +0100145have been called, then the assertion will fail. This is useful because as well
146as asserting that the calls you expected have been made, you are also checking
147that they were made in the right order and with no additional calls:
148
149You use the :data:`call` object to construct lists for comparing with
Georg Brandl7ad3df62014-10-31 07:59:37 +0100150``mock_calls``:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100151
152 >>> expected = [call.method(), call.attribute.method(10, x=53)]
153 >>> mock.mock_calls == expected
154 True
155
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800156However, parameters to calls that return mocks are not recorded, which means it is not
157possible to track nested calls where the parameters used to create ancestors are important:
158
159 >>> m = Mock()
160 >>> m.factory(important=True).deliver()
161 <Mock name='mock.factory().deliver()' id='...'>
162 >>> m.mock_calls[-1] == call.factory(important=False).deliver()
163 True
164
Michael Foorda9e6fb22012-03-28 14:36:02 +0100165
166Setting Return Values and Attributes
167~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
168
169Setting the return values on a mock object is trivially easy:
170
171 >>> mock = Mock()
172 >>> mock.return_value = 3
173 >>> mock()
174 3
175
176Of course you can do the same for methods on the mock:
177
178 >>> mock = Mock()
179 >>> mock.method.return_value = 3
180 >>> mock.method()
181 3
182
183The return value can also be set in the constructor:
184
185 >>> mock = Mock(return_value=3)
186 >>> mock()
187 3
188
189If you need an attribute setting on your mock, just do it:
190
191 >>> mock = Mock()
192 >>> mock.x = 3
193 >>> mock.x
194 3
195
196Sometimes you want to mock up a more complex situation, like for example
Georg Brandl7ad3df62014-10-31 07:59:37 +0100197``mock.connection.cursor().execute("SELECT 1")``. If we wanted this call to
Michael Foorda9e6fb22012-03-28 14:36:02 +0100198return a list, then we have to configure the result of the nested call.
199
200We can use :data:`call` to construct the set of calls in a "chained call" like
201this for easy assertion afterwards:
202
203 >>> mock = Mock()
204 >>> cursor = mock.connection.cursor.return_value
205 >>> cursor.execute.return_value = ['foo']
206 >>> mock.connection.cursor().execute("SELECT 1")
207 ['foo']
208 >>> expected = call.connection.cursor().execute("SELECT 1").call_list()
209 >>> mock.mock_calls
210 [call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]
211 >>> mock.mock_calls == expected
212 True
213
Georg Brandl7ad3df62014-10-31 07:59:37 +0100214It is the call to ``.call_list()`` that turns our call object into a list of
Michael Foorda9e6fb22012-03-28 14:36:02 +0100215calls representing the chained calls.
216
217
218Raising exceptions with mocks
219~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
220
221A useful attribute is :attr:`~Mock.side_effect`. If you set this to an
222exception class or instance then the exception will be raised when the mock
223is called.
224
225 >>> mock = Mock(side_effect=Exception('Boom!'))
226 >>> mock()
227 Traceback (most recent call last):
228 ...
229 Exception: Boom!
230
231
232Side effect functions and iterables
233~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
234
Georg Brandl7ad3df62014-10-31 07:59:37 +0100235``side_effect`` can also be set to a function or an iterable. The use case for
236``side_effect`` as an iterable is where your mock is going to be called several
Michael Foorda9e6fb22012-03-28 14:36:02 +0100237times, and you want each call to return a different value. When you set
Georg Brandl7ad3df62014-10-31 07:59:37 +0100238``side_effect`` to an iterable every call to the mock returns the next value
Michael Foorda9e6fb22012-03-28 14:36:02 +0100239from the iterable:
240
241 >>> mock = MagicMock(side_effect=[4, 5, 6])
242 >>> mock()
243 4
244 >>> mock()
245 5
246 >>> mock()
247 6
248
249
250For more advanced use cases, like dynamically varying the return values
Georg Brandl7ad3df62014-10-31 07:59:37 +0100251depending on what the mock is called with, ``side_effect`` can be a function.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100252The function will be called with the same arguments as the mock. Whatever the
253function returns is what the call returns:
254
255 >>> vals = {(1, 2): 1, (2, 3): 2}
256 >>> def side_effect(*args):
257 ... return vals[args]
258 ...
259 >>> mock = MagicMock(side_effect=side_effect)
260 >>> mock(1, 2)
261 1
262 >>> mock(2, 3)
263 2
264
265
266Creating a Mock from an Existing Object
267~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
268
269One problem with over use of mocking is that it couples your tests to the
270implementation of your mocks rather than your real code. Suppose you have a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100271class that implements ``some_method``. In a test for another class, you
272provide a mock of this object that *also* provides ``some_method``. If later
273you refactor the first class, so that it no longer has ``some_method`` - then
Michael Foorda9e6fb22012-03-28 14:36:02 +0100274your tests will continue to pass even though your code is now broken!
275
Georg Brandl7ad3df62014-10-31 07:59:37 +0100276:class:`Mock` allows you to provide an object as a specification for the mock,
277using the *spec* keyword argument. Accessing methods / attributes on the
Michael Foorda9e6fb22012-03-28 14:36:02 +0100278mock that don't exist on your specification object will immediately raise an
279attribute error. If you change the implementation of your specification, then
280tests that use that class will start failing immediately without you having to
281instantiate the class in those tests.
282
283 >>> mock = Mock(spec=SomeClass)
284 >>> mock.old_method()
285 Traceback (most recent call last):
286 ...
287 AttributeError: object has no attribute 'old_method'
288
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100289Using a specification also enables a smarter matching of calls made to the
290mock, regardless of whether some parameters were passed as positional or
291named arguments::
292
293 >>> def f(a, b, c): pass
294 ...
295 >>> mock = Mock(spec=f)
296 >>> mock(1, 2, 3)
297 <Mock name='mock()' id='140161580456576'>
298 >>> mock.assert_called_with(a=1, b=2, c=3)
299
300If you want this smarter matching to also work with method calls on the mock,
301you can use :ref:`auto-speccing <auto-speccing>`.
302
Michael Foorda9e6fb22012-03-28 14:36:02 +0100303If you want a stronger form of specification that prevents the setting
304of arbitrary attributes as well as the getting of them then you can use
Georg Brandl7ad3df62014-10-31 07:59:37 +0100305*spec_set* instead of *spec*.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100306
307
308
309Patch Decorators
310----------------
311
312.. note::
313
Georg Brandl7ad3df62014-10-31 07:59:37 +0100314 With :func:`patch` it matters that you patch objects in the namespace where
315 they are looked up. This is normally straightforward, but for a quick guide
Michael Foorda9e6fb22012-03-28 14:36:02 +0100316 read :ref:`where to patch <where-to-patch>`.
317
318
319A common need in tests is to patch a class attribute or a module attribute,
320for example patching a builtin or patching a class in a module to test that it
321is instantiated. Modules and classes are effectively global, so patching on
322them has to be undone after the test or the patch will persist into other
323tests and cause hard to diagnose problems.
324
Georg Brandl7ad3df62014-10-31 07:59:37 +0100325mock provides three convenient decorators for this: :func:`patch`, :func:`patch.object` and
326:func:`patch.dict`. ``patch`` takes a single string, of the form
327``package.module.Class.attribute`` to specify the attribute you are patching. It
Michael Foorda9e6fb22012-03-28 14:36:02 +0100328also optionally takes a value that you want the attribute (or class or
329whatever) to be replaced with. 'patch.object' takes an object and the name of
330the attribute you would like patched, plus optionally the value to patch it
331with.
332
Georg Brandl7ad3df62014-10-31 07:59:37 +0100333``patch.object``:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100334
335 >>> original = SomeClass.attribute
336 >>> @patch.object(SomeClass, 'attribute', sentinel.attribute)
337 ... def test():
338 ... assert SomeClass.attribute == sentinel.attribute
339 ...
340 >>> test()
341 >>> assert SomeClass.attribute == original
342
343 >>> @patch('package.module.attribute', sentinel.attribute)
344 ... def test():
345 ... from package.module import attribute
346 ... assert attribute is sentinel.attribute
347 ...
348 >>> test()
349
Georg Brandl7ad3df62014-10-31 07:59:37 +0100350If you are patching a module (including :mod:`builtins`) then use :func:`patch`
351instead of :func:`patch.object`:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100352
Ezio Melottib40a2202013-03-30 05:55:52 +0200353 >>> mock = MagicMock(return_value=sentinel.file_handle)
354 >>> with patch('builtins.open', mock):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100355 ... handle = open('filename', 'r')
356 ...
357 >>> mock.assert_called_with('filename', 'r')
358 >>> assert handle == sentinel.file_handle, "incorrect file handle returned"
359
Georg Brandl7ad3df62014-10-31 07:59:37 +0100360The module name can be 'dotted', in the form ``package.module`` if needed:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100361
362 >>> @patch('package.module.ClassName.attribute', sentinel.attribute)
363 ... def test():
364 ... from package.module import ClassName
365 ... assert ClassName.attribute == sentinel.attribute
366 ...
367 >>> test()
368
369A nice pattern is to actually decorate test methods themselves:
370
Berker Peksagb31daff2016-04-02 04:32:06 +0300371 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100372 ... @patch.object(SomeClass, 'attribute', sentinel.attribute)
373 ... def test_something(self):
374 ... self.assertEqual(SomeClass.attribute, sentinel.attribute)
375 ...
376 >>> original = SomeClass.attribute
377 >>> MyTest('test_something').test_something()
378 >>> assert SomeClass.attribute == original
379
Georg Brandl7ad3df62014-10-31 07:59:37 +0100380If you want to patch with a Mock, you can use :func:`patch` with only one argument
381(or :func:`patch.object` with two arguments). The mock will be created for you and
Michael Foorda9e6fb22012-03-28 14:36:02 +0100382passed into the test function / method:
383
Berker Peksagb31daff2016-04-02 04:32:06 +0300384 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100385 ... @patch.object(SomeClass, 'static_method')
386 ... def test_something(self, mock_method):
387 ... SomeClass.static_method()
388 ... mock_method.assert_called_with()
389 ...
390 >>> MyTest('test_something').test_something()
391
392You can stack up multiple patch decorators using this pattern:
393
Berker Peksagb31daff2016-04-02 04:32:06 +0300394 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100395 ... @patch('package.module.ClassName1')
396 ... @patch('package.module.ClassName2')
397 ... def test_something(self, MockClass2, MockClass1):
Ezio Melottie2123702013-01-10 03:43:33 +0200398 ... self.assertIs(package.module.ClassName1, MockClass1)
399 ... self.assertIs(package.module.ClassName2, MockClass2)
Michael Foorda9e6fb22012-03-28 14:36:02 +0100400 ...
401 >>> MyTest('test_something').test_something()
402
403When you nest patch decorators the mocks are passed in to the decorated
Miss Islington (bot)b2ecb8b2018-09-14 12:15:10 -0700404function in the same order they applied (the normal *Python* order that
Michael Foorda9e6fb22012-03-28 14:36:02 +0100405decorators are applied). This means from the bottom up, so in the example
Georg Brandl7ad3df62014-10-31 07:59:37 +0100406above the mock for ``test_module.ClassName2`` is passed in first.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100407
408There is also :func:`patch.dict` for setting values in a dictionary just
409during a scope and restoring the dictionary to its original state when the test
410ends:
411
412 >>> foo = {'key': 'value'}
413 >>> original = foo.copy()
414 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
415 ... assert foo == {'newkey': 'newvalue'}
416 ...
417 >>> assert foo == original
418
Georg Brandl7ad3df62014-10-31 07:59:37 +0100419``patch``, ``patch.object`` and ``patch.dict`` can all be used as context managers.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100420
Georg Brandl7ad3df62014-10-31 07:59:37 +0100421Where you use :func:`patch` to create a mock for you, you can get a reference to the
Michael Foorda9e6fb22012-03-28 14:36:02 +0100422mock using the "as" form of the with statement:
423
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200424 >>> class ProductionClass:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100425 ... def method(self):
426 ... pass
427 ...
428 >>> with patch.object(ProductionClass, 'method') as mock_method:
429 ... mock_method.return_value = None
430 ... real = ProductionClass()
431 ... real.method(1, 2, 3)
432 ...
433 >>> mock_method.assert_called_with(1, 2, 3)
434
435
Georg Brandl7ad3df62014-10-31 07:59:37 +0100436As an alternative ``patch``, ``patch.object`` and ``patch.dict`` can be used as
Michael Foorda9e6fb22012-03-28 14:36:02 +0100437class decorators. When used in this way it is the same as applying the
Larry Hastings3732ed22014-03-15 21:13:56 -0700438decorator individually to every method whose name starts with "test".
Michael Foorda9e6fb22012-03-28 14:36:02 +0100439
440
441.. _further-examples:
442
443Further Examples
Georg Brandl7fc972a2013-02-03 14:00:04 +0100444----------------
Michael Foorda9e6fb22012-03-28 14:36:02 +0100445
446
447Here are some more examples for some slightly more advanced scenarios.
Michael Foord944e02d2012-03-25 23:12:55 +0100448
449
450Mocking chained calls
Georg Brandl7fc972a2013-02-03 14:00:04 +0100451~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100452
453Mocking chained calls is actually straightforward with mock once you
454understand the :attr:`~Mock.return_value` attribute. When a mock is called for
Georg Brandl7ad3df62014-10-31 07:59:37 +0100455the first time, or you fetch its ``return_value`` before it has been called, a
456new :class:`Mock` is created.
Michael Foord944e02d2012-03-25 23:12:55 +0100457
458This means that you can see how the object returned from a call to a mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +0100459object has been used by interrogating the ``return_value`` mock:
Michael Foord944e02d2012-03-25 23:12:55 +0100460
461 >>> mock = Mock()
462 >>> mock().foo(a=2, b=3)
463 <Mock name='mock().foo()' id='...'>
464 >>> mock.return_value.foo.assert_called_with(a=2, b=3)
465
466From here it is a simple step to configure and then make assertions about
467chained calls. Of course another alternative is writing your code in a more
468testable way in the first place...
469
470So, suppose we have some code that looks a little bit like this:
471
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200472 >>> class Something:
Michael Foord944e02d2012-03-25 23:12:55 +0100473 ... def __init__(self):
474 ... self.backend = BackendProvider()
475 ... def method(self):
476 ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
477 ... # more code
478
Georg Brandl7ad3df62014-10-31 07:59:37 +0100479Assuming that ``BackendProvider`` is already well tested, how do we test
480``method()``? Specifically, we want to test that the code section ``# more
481code`` uses the response object in the correct way.
Michael Foord944e02d2012-03-25 23:12:55 +0100482
483As this chain of calls is made from an instance attribute we can monkey patch
Georg Brandl7ad3df62014-10-31 07:59:37 +0100484the ``backend`` attribute on a ``Something`` instance. In this particular case
Michael Foord944e02d2012-03-25 23:12:55 +0100485we are only interested in the return value from the final call to
Georg Brandl7ad3df62014-10-31 07:59:37 +0100486``start_call`` so we don't have much configuration to do. Let's assume the
Michael Foord944e02d2012-03-25 23:12:55 +0100487object it returns is 'file-like', so we'll ensure that our response object
Georg Brandl7ad3df62014-10-31 07:59:37 +0100488uses the builtin :func:`open` as its ``spec``.
Michael Foord944e02d2012-03-25 23:12:55 +0100489
490To do this we create a mock instance as our mock backend and create a mock
491response object for it. To set the response as the return value for that final
Georg Brandl7ad3df62014-10-31 07:59:37 +0100492``start_call`` we could do this::
Michael Foord944e02d2012-03-25 23:12:55 +0100493
Georg Brandl7ad3df62014-10-31 07:59:37 +0100494 mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response
Michael Foord944e02d2012-03-25 23:12:55 +0100495
496We can do that in a slightly nicer way using the :meth:`~Mock.configure_mock`
497method to directly set the return value for us:
498
499 >>> something = Something()
Terry Jan Reedy30ffe7e2014-01-21 00:01:51 -0500500 >>> mock_response = Mock(spec=open)
Michael Foord944e02d2012-03-25 23:12:55 +0100501 >>> mock_backend = Mock()
502 >>> config = {'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response}
503 >>> mock_backend.configure_mock(**config)
504
505With these we monkey patch the "mock backend" in place and can make the real
506call:
507
508 >>> something.backend = mock_backend
509 >>> something.method()
510
511Using :attr:`~Mock.mock_calls` we can check the chained call with a single
512assert. A chained call is several calls in one line of code, so there will be
Georg Brandl7ad3df62014-10-31 07:59:37 +0100513several entries in ``mock_calls``. We can use :meth:`call.call_list` to create
Michael Foord944e02d2012-03-25 23:12:55 +0100514this list of calls for us:
515
516 >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
517 >>> call_list = chained.call_list()
518 >>> assert mock_backend.mock_calls == call_list
519
520
521Partial mocking
Georg Brandl7fc972a2013-02-03 14:00:04 +0100522~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100523
Georg Brandl7ad3df62014-10-31 07:59:37 +0100524In some tests I wanted to mock out a call to :meth:`datetime.date.today`
Georg Brandl728e4de2014-10-29 09:00:30 +0100525to return a known date, but I didn't want to prevent the code under test from
Georg Brandl7ad3df62014-10-31 07:59:37 +0100526creating new date objects. Unfortunately :class:`datetime.date` is written in C, and
527so I couldn't just monkey-patch out the static :meth:`date.today` method.
Michael Foord944e02d2012-03-25 23:12:55 +0100528
529I found a simple way of doing this that involved effectively wrapping the date
530class with a mock, but passing through calls to the constructor to the real
531class (and returning real instances).
532
533The :func:`patch decorator <patch>` is used here to
Georg Brandl7ad3df62014-10-31 07:59:37 +0100534mock out the ``date`` class in the module under test. The :attr:`side_effect`
Michael Foord944e02d2012-03-25 23:12:55 +0100535attribute on the mock date class is then set to a lambda function that returns
536a real date. When the mock date class is called a real date will be
Georg Brandl7ad3df62014-10-31 07:59:37 +0100537constructed and returned by ``side_effect``.
Michael Foord944e02d2012-03-25 23:12:55 +0100538
539 >>> from datetime import date
540 >>> with patch('mymodule.date') as mock_date:
541 ... mock_date.today.return_value = date(2010, 10, 8)
542 ... mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
543 ...
544 ... assert mymodule.date.today() == date(2010, 10, 8)
545 ... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
546 ...
547
Georg Brandl7ad3df62014-10-31 07:59:37 +0100548Note that we don't patch :class:`datetime.date` globally, we patch ``date`` in the
Michael Foord944e02d2012-03-25 23:12:55 +0100549module that *uses* it. See :ref:`where to patch <where-to-patch>`.
550
Georg Brandl7ad3df62014-10-31 07:59:37 +0100551When ``date.today()`` is called a known date is returned, but calls to the
552``date(...)`` constructor still return normal dates. Without this you can find
Michael Foord944e02d2012-03-25 23:12:55 +0100553yourself having to calculate an expected result using exactly the same
554algorithm as the code under test, which is a classic testing anti-pattern.
555
Georg Brandl7ad3df62014-10-31 07:59:37 +0100556Calls to the date constructor are recorded in the ``mock_date`` attributes
557(``call_count`` and friends) which may also be useful for your tests.
Michael Foord944e02d2012-03-25 23:12:55 +0100558
559An alternative way of dealing with mocking dates, or other builtin classes,
560is discussed in `this blog entry
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300561<https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/>`_.
Michael Foord944e02d2012-03-25 23:12:55 +0100562
563
564Mocking a Generator Method
Georg Brandl7fc972a2013-02-03 14:00:04 +0100565~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100566
Georg Brandl728e4de2014-10-29 09:00:30 +0100567A Python generator is a function or method that uses the :keyword:`yield` statement
568to return a series of values when iterated over [#]_.
Michael Foord944e02d2012-03-25 23:12:55 +0100569
570A generator method / function is called to return the generator object. It is
571the generator object that is then iterated over. The protocol method for
Georg Brandl728e4de2014-10-29 09:00:30 +0100572iteration is :meth:`~container.__iter__`, so we can
Georg Brandl7ad3df62014-10-31 07:59:37 +0100573mock this using a :class:`MagicMock`.
Michael Foord944e02d2012-03-25 23:12:55 +0100574
575Here's an example class with an "iter" method implemented as a generator:
576
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200577 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100578 ... def iter(self):
579 ... for i in [1, 2, 3]:
580 ... yield i
581 ...
582 >>> foo = Foo()
583 >>> list(foo.iter())
584 [1, 2, 3]
585
586
587How would we mock this class, and in particular its "iter" method?
588
589To configure the values returned from the iteration (implicit in the call to
Georg Brandl7ad3df62014-10-31 07:59:37 +0100590:class:`list`), we need to configure the object returned by the call to ``foo.iter()``.
Michael Foord944e02d2012-03-25 23:12:55 +0100591
592 >>> mock_foo = MagicMock()
593 >>> mock_foo.iter.return_value = iter([1, 2, 3])
594 >>> list(mock_foo.iter())
595 [1, 2, 3]
596
597.. [#] There are also generator expressions and more `advanced uses
598 <http://www.dabeaz.com/coroutines/index.html>`_ of generators, but we aren't
599 concerned about them here. A very good introduction to generators and how
600 powerful they are is: `Generator Tricks for Systems Programmers
601 <http://www.dabeaz.com/generators/>`_.
602
603
604Applying the same patch to every test method
Georg Brandl7fc972a2013-02-03 14:00:04 +0100605~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100606
607If you want several patches in place for multiple test methods the obvious way
608is to apply the patch decorators to every method. This can feel like unnecessary
Georg Brandl7ad3df62014-10-31 07:59:37 +0100609repetition. For Python 2.6 or more recent you can use :func:`patch` (in all its
Michael Foord944e02d2012-03-25 23:12:55 +0100610various forms) as a class decorator. This applies the patches to all test
611methods on the class. A test method is identified by methods whose names start
Georg Brandl7ad3df62014-10-31 07:59:37 +0100612with ``test``:
Michael Foord944e02d2012-03-25 23:12:55 +0100613
614 >>> @patch('mymodule.SomeClass')
615 ... class MyTest(TestCase):
616 ...
617 ... def test_one(self, MockSomeClass):
Ezio Melottie2123702013-01-10 03:43:33 +0200618 ... self.assertIs(mymodule.SomeClass, MockSomeClass)
Michael Foord944e02d2012-03-25 23:12:55 +0100619 ...
620 ... def test_two(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 not_a_test(self):
624 ... return 'something'
625 ...
626 >>> MyTest('test_one').test_one()
627 >>> MyTest('test_two').test_two()
628 >>> MyTest('test_two').not_a_test()
629 'something'
630
631An alternative way of managing patches is to use the :ref:`start-and-stop`.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100632These allow you to move the patching into your ``setUp`` and ``tearDown`` methods.
Michael Foord944e02d2012-03-25 23:12:55 +0100633
634 >>> class MyTest(TestCase):
635 ... def setUp(self):
636 ... self.patcher = patch('mymodule.foo')
637 ... self.mock_foo = self.patcher.start()
638 ...
639 ... def test_foo(self):
Ezio Melottie2123702013-01-10 03:43:33 +0200640 ... self.assertIs(mymodule.foo, self.mock_foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100641 ...
642 ... def tearDown(self):
643 ... self.patcher.stop()
644 ...
645 >>> MyTest('test_foo').run()
646
647If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +0100648calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foord944e02d2012-03-25 23:12:55 +0100649exception is raised in the setUp then tearDown is not called.
650:meth:`unittest.TestCase.addCleanup` makes this easier:
651
652 >>> class MyTest(TestCase):
653 ... def setUp(self):
654 ... patcher = patch('mymodule.foo')
655 ... self.addCleanup(patcher.stop)
656 ... self.mock_foo = patcher.start()
657 ...
658 ... def test_foo(self):
Ezio Melottie2123702013-01-10 03:43:33 +0200659 ... self.assertIs(mymodule.foo, self.mock_foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100660 ...
661 >>> MyTest('test_foo').run()
662
663
664Mocking Unbound Methods
Georg Brandl7fc972a2013-02-03 14:00:04 +0100665~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100666
667Whilst writing tests today I needed to patch an *unbound method* (patching the
668method on the class rather than on the instance). I needed self to be passed
669in as the first argument because I want to make asserts about which objects
670were calling this particular method. The issue is that you can't patch with a
671mock for this, because if you replace an unbound method with a mock it doesn't
672become a bound method when fetched from the instance, and so it doesn't get
673self passed in. The workaround is to patch the unbound method with a real
674function instead. The :func:`patch` decorator makes it so simple to
675patch out methods with a mock that having to create a real function becomes a
676nuisance.
677
Georg Brandl7ad3df62014-10-31 07:59:37 +0100678If you pass ``autospec=True`` to patch then it does the patching with a
Michael Foord944e02d2012-03-25 23:12:55 +0100679*real* function object. This function object has the same signature as the one
680it is replacing, but delegates to a mock under the hood. You still get your
681mock auto-created in exactly the same way as before. What it means though, is
682that if you use it to patch out an unbound method on a class the mocked
683function will be turned into a bound method if it is fetched from an instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100684It will have ``self`` passed in as the first argument, which is exactly what I
Michael Foord944e02d2012-03-25 23:12:55 +0100685wanted:
686
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200687 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100688 ... def foo(self):
689 ... pass
690 ...
691 >>> with patch.object(Foo, 'foo', autospec=True) as mock_foo:
692 ... mock_foo.return_value = 'foo'
693 ... foo = Foo()
694 ... foo.foo()
695 ...
696 'foo'
697 >>> mock_foo.assert_called_once_with(foo)
698
Georg Brandl7ad3df62014-10-31 07:59:37 +0100699If we don't use ``autospec=True`` then the unbound method is patched out
700with a Mock instance instead, and isn't called with ``self``.
Michael Foord944e02d2012-03-25 23:12:55 +0100701
702
703Checking multiple calls with mock
Georg Brandl7fc972a2013-02-03 14:00:04 +0100704~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100705
706mock has a nice API for making assertions about how your mock objects are used.
707
708 >>> mock = Mock()
709 >>> mock.foo_bar.return_value = None
710 >>> mock.foo_bar('baz', spam='eggs')
711 >>> mock.foo_bar.assert_called_with('baz', spam='eggs')
712
713If your mock is only being called once you can use the
714:meth:`assert_called_once_with` method that also asserts that the
715:attr:`call_count` is one.
716
717 >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
718 >>> mock.foo_bar()
719 >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
720 Traceback (most recent call last):
721 ...
722 AssertionError: Expected to be called once. Called 2 times.
723
Georg Brandl7ad3df62014-10-31 07:59:37 +0100724Both ``assert_called_with`` and ``assert_called_once_with`` make assertions about
Michael Foord944e02d2012-03-25 23:12:55 +0100725the *most recent* call. If your mock is going to be called several times, and
726you want to make assertions about *all* those calls you can use
727:attr:`~Mock.call_args_list`:
728
729 >>> mock = Mock(return_value=None)
730 >>> mock(1, 2, 3)
731 >>> mock(4, 5, 6)
732 >>> mock()
733 >>> mock.call_args_list
734 [call(1, 2, 3), call(4, 5, 6), call()]
735
736The :data:`call` helper makes it easy to make assertions about these calls. You
Georg Brandl7ad3df62014-10-31 07:59:37 +0100737can build up a list of expected calls and compare it to ``call_args_list``. This
738looks remarkably similar to the repr of the ``call_args_list``:
Michael Foord944e02d2012-03-25 23:12:55 +0100739
740 >>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
741 >>> mock.call_args_list == expected
742 True
743
744
745Coping with mutable arguments
Georg Brandl7fc972a2013-02-03 14:00:04 +0100746~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100747
748Another situation is rare, but can bite you, is when your mock is called with
Georg Brandl7ad3df62014-10-31 07:59:37 +0100749mutable arguments. ``call_args`` and ``call_args_list`` store *references* to the
Michael Foord944e02d2012-03-25 23:12:55 +0100750arguments. If the arguments are mutated by the code under test then you can no
751longer make assertions about what the values were when the mock was called.
752
753Here's some example code that shows the problem. Imagine the following functions
754defined in 'mymodule'::
755
756 def frob(val):
757 pass
758
759 def grob(val):
760 "First frob and then clear val"
761 frob(val)
762 val.clear()
763
Georg Brandl7ad3df62014-10-31 07:59:37 +0100764When we try to test that ``grob`` calls ``frob`` with the correct argument look
Michael Foord944e02d2012-03-25 23:12:55 +0100765what happens:
766
767 >>> with patch('mymodule.frob') as mock_frob:
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200768 ... val = {6}
Michael Foord944e02d2012-03-25 23:12:55 +0100769 ... mymodule.grob(val)
770 ...
771 >>> val
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200772 set()
773 >>> mock_frob.assert_called_with({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100774 Traceback (most recent call last):
775 ...
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200776 AssertionError: Expected: (({6},), {})
777 Called with: ((set(),), {})
Michael Foord944e02d2012-03-25 23:12:55 +0100778
779One possibility would be for mock to copy the arguments you pass in. This
780could then cause problems if you do assertions that rely on object identity
781for equality.
782
783Here's one solution that uses the :attr:`side_effect`
Georg Brandl7ad3df62014-10-31 07:59:37 +0100784functionality. If you provide a ``side_effect`` function for a mock then
785``side_effect`` will be called with the same args as the mock. This gives us an
Michael Foord944e02d2012-03-25 23:12:55 +0100786opportunity to copy the arguments and store them for later assertions. In this
787example I'm using *another* mock to store the arguments so that I can use the
788mock methods for doing the assertion. Again a helper function sets this up for
789me.
790
791 >>> from copy import deepcopy
792 >>> from unittest.mock import Mock, patch, DEFAULT
793 >>> def copy_call_args(mock):
794 ... new_mock = Mock()
795 ... def side_effect(*args, **kwargs):
796 ... args = deepcopy(args)
797 ... kwargs = deepcopy(kwargs)
798 ... new_mock(*args, **kwargs)
799 ... return DEFAULT
800 ... mock.side_effect = side_effect
801 ... return new_mock
802 ...
803 >>> with patch('mymodule.frob') as mock_frob:
804 ... new_mock = copy_call_args(mock_frob)
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200805 ... val = {6}
Michael Foord944e02d2012-03-25 23:12:55 +0100806 ... mymodule.grob(val)
807 ...
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200808 >>> new_mock.assert_called_with({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100809 >>> new_mock.call_args
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200810 call({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100811
Georg Brandl7ad3df62014-10-31 07:59:37 +0100812``copy_call_args`` is called with the mock that will be called. It returns a new
813mock that we do the assertion on. The ``side_effect`` function makes a copy of
814the args and calls our ``new_mock`` with the copy.
Michael Foord944e02d2012-03-25 23:12:55 +0100815
816.. note::
817
818 If your mock is only going to be used once there is an easier way of
819 checking arguments at the point they are called. You can simply do the
Georg Brandl7ad3df62014-10-31 07:59:37 +0100820 checking inside a ``side_effect`` function.
Michael Foord944e02d2012-03-25 23:12:55 +0100821
822 >>> def side_effect(arg):
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200823 ... assert arg == {6}
Michael Foord944e02d2012-03-25 23:12:55 +0100824 ...
825 >>> mock = Mock(side_effect=side_effect)
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200826 >>> mock({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100827 >>> mock(set())
828 Traceback (most recent call last):
829 ...
830 AssertionError
831
Georg Brandl7ad3df62014-10-31 07:59:37 +0100832An alternative approach is to create a subclass of :class:`Mock` or
833:class:`MagicMock` that copies (using :func:`copy.deepcopy`) the arguments.
Michael Foord944e02d2012-03-25 23:12:55 +0100834Here's an example implementation:
835
836 >>> from copy import deepcopy
837 >>> class CopyingMock(MagicMock):
838 ... def __call__(self, *args, **kwargs):
839 ... args = deepcopy(args)
840 ... kwargs = deepcopy(kwargs)
841 ... return super(CopyingMock, self).__call__(*args, **kwargs)
842 ...
843 >>> c = CopyingMock(return_value=None)
844 >>> arg = set()
845 >>> c(arg)
846 >>> arg.add(1)
847 >>> c.assert_called_with(set())
848 >>> c.assert_called_with(arg)
849 Traceback (most recent call last):
850 ...
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200851 AssertionError: Expected call: mock({1})
852 Actual call: mock(set())
Michael Foord944e02d2012-03-25 23:12:55 +0100853 >>> c.foo
854 <CopyingMock name='mock.foo' id='...'>
855
Georg Brandl7ad3df62014-10-31 07:59:37 +0100856When you subclass ``Mock`` or ``MagicMock`` all dynamically created attributes,
857and the ``return_value`` will use your subclass automatically. That means all
858children of a ``CopyingMock`` will also have the type ``CopyingMock``.
Michael Foord944e02d2012-03-25 23:12:55 +0100859
860
Michael Foord944e02d2012-03-25 23:12:55 +0100861Nesting Patches
Georg Brandl7fc972a2013-02-03 14:00:04 +0100862~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100863
864Using patch as a context manager is nice, but if you do multiple patches you
865can end up with nested with statements indenting further and further to the
866right:
867
868 >>> class MyTest(TestCase):
869 ...
870 ... def test_foo(self):
871 ... with patch('mymodule.Foo') as mock_foo:
872 ... with patch('mymodule.Bar') as mock_bar:
873 ... with patch('mymodule.Spam') as mock_spam:
874 ... assert mymodule.Foo is mock_foo
875 ... assert mymodule.Bar is mock_bar
876 ... assert mymodule.Spam is mock_spam
877 ...
878 >>> original = mymodule.Foo
879 >>> MyTest('test_foo').test_foo()
880 >>> assert mymodule.Foo is original
881
Georg Brandl7ad3df62014-10-31 07:59:37 +0100882With unittest ``cleanup`` functions and the :ref:`start-and-stop` we can
Michael Foord944e02d2012-03-25 23:12:55 +0100883achieve the same effect without the nested indentation. A simple helper
Georg Brandl7ad3df62014-10-31 07:59:37 +0100884method, ``create_patch``, puts the patch in place and returns the created mock
Michael Foord944e02d2012-03-25 23:12:55 +0100885for us:
886
887 >>> class MyTest(TestCase):
888 ...
889 ... def create_patch(self, name):
890 ... patcher = patch(name)
891 ... thing = patcher.start()
892 ... self.addCleanup(patcher.stop)
893 ... return thing
894 ...
895 ... def test_foo(self):
896 ... mock_foo = self.create_patch('mymodule.Foo')
897 ... mock_bar = self.create_patch('mymodule.Bar')
898 ... mock_spam = self.create_patch('mymodule.Spam')
899 ...
900 ... assert mymodule.Foo is mock_foo
901 ... assert mymodule.Bar is mock_bar
902 ... assert mymodule.Spam is mock_spam
903 ...
904 >>> original = mymodule.Foo
905 >>> MyTest('test_foo').run()
906 >>> assert mymodule.Foo is original
907
908
909Mocking a dictionary with MagicMock
Georg Brandl7fc972a2013-02-03 14:00:04 +0100910~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100911
912You may want to mock a dictionary, or other container object, recording all
913access to it whilst having it still behave like a dictionary.
914
915We can do this with :class:`MagicMock`, which will behave like a dictionary,
916and using :data:`~Mock.side_effect` to delegate dictionary access to a real
917underlying dictionary that is under our control.
918
Georg Brandl7ad3df62014-10-31 07:59:37 +0100919When the :meth:`__getitem__` and :meth:`__setitem__` methods of our ``MagicMock`` are called
920(normal dictionary access) then ``side_effect`` is called with the key (and in
921the case of ``__setitem__`` the value too). We can also control what is returned.
Michael Foord944e02d2012-03-25 23:12:55 +0100922
Georg Brandl7ad3df62014-10-31 07:59:37 +0100923After the ``MagicMock`` has been used we can use attributes like
Michael Foord944e02d2012-03-25 23:12:55 +0100924:data:`~Mock.call_args_list` to assert about how the dictionary was used:
925
926 >>> my_dict = {'a': 1, 'b': 2, 'c': 3}
927 >>> def getitem(name):
928 ... return my_dict[name]
929 ...
930 >>> def setitem(name, val):
931 ... my_dict[name] = val
932 ...
933 >>> mock = MagicMock()
934 >>> mock.__getitem__.side_effect = getitem
935 >>> mock.__setitem__.side_effect = setitem
936
937.. note::
938
Georg Brandl7ad3df62014-10-31 07:59:37 +0100939 An alternative to using ``MagicMock`` is to use ``Mock`` and *only* provide
Michael Foord944e02d2012-03-25 23:12:55 +0100940 the magic methods you specifically want:
941
942 >>> mock = Mock()
Éric Araujo0b1be1a2014-03-17 16:48:13 -0400943 >>> mock.__getitem__ = Mock(side_effect=getitem)
944 >>> mock.__setitem__ = Mock(side_effect=setitem)
Michael Foord944e02d2012-03-25 23:12:55 +0100945
Georg Brandl7ad3df62014-10-31 07:59:37 +0100946 A *third* option is to use ``MagicMock`` but passing in ``dict`` as the *spec*
947 (or *spec_set*) argument so that the ``MagicMock`` created only has
Michael Foord944e02d2012-03-25 23:12:55 +0100948 dictionary magic methods available:
949
950 >>> mock = MagicMock(spec_set=dict)
951 >>> mock.__getitem__.side_effect = getitem
952 >>> mock.__setitem__.side_effect = setitem
953
Georg Brandl7ad3df62014-10-31 07:59:37 +0100954With these side effect functions in place, the ``mock`` will behave like a normal
955dictionary but recording the access. It even raises a :exc:`KeyError` if you try
Michael Foord944e02d2012-03-25 23:12:55 +0100956to access a key that doesn't exist.
957
958 >>> mock['a']
959 1
960 >>> mock['c']
961 3
962 >>> mock['d']
963 Traceback (most recent call last):
964 ...
965 KeyError: 'd'
966 >>> mock['b'] = 'fish'
967 >>> mock['d'] = 'eggs'
968 >>> mock['b']
969 'fish'
970 >>> mock['d']
971 'eggs'
972
973After it has been used you can make assertions about the access using the normal
974mock methods and attributes:
975
976 >>> mock.__getitem__.call_args_list
977 [call('a'), call('c'), call('d'), call('b'), call('d')]
978 >>> mock.__setitem__.call_args_list
979 [call('b', 'fish'), call('d', 'eggs')]
980 >>> my_dict
981 {'a': 1, 'c': 3, 'b': 'fish', 'd': 'eggs'}
982
983
984Mock subclasses and their attributes
Georg Brandl7fc972a2013-02-03 14:00:04 +0100985~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100986
Georg Brandl7ad3df62014-10-31 07:59:37 +0100987There are various reasons why you might want to subclass :class:`Mock`. One
988reason might be to add helper methods. Here's a silly example:
Michael Foord944e02d2012-03-25 23:12:55 +0100989
990 >>> class MyMock(MagicMock):
991 ... def has_been_called(self):
992 ... return self.called
993 ...
994 >>> mymock = MyMock(return_value=None)
995 >>> mymock
996 <MyMock id='...'>
997 >>> mymock.has_been_called()
998 False
999 >>> mymock()
1000 >>> mymock.has_been_called()
1001 True
1002
Georg Brandl7ad3df62014-10-31 07:59:37 +01001003The standard behaviour for ``Mock`` instances is that attributes and the return
Michael Foord944e02d2012-03-25 23:12:55 +01001004value mocks are of the same type as the mock they are accessed on. This ensures
Georg Brandl7ad3df62014-10-31 07:59:37 +01001005that ``Mock`` attributes are ``Mocks`` and ``MagicMock`` attributes are ``MagicMocks``
Michael Foord944e02d2012-03-25 23:12:55 +01001006[#]_. So if you're subclassing to add helper methods then they'll also be
1007available on the attributes and return value mock of instances of your
1008subclass.
1009
1010 >>> mymock.foo
1011 <MyMock name='mock.foo' id='...'>
1012 >>> mymock.foo.has_been_called()
1013 False
1014 >>> mymock.foo()
1015 <MyMock name='mock.foo()' id='...'>
1016 >>> mymock.foo.has_been_called()
1017 True
1018
1019Sometimes this is inconvenient. For example, `one user
Sanyam Khurana338cd832018-01-20 05:55:37 +05301020<https://code.google.com/archive/p/mock/issues/105>`_ is subclassing mock to
Michael Foord944e02d2012-03-25 23:12:55 +01001021created a `Twisted adaptor
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001022<https://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html>`_.
Michael Foord944e02d2012-03-25 23:12:55 +01001023Having this applied to attributes too actually causes errors.
1024
Georg Brandl7ad3df62014-10-31 07:59:37 +01001025``Mock`` (in all its flavours) uses a method called ``_get_child_mock`` to create
Michael Foord944e02d2012-03-25 23:12:55 +01001026these "sub-mocks" for attributes and return values. You can prevent your
1027subclass being used for attributes by overriding this method. The signature is
Georg Brandl7ad3df62014-10-31 07:59:37 +01001028that it takes arbitrary keyword arguments (``**kwargs``) which are then passed
Michael Foord944e02d2012-03-25 23:12:55 +01001029onto the mock constructor:
1030
1031 >>> class Subclass(MagicMock):
1032 ... def _get_child_mock(self, **kwargs):
1033 ... return MagicMock(**kwargs)
1034 ...
1035 >>> mymock = Subclass()
1036 >>> mymock.foo
1037 <MagicMock name='mock.foo' id='...'>
1038 >>> assert isinstance(mymock, Subclass)
1039 >>> assert not isinstance(mymock.foo, Subclass)
1040 >>> assert not isinstance(mymock(), Subclass)
1041
1042.. [#] An exception to this rule are the non-callable mocks. Attributes use the
1043 callable variant because otherwise non-callable mocks couldn't have callable
1044 methods.
1045
1046
1047Mocking imports with patch.dict
Georg Brandl7fc972a2013-02-03 14:00:04 +01001048~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001049
1050One situation where mocking can be hard is where you have a local import inside
1051a function. These are harder to mock because they aren't using an object from
1052the module namespace that we can patch out.
1053
1054Generally local imports are to be avoided. They are sometimes done to prevent
1055circular dependencies, for which there is *usually* a much better way to solve
1056the problem (refactor the code) or to prevent "up front costs" by delaying the
1057import. This can also be solved in better ways than an unconditional local
1058import (store the module as a class or module attribute and only do the import
1059on first use).
1060
Georg Brandl7ad3df62014-10-31 07:59:37 +01001061That aside there is a way to use ``mock`` to affect the results of an import.
1062Importing fetches an *object* from the :data:`sys.modules` dictionary. Note that it
Michael Foord944e02d2012-03-25 23:12:55 +01001063fetches an *object*, which need not be a module. Importing a module for the
1064first time results in a module object being put in `sys.modules`, so usually
1065when you import something you get a module back. This need not be the case
1066however.
1067
1068This means you can use :func:`patch.dict` to *temporarily* put a mock in place
Georg Brandl7ad3df62014-10-31 07:59:37 +01001069in :data:`sys.modules`. Any imports whilst this patch is active will fetch the mock.
Michael Foord944e02d2012-03-25 23:12:55 +01001070When the patch is complete (the decorated function exits, the with statement
Georg Brandl7ad3df62014-10-31 07:59:37 +01001071body is complete or ``patcher.stop()`` is called) then whatever was there
Michael Foord944e02d2012-03-25 23:12:55 +01001072previously will be restored safely.
1073
1074Here's an example that mocks out the 'fooble' module.
1075
1076 >>> mock = Mock()
1077 >>> with patch.dict('sys.modules', {'fooble': mock}):
1078 ... import fooble
1079 ... fooble.blob()
1080 ...
1081 <Mock name='mock.blob()' id='...'>
1082 >>> assert 'fooble' not in sys.modules
1083 >>> mock.blob.assert_called_once_with()
1084
Georg Brandl7ad3df62014-10-31 07:59:37 +01001085As you can see the ``import fooble`` succeeds, but on exit there is no 'fooble'
1086left in :data:`sys.modules`.
Michael Foord944e02d2012-03-25 23:12:55 +01001087
Georg Brandl7ad3df62014-10-31 07:59:37 +01001088This also works for the ``from module import name`` form:
Michael Foord944e02d2012-03-25 23:12:55 +01001089
1090 >>> mock = Mock()
1091 >>> with patch.dict('sys.modules', {'fooble': mock}):
1092 ... from fooble import blob
1093 ... blob.blip()
1094 ...
1095 <Mock name='mock.blob.blip()' id='...'>
1096 >>> mock.blob.blip.assert_called_once_with()
1097
1098With slightly more work you can also mock package imports:
1099
1100 >>> mock = Mock()
1101 >>> modules = {'package': mock, 'package.module': mock.module}
1102 >>> with patch.dict('sys.modules', modules):
1103 ... from package.module import fooble
1104 ... fooble()
1105 ...
1106 <Mock name='mock.module.fooble()' id='...'>
1107 >>> mock.module.fooble.assert_called_once_with()
1108
1109
1110Tracking order of calls and less verbose call assertions
Georg Brandl7fc972a2013-02-03 14:00:04 +01001111~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001112
1113The :class:`Mock` class allows you to track the *order* of method calls on
1114your mock objects through the :attr:`~Mock.method_calls` attribute. This
1115doesn't allow you to track the order of calls between separate mock objects,
1116however we can use :attr:`~Mock.mock_calls` to achieve the same effect.
1117
Georg Brandl7ad3df62014-10-31 07:59:37 +01001118Because mocks track calls to child mocks in ``mock_calls``, and accessing an
Michael Foord944e02d2012-03-25 23:12:55 +01001119arbitrary attribute of a mock creates a child mock, we can create our separate
1120mocks from a parent one. Calls to those child mock will then all be recorded,
Georg Brandl7ad3df62014-10-31 07:59:37 +01001121in order, in the ``mock_calls`` of the parent:
Michael Foord944e02d2012-03-25 23:12:55 +01001122
1123 >>> manager = Mock()
1124 >>> mock_foo = manager.foo
1125 >>> mock_bar = manager.bar
1126
1127 >>> mock_foo.something()
1128 <Mock name='mock.foo.something()' id='...'>
1129 >>> mock_bar.other.thing()
1130 <Mock name='mock.bar.other.thing()' id='...'>
1131
1132 >>> manager.mock_calls
1133 [call.foo.something(), call.bar.other.thing()]
1134
1135We can then assert about the calls, including the order, by comparing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01001136the ``mock_calls`` attribute on the manager mock:
Michael Foord944e02d2012-03-25 23:12:55 +01001137
1138 >>> expected_calls = [call.foo.something(), call.bar.other.thing()]
1139 >>> manager.mock_calls == expected_calls
1140 True
1141
Georg Brandl7ad3df62014-10-31 07:59:37 +01001142If ``patch`` is creating, and putting in place, your mocks then you can attach
Michael Foord944e02d2012-03-25 23:12:55 +01001143them to a manager mock using the :meth:`~Mock.attach_mock` method. After
Georg Brandl7ad3df62014-10-31 07:59:37 +01001144attaching calls will be recorded in ``mock_calls`` of the manager.
Michael Foord944e02d2012-03-25 23:12:55 +01001145
1146 >>> manager = MagicMock()
1147 >>> with patch('mymodule.Class1') as MockClass1:
1148 ... with patch('mymodule.Class2') as MockClass2:
1149 ... manager.attach_mock(MockClass1, 'MockClass1')
1150 ... manager.attach_mock(MockClass2, 'MockClass2')
1151 ... MockClass1().foo()
1152 ... MockClass2().bar()
1153 ...
1154 <MagicMock name='mock.MockClass1().foo()' id='...'>
1155 <MagicMock name='mock.MockClass2().bar()' id='...'>
1156 >>> manager.mock_calls
1157 [call.MockClass1(),
1158 call.MockClass1().foo(),
1159 call.MockClass2(),
1160 call.MockClass2().bar()]
1161
1162If many calls have been made, but you're only interested in a particular
1163sequence of them then an alternative is to use the
1164:meth:`~Mock.assert_has_calls` method. This takes a list of calls (constructed
1165with the :data:`call` object). If that sequence of calls are in
1166:attr:`~Mock.mock_calls` then the assert succeeds.
1167
1168 >>> m = MagicMock()
1169 >>> m().foo().bar().baz()
1170 <MagicMock name='mock().foo().bar().baz()' id='...'>
1171 >>> m.one().two().three()
1172 <MagicMock name='mock.one().two().three()' id='...'>
1173 >>> calls = call.one().two().three().call_list()
1174 >>> m.assert_has_calls(calls)
1175
Georg Brandl7ad3df62014-10-31 07:59:37 +01001176Even though the chained call ``m.one().two().three()`` aren't the only calls that
Michael Foord944e02d2012-03-25 23:12:55 +01001177have been made to the mock, the assert still succeeds.
1178
1179Sometimes a mock may have several calls made to it, and you are only interested
1180in asserting about *some* of those calls. You may not even care about the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001181order. In this case you can pass ``any_order=True`` to ``assert_has_calls``:
Michael Foord944e02d2012-03-25 23:12:55 +01001182
1183 >>> m = MagicMock()
1184 >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
1185 (...)
1186 >>> calls = [call.fifty('50'), call(1), call.seven(7)]
1187 >>> m.assert_has_calls(calls, any_order=True)
1188
1189
1190More complex argument matching
Georg Brandl7fc972a2013-02-03 14:00:04 +01001191~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001192
1193Using the same basic concept as :data:`ANY` we can implement matchers to do more
1194complex assertions on objects used as arguments to mocks.
1195
1196Suppose we expect some object to be passed to a mock that by default
1197compares equal based on object identity (which is the Python default for user
1198defined classes). To use :meth:`~Mock.assert_called_with` we would need to pass
1199in the exact same object. If we are only interested in some of the attributes
1200of this object then we can create a matcher that will check these attributes
1201for us.
1202
Georg Brandl7ad3df62014-10-31 07:59:37 +01001203You can see in this example how a 'standard' call to ``assert_called_with`` isn't
Michael Foord944e02d2012-03-25 23:12:55 +01001204sufficient:
1205
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001206 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +01001207 ... def __init__(self, a, b):
1208 ... self.a, self.b = a, b
1209 ...
1210 >>> mock = Mock(return_value=None)
1211 >>> mock(Foo(1, 2))
1212 >>> mock.assert_called_with(Foo(1, 2))
1213 Traceback (most recent call last):
1214 ...
1215 AssertionError: Expected: call(<__main__.Foo object at 0x...>)
1216 Actual call: call(<__main__.Foo object at 0x...>)
1217
Georg Brandl7ad3df62014-10-31 07:59:37 +01001218A comparison function for our ``Foo`` class might look something like this:
Michael Foord944e02d2012-03-25 23:12:55 +01001219
1220 >>> def compare(self, other):
1221 ... if not type(self) == type(other):
1222 ... return False
1223 ... if self.a != other.a:
1224 ... return False
1225 ... if self.b != other.b:
1226 ... return False
1227 ... return True
1228 ...
1229
1230And a matcher object that can use comparison functions like this for its
1231equality operation would look something like this:
1232
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001233 >>> class Matcher:
Michael Foord944e02d2012-03-25 23:12:55 +01001234 ... def __init__(self, compare, some_obj):
1235 ... self.compare = compare
1236 ... self.some_obj = some_obj
1237 ... def __eq__(self, other):
1238 ... return self.compare(self.some_obj, other)
1239 ...
1240
1241Putting all this together:
1242
1243 >>> match_foo = Matcher(compare, Foo(1, 2))
1244 >>> mock.assert_called_with(match_foo)
1245
Georg Brandl7ad3df62014-10-31 07:59:37 +01001246The ``Matcher`` is instantiated with our compare function and the ``Foo`` object
1247we want to compare against. In ``assert_called_with`` the ``Matcher`` equality
Michael Foord944e02d2012-03-25 23:12:55 +01001248method will be called, which compares the object the mock was called with
1249against the one we created our matcher with. If they match then
Georg Brandl7ad3df62014-10-31 07:59:37 +01001250``assert_called_with`` passes, and if they don't an :exc:`AssertionError` is raised:
Michael Foord944e02d2012-03-25 23:12:55 +01001251
1252 >>> match_wrong = Matcher(compare, Foo(3, 4))
1253 >>> mock.assert_called_with(match_wrong)
1254 Traceback (most recent call last):
1255 ...
1256 AssertionError: Expected: ((<Matcher object at 0x...>,), {})
1257 Called with: ((<Foo object at 0x...>,), {})
1258
1259With a bit of tweaking you could have the comparison function raise the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001260:exc:`AssertionError` directly and provide a more useful failure message.
Michael Foord944e02d2012-03-25 23:12:55 +01001261
1262As of version 1.5, the Python testing library `PyHamcrest
Sanyam Khurana338cd832018-01-20 05:55:37 +05301263<https://pyhamcrest.readthedocs.io/>`_ provides similar functionality,
Michael Foord944e02d2012-03-25 23:12:55 +01001264that may be useful here, in the form of its equality matcher
1265(`hamcrest.library.integration.match_equality
Sanyam Khurana338cd832018-01-20 05:55:37 +05301266<https://pyhamcrest.readthedocs.io/en/release-1.8/integration/#module-hamcrest.library.integration.match_equality>`_).