blob: cf6b671b5beeb444caa266faae060c54eb1920fa [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
Xtreakc8dfa732019-09-10 11:37:17 +010015 import asyncio
Stéphane Wirtel859c0682018-10-12 09:51:05 +020016 import unittest
17 from unittest.mock import Mock, MagicMock, patch, call, sentinel
18
19 class SomeClass:
20 attribute = 'this is a doctest'
21
22 @staticmethod
23 def static_method():
24 pass
25
Michael Foorda9e6fb22012-03-28 14:36:02 +010026Using Mock
27----------
28
29Mock Patching Methods
30~~~~~~~~~~~~~~~~~~~~~
31
32Common uses for :class:`Mock` objects include:
33
34* Patching methods
35* Recording method calls on objects
36
37You might want to replace a method on an object to check that
38it is called with the correct arguments by another part of the system:
39
40 >>> real = SomeClass()
41 >>> real.method = MagicMock(name='method')
42 >>> real.method(3, 4, 5, key='value')
43 <MagicMock name='method()' id='...'>
44
Georg Brandl7ad3df62014-10-31 07:59:37 +010045Once our mock has been used (``real.method`` in this example) it has methods
Michael Foorda9e6fb22012-03-28 14:36:02 +010046and attributes that allow you to make assertions about how it has been used.
47
48.. note::
49
50 In most of these examples the :class:`Mock` and :class:`MagicMock` classes
Georg Brandl7ad3df62014-10-31 07:59:37 +010051 are interchangeable. As the ``MagicMock`` is the more capable class it makes
Michael Foorda9e6fb22012-03-28 14:36:02 +010052 a sensible one to use by default.
53
54Once the mock has been called its :attr:`~Mock.called` attribute is set to
Georg Brandl7ad3df62014-10-31 07:59:37 +010055``True``. More importantly we can use the :meth:`~Mock.assert_called_with` or
Georg Brandl24891672012-04-01 13:48:26 +020056:meth:`~Mock.assert_called_once_with` method to check that it was called with
Michael Foorda9e6fb22012-03-28 14:36:02 +010057the correct arguments.
58
Georg Brandl7ad3df62014-10-31 07:59:37 +010059This example tests that calling ``ProductionClass().method`` results in a call to
60the ``something`` method:
Michael Foorda9e6fb22012-03-28 14:36:02 +010061
Ezio Melottic9cfcf12013-03-11 09:42:40 +020062 >>> class ProductionClass:
Michael Foorda9e6fb22012-03-28 14:36:02 +010063 ... def method(self):
64 ... self.something(1, 2, 3)
65 ... def something(self, a, b, c):
66 ... pass
67 ...
68 >>> real = ProductionClass()
69 >>> real.something = MagicMock()
70 >>> real.method()
71 >>> real.something.assert_called_once_with(1, 2, 3)
72
73
74
75Mock for Method Calls on an Object
76~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
77
78In the last example we patched a method directly on an object to check that it
79was called correctly. Another common use case is to pass an object into a
80method (or some part of the system under test) and then check that it is used
81in the correct way.
82
Georg Brandl7ad3df62014-10-31 07:59:37 +010083The simple ``ProductionClass`` below has a ``closer`` method. If it is called with
84an object then it calls ``close`` on it.
Michael Foorda9e6fb22012-03-28 14:36:02 +010085
Ezio Melottic9cfcf12013-03-11 09:42:40 +020086 >>> class ProductionClass:
Michael Foorda9e6fb22012-03-28 14:36:02 +010087 ... def closer(self, something):
88 ... something.close()
89 ...
90
Georg Brandl7ad3df62014-10-31 07:59:37 +010091So to test it we need to pass in an object with a ``close`` method and check
Michael Foorda9e6fb22012-03-28 14:36:02 +010092that it was called correctly.
93
94 >>> real = ProductionClass()
95 >>> mock = Mock()
96 >>> real.closer(mock)
97 >>> mock.close.assert_called_with()
98
99We don't have to do any work to provide the 'close' method on our mock.
100Accessing close creates it. So, if 'close' hasn't already been called then
101accessing it in the test will create it, but :meth:`~Mock.assert_called_with`
102will raise a failure exception.
103
104
105Mocking Classes
106~~~~~~~~~~~~~~~
107
108A common use case is to mock out classes instantiated by your code under test.
109When you patch a class, then that class is replaced with a mock. Instances
110are created by *calling the class*. This means you access the "mock instance"
111by looking at the return value of the mocked class.
112
Georg Brandl7ad3df62014-10-31 07:59:37 +0100113In the example below we have a function ``some_function`` that instantiates ``Foo``
114and calls a method on it. The call to :func:`patch` replaces the class ``Foo`` with a
115mock. The ``Foo`` instance is the result of calling the mock, so it is configured
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200116by modifying the mock :attr:`~Mock.return_value`. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +0100117
118 >>> def some_function():
119 ... instance = module.Foo()
120 ... return instance.method()
121 ...
122 >>> with patch('module.Foo') as mock:
123 ... instance = mock.return_value
124 ... instance.method.return_value = 'the result'
125 ... result = some_function()
126 ... assert result == 'the result'
127
128
129Naming your mocks
130~~~~~~~~~~~~~~~~~
131
132It can be useful to give your mocks a name. The name is shown in the repr of
133the mock and can be helpful when the mock appears in test failure messages. The
134name is also propagated to attributes or methods of the mock:
135
136 >>> mock = MagicMock(name='foo')
137 >>> mock
138 <MagicMock name='foo' id='...'>
139 >>> mock.method
140 <MagicMock name='foo.method' id='...'>
141
142
143Tracking all Calls
144~~~~~~~~~~~~~~~~~~
145
146Often you want to track more than a single call to a method. The
147:attr:`~Mock.mock_calls` attribute records all calls
148to child attributes of the mock - and also to their children.
149
150 >>> mock = MagicMock()
151 >>> mock.method()
152 <MagicMock name='mock.method()' id='...'>
153 >>> mock.attribute.method(10, x=53)
154 <MagicMock name='mock.attribute.method()' id='...'>
155 >>> mock.mock_calls
156 [call.method(), call.attribute.method(10, x=53)]
157
Georg Brandl7ad3df62014-10-31 07:59:37 +0100158If you make an assertion about ``mock_calls`` and any unexpected methods
Michael Foorda9e6fb22012-03-28 14:36:02 +0100159have been called, then the assertion will fail. This is useful because as well
160as asserting that the calls you expected have been made, you are also checking
161that they were made in the right order and with no additional calls:
162
163You use the :data:`call` object to construct lists for comparing with
Georg Brandl7ad3df62014-10-31 07:59:37 +0100164``mock_calls``:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100165
166 >>> expected = [call.method(), call.attribute.method(10, x=53)]
167 >>> mock.mock_calls == expected
168 True
169
Chris Withers8ca0fa92018-12-03 21:31:37 +0000170However, parameters to calls that return mocks are not recorded, which means it is not
171possible to track nested calls where the parameters used to create ancestors are important:
172
173 >>> m = Mock()
174 >>> m.factory(important=True).deliver()
175 <Mock name='mock.factory().deliver()' id='...'>
176 >>> m.mock_calls[-1] == call.factory(important=False).deliver()
177 True
178
Michael Foorda9e6fb22012-03-28 14:36:02 +0100179
180Setting Return Values and Attributes
181~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
182
183Setting the return values on a mock object is trivially easy:
184
185 >>> mock = Mock()
186 >>> mock.return_value = 3
187 >>> mock()
188 3
189
190Of course you can do the same for methods on the mock:
191
192 >>> mock = Mock()
193 >>> mock.method.return_value = 3
194 >>> mock.method()
195 3
196
197The return value can also be set in the constructor:
198
199 >>> mock = Mock(return_value=3)
200 >>> mock()
201 3
202
203If you need an attribute setting on your mock, just do it:
204
205 >>> mock = Mock()
206 >>> mock.x = 3
207 >>> mock.x
208 3
209
210Sometimes you want to mock up a more complex situation, like for example
Georg Brandl7ad3df62014-10-31 07:59:37 +0100211``mock.connection.cursor().execute("SELECT 1")``. If we wanted this call to
Michael Foorda9e6fb22012-03-28 14:36:02 +0100212return a list, then we have to configure the result of the nested call.
213
214We can use :data:`call` to construct the set of calls in a "chained call" like
215this for easy assertion afterwards:
216
217 >>> mock = Mock()
218 >>> cursor = mock.connection.cursor.return_value
219 >>> cursor.execute.return_value = ['foo']
220 >>> mock.connection.cursor().execute("SELECT 1")
221 ['foo']
222 >>> expected = call.connection.cursor().execute("SELECT 1").call_list()
223 >>> mock.mock_calls
224 [call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]
225 >>> mock.mock_calls == expected
226 True
227
Georg Brandl7ad3df62014-10-31 07:59:37 +0100228It is the call to ``.call_list()`` that turns our call object into a list of
Michael Foorda9e6fb22012-03-28 14:36:02 +0100229calls representing the chained calls.
230
231
232Raising exceptions with mocks
233~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
234
235A useful attribute is :attr:`~Mock.side_effect`. If you set this to an
236exception class or instance then the exception will be raised when the mock
237is called.
238
239 >>> mock = Mock(side_effect=Exception('Boom!'))
240 >>> mock()
241 Traceback (most recent call last):
242 ...
243 Exception: Boom!
244
245
246Side effect functions and iterables
247~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
248
Georg Brandl7ad3df62014-10-31 07:59:37 +0100249``side_effect`` can also be set to a function or an iterable. The use case for
250``side_effect`` as an iterable is where your mock is going to be called several
Michael Foorda9e6fb22012-03-28 14:36:02 +0100251times, and you want each call to return a different value. When you set
Georg Brandl7ad3df62014-10-31 07:59:37 +0100252``side_effect`` to an iterable every call to the mock returns the next value
Michael Foorda9e6fb22012-03-28 14:36:02 +0100253from the iterable:
254
255 >>> mock = MagicMock(side_effect=[4, 5, 6])
256 >>> mock()
257 4
258 >>> mock()
259 5
260 >>> mock()
261 6
262
263
264For more advanced use cases, like dynamically varying the return values
Georg Brandl7ad3df62014-10-31 07:59:37 +0100265depending on what the mock is called with, ``side_effect`` can be a function.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100266The function will be called with the same arguments as the mock. Whatever the
267function returns is what the call returns:
268
269 >>> vals = {(1, 2): 1, (2, 3): 2}
270 >>> def side_effect(*args):
271 ... return vals[args]
272 ...
273 >>> mock = MagicMock(side_effect=side_effect)
274 >>> mock(1, 2)
275 1
276 >>> mock(2, 3)
277 2
278
279
Xtreakc8dfa732019-09-10 11:37:17 +0100280Mocking asynchronous iterators
281~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
282
283Since Python 3.8, ``MagicMock`` has support to mock :ref:`async-iterators`
284through ``__aiter__``. The :attr:`~Mock.return_value` attribute of ``__aiter__``
285can be used to set the return values to be used for iteration.
286
287 >>> mock = MagicMock()
288 >>> mock.__aiter__.return_value = [1, 2, 3]
289 >>> async def main():
290 ... return [i async for i in mock]
291 >>> asyncio.run(main())
292 [1, 2, 3]
293
294
295Mocking asynchronous context manager
296~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
297
298Since Python 3.8, ``MagicMock`` has support to mock
299:ref:`async-context-managers` through ``__aenter__`` and ``__aexit__``. The
300return value of ``__aenter__`` is an :class:`AsyncMock`.
301
302 >>> class AsyncContextManager:
303 ...
304 ... async def __aenter__(self):
305 ... return self
306 ...
307 ... async def __aexit__(self):
308 ... pass
309 >>> mock_instance = MagicMock(AsyncContextManager())
310 >>> async def main():
311 ... async with mock_instance as result:
312 ... pass
313 >>> asyncio.run(main())
314 >>> mock_instance.__aenter__.assert_called_once()
315 >>> mock_instance.__aexit__.assert_called_once()
316
317
Michael Foorda9e6fb22012-03-28 14:36:02 +0100318Creating a Mock from an Existing Object
319~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
320
321One problem with over use of mocking is that it couples your tests to the
322implementation of your mocks rather than your real code. Suppose you have a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100323class that implements ``some_method``. In a test for another class, you
324provide a mock of this object that *also* provides ``some_method``. If later
325you refactor the first class, so that it no longer has ``some_method`` - then
Michael Foorda9e6fb22012-03-28 14:36:02 +0100326your tests will continue to pass even though your code is now broken!
327
Georg Brandl7ad3df62014-10-31 07:59:37 +0100328:class:`Mock` allows you to provide an object as a specification for the mock,
329using the *spec* keyword argument. Accessing methods / attributes on the
Michael Foorda9e6fb22012-03-28 14:36:02 +0100330mock that don't exist on your specification object will immediately raise an
331attribute error. If you change the implementation of your specification, then
332tests that use that class will start failing immediately without you having to
333instantiate the class in those tests.
334
335 >>> mock = Mock(spec=SomeClass)
336 >>> mock.old_method()
337 Traceback (most recent call last):
338 ...
339 AttributeError: object has no attribute 'old_method'
340
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100341Using a specification also enables a smarter matching of calls made to the
342mock, regardless of whether some parameters were passed as positional or
343named arguments::
344
345 >>> def f(a, b, c): pass
346 ...
347 >>> mock = Mock(spec=f)
348 >>> mock(1, 2, 3)
349 <Mock name='mock()' id='140161580456576'>
350 >>> mock.assert_called_with(a=1, b=2, c=3)
351
352If you want this smarter matching to also work with method calls on the mock,
353you can use :ref:`auto-speccing <auto-speccing>`.
354
Michael Foorda9e6fb22012-03-28 14:36:02 +0100355If you want a stronger form of specification that prevents the setting
356of arbitrary attributes as well as the getting of them then you can use
Georg Brandl7ad3df62014-10-31 07:59:37 +0100357*spec_set* instead of *spec*.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100358
359
360
361Patch Decorators
362----------------
363
364.. note::
365
Georg Brandl7ad3df62014-10-31 07:59:37 +0100366 With :func:`patch` it matters that you patch objects in the namespace where
367 they are looked up. This is normally straightforward, but for a quick guide
Michael Foorda9e6fb22012-03-28 14:36:02 +0100368 read :ref:`where to patch <where-to-patch>`.
369
370
371A common need in tests is to patch a class attribute or a module attribute,
372for example patching a builtin or patching a class in a module to test that it
373is instantiated. Modules and classes are effectively global, so patching on
374them has to be undone after the test or the patch will persist into other
375tests and cause hard to diagnose problems.
376
Georg Brandl7ad3df62014-10-31 07:59:37 +0100377mock provides three convenient decorators for this: :func:`patch`, :func:`patch.object` and
378:func:`patch.dict`. ``patch`` takes a single string, of the form
379``package.module.Class.attribute`` to specify the attribute you are patching. It
Michael Foorda9e6fb22012-03-28 14:36:02 +0100380also optionally takes a value that you want the attribute (or class or
381whatever) to be replaced with. 'patch.object' takes an object and the name of
382the attribute you would like patched, plus optionally the value to patch it
383with.
384
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200385``patch.object``::
Michael Foorda9e6fb22012-03-28 14:36:02 +0100386
387 >>> original = SomeClass.attribute
388 >>> @patch.object(SomeClass, 'attribute', sentinel.attribute)
389 ... def test():
390 ... assert SomeClass.attribute == sentinel.attribute
391 ...
392 >>> test()
393 >>> assert SomeClass.attribute == original
394
395 >>> @patch('package.module.attribute', sentinel.attribute)
396 ... def test():
397 ... from package.module import attribute
398 ... assert attribute is sentinel.attribute
399 ...
400 >>> test()
401
Georg Brandl7ad3df62014-10-31 07:59:37 +0100402If you are patching a module (including :mod:`builtins`) then use :func:`patch`
403instead of :func:`patch.object`:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100404
Ezio Melottib40a2202013-03-30 05:55:52 +0200405 >>> mock = MagicMock(return_value=sentinel.file_handle)
406 >>> with patch('builtins.open', mock):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100407 ... handle = open('filename', 'r')
408 ...
409 >>> mock.assert_called_with('filename', 'r')
410 >>> assert handle == sentinel.file_handle, "incorrect file handle returned"
411
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200412The module name can be 'dotted', in the form ``package.module`` if needed::
Michael Foorda9e6fb22012-03-28 14:36:02 +0100413
414 >>> @patch('package.module.ClassName.attribute', sentinel.attribute)
415 ... def test():
416 ... from package.module import ClassName
417 ... assert ClassName.attribute == sentinel.attribute
418 ...
419 >>> test()
420
421A nice pattern is to actually decorate test methods themselves:
422
Berker Peksagb31daff2016-04-02 04:32:06 +0300423 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100424 ... @patch.object(SomeClass, 'attribute', sentinel.attribute)
425 ... def test_something(self):
426 ... self.assertEqual(SomeClass.attribute, sentinel.attribute)
427 ...
428 >>> original = SomeClass.attribute
429 >>> MyTest('test_something').test_something()
430 >>> assert SomeClass.attribute == original
431
Georg Brandl7ad3df62014-10-31 07:59:37 +0100432If you want to patch with a Mock, you can use :func:`patch` with only one argument
433(or :func:`patch.object` with two arguments). The mock will be created for you and
Michael Foorda9e6fb22012-03-28 14:36:02 +0100434passed into the test function / method:
435
Berker Peksagb31daff2016-04-02 04:32:06 +0300436 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100437 ... @patch.object(SomeClass, 'static_method')
438 ... def test_something(self, mock_method):
439 ... SomeClass.static_method()
440 ... mock_method.assert_called_with()
441 ...
442 >>> MyTest('test_something').test_something()
443
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200444You can stack up multiple patch decorators using this pattern::
Michael Foorda9e6fb22012-03-28 14:36:02 +0100445
Berker Peksagb31daff2016-04-02 04:32:06 +0300446 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100447 ... @patch('package.module.ClassName1')
448 ... @patch('package.module.ClassName2')
449 ... def test_something(self, MockClass2, MockClass1):
Ezio Melottie2123702013-01-10 03:43:33 +0200450 ... self.assertIs(package.module.ClassName1, MockClass1)
451 ... self.assertIs(package.module.ClassName2, MockClass2)
Michael Foorda9e6fb22012-03-28 14:36:02 +0100452 ...
453 >>> MyTest('test_something').test_something()
454
455When you nest patch decorators the mocks are passed in to the decorated
Andrés Delfino271818f2018-09-14 14:13:09 -0300456function in the same order they applied (the normal *Python* order that
Michael Foorda9e6fb22012-03-28 14:36:02 +0100457decorators are applied). This means from the bottom up, so in the example
Georg Brandl7ad3df62014-10-31 07:59:37 +0100458above the mock for ``test_module.ClassName2`` is passed in first.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100459
460There is also :func:`patch.dict` for setting values in a dictionary just
461during a scope and restoring the dictionary to its original state when the test
462ends:
463
464 >>> foo = {'key': 'value'}
465 >>> original = foo.copy()
466 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
467 ... assert foo == {'newkey': 'newvalue'}
468 ...
469 >>> assert foo == original
470
Georg Brandl7ad3df62014-10-31 07:59:37 +0100471``patch``, ``patch.object`` and ``patch.dict`` can all be used as context managers.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100472
Georg Brandl7ad3df62014-10-31 07:59:37 +0100473Where you use :func:`patch` to create a mock for you, you can get a reference to the
Michael Foorda9e6fb22012-03-28 14:36:02 +0100474mock using the "as" form of the with statement:
475
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200476 >>> class ProductionClass:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100477 ... def method(self):
478 ... pass
479 ...
480 >>> with patch.object(ProductionClass, 'method') as mock_method:
481 ... mock_method.return_value = None
482 ... real = ProductionClass()
483 ... real.method(1, 2, 3)
484 ...
485 >>> mock_method.assert_called_with(1, 2, 3)
486
487
Georg Brandl7ad3df62014-10-31 07:59:37 +0100488As an alternative ``patch``, ``patch.object`` and ``patch.dict`` can be used as
Michael Foorda9e6fb22012-03-28 14:36:02 +0100489class decorators. When used in this way it is the same as applying the
Larry Hastings3732ed22014-03-15 21:13:56 -0700490decorator individually to every method whose name starts with "test".
Michael Foorda9e6fb22012-03-28 14:36:02 +0100491
492
493.. _further-examples:
494
495Further Examples
Georg Brandl7fc972a2013-02-03 14:00:04 +0100496----------------
Michael Foorda9e6fb22012-03-28 14:36:02 +0100497
498
499Here are some more examples for some slightly more advanced scenarios.
Michael Foord944e02d2012-03-25 23:12:55 +0100500
501
502Mocking chained calls
Georg Brandl7fc972a2013-02-03 14:00:04 +0100503~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100504
505Mocking chained calls is actually straightforward with mock once you
506understand the :attr:`~Mock.return_value` attribute. When a mock is called for
Georg Brandl7ad3df62014-10-31 07:59:37 +0100507the first time, or you fetch its ``return_value`` before it has been called, a
508new :class:`Mock` is created.
Michael Foord944e02d2012-03-25 23:12:55 +0100509
510This means that you can see how the object returned from a call to a mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +0100511object has been used by interrogating the ``return_value`` mock:
Michael Foord944e02d2012-03-25 23:12:55 +0100512
513 >>> mock = Mock()
514 >>> mock().foo(a=2, b=3)
515 <Mock name='mock().foo()' id='...'>
516 >>> mock.return_value.foo.assert_called_with(a=2, b=3)
517
518From here it is a simple step to configure and then make assertions about
519chained calls. Of course another alternative is writing your code in a more
520testable way in the first place...
521
522So, suppose we have some code that looks a little bit like this:
523
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200524 >>> class Something:
Michael Foord944e02d2012-03-25 23:12:55 +0100525 ... def __init__(self):
526 ... self.backend = BackendProvider()
527 ... def method(self):
528 ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
529 ... # more code
530
Georg Brandl7ad3df62014-10-31 07:59:37 +0100531Assuming that ``BackendProvider`` is already well tested, how do we test
532``method()``? Specifically, we want to test that the code section ``# more
533code`` uses the response object in the correct way.
Michael Foord944e02d2012-03-25 23:12:55 +0100534
535As this chain of calls is made from an instance attribute we can monkey patch
Georg Brandl7ad3df62014-10-31 07:59:37 +0100536the ``backend`` attribute on a ``Something`` instance. In this particular case
Michael Foord944e02d2012-03-25 23:12:55 +0100537we are only interested in the return value from the final call to
Georg Brandl7ad3df62014-10-31 07:59:37 +0100538``start_call`` so we don't have much configuration to do. Let's assume the
Michael Foord944e02d2012-03-25 23:12:55 +0100539object it returns is 'file-like', so we'll ensure that our response object
Georg Brandl7ad3df62014-10-31 07:59:37 +0100540uses the builtin :func:`open` as its ``spec``.
Michael Foord944e02d2012-03-25 23:12:55 +0100541
542To do this we create a mock instance as our mock backend and create a mock
543response object for it. To set the response as the return value for that final
Georg Brandl7ad3df62014-10-31 07:59:37 +0100544``start_call`` we could do this::
Michael Foord944e02d2012-03-25 23:12:55 +0100545
Georg Brandl7ad3df62014-10-31 07:59:37 +0100546 mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response
Michael Foord944e02d2012-03-25 23:12:55 +0100547
548We can do that in a slightly nicer way using the :meth:`~Mock.configure_mock`
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200549method to directly set the return value for us::
Michael Foord944e02d2012-03-25 23:12:55 +0100550
551 >>> something = Something()
Terry Jan Reedy30ffe7e2014-01-21 00:01:51 -0500552 >>> mock_response = Mock(spec=open)
Michael Foord944e02d2012-03-25 23:12:55 +0100553 >>> mock_backend = Mock()
554 >>> config = {'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response}
555 >>> mock_backend.configure_mock(**config)
556
557With these we monkey patch the "mock backend" in place and can make the real
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200558call::
Michael Foord944e02d2012-03-25 23:12:55 +0100559
560 >>> something.backend = mock_backend
561 >>> something.method()
562
563Using :attr:`~Mock.mock_calls` we can check the chained call with a single
564assert. A chained call is several calls in one line of code, so there will be
Georg Brandl7ad3df62014-10-31 07:59:37 +0100565several entries in ``mock_calls``. We can use :meth:`call.call_list` to create
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200566this list of calls for us::
Michael Foord944e02d2012-03-25 23:12:55 +0100567
568 >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
569 >>> call_list = chained.call_list()
570 >>> assert mock_backend.mock_calls == call_list
571
572
573Partial mocking
Georg Brandl7fc972a2013-02-03 14:00:04 +0100574~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100575
Georg Brandl7ad3df62014-10-31 07:59:37 +0100576In some tests I wanted to mock out a call to :meth:`datetime.date.today`
Georg Brandl728e4de2014-10-29 09:00:30 +0100577to return a known date, but I didn't want to prevent the code under test from
Georg Brandl7ad3df62014-10-31 07:59:37 +0100578creating new date objects. Unfortunately :class:`datetime.date` is written in C, and
579so I couldn't just monkey-patch out the static :meth:`date.today` method.
Michael Foord944e02d2012-03-25 23:12:55 +0100580
581I found a simple way of doing this that involved effectively wrapping the date
582class with a mock, but passing through calls to the constructor to the real
583class (and returning real instances).
584
585The :func:`patch decorator <patch>` is used here to
Georg Brandl7ad3df62014-10-31 07:59:37 +0100586mock out the ``date`` class in the module under test. The :attr:`side_effect`
Michael Foord944e02d2012-03-25 23:12:55 +0100587attribute on the mock date class is then set to a lambda function that returns
588a real date. When the mock date class is called a real date will be
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200589constructed and returned by ``side_effect``. ::
Michael Foord944e02d2012-03-25 23:12:55 +0100590
591 >>> from datetime import date
592 >>> with patch('mymodule.date') as mock_date:
593 ... mock_date.today.return_value = date(2010, 10, 8)
594 ... mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
595 ...
596 ... assert mymodule.date.today() == date(2010, 10, 8)
597 ... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
Michael Foord944e02d2012-03-25 23:12:55 +0100598
Georg Brandl7ad3df62014-10-31 07:59:37 +0100599Note that we don't patch :class:`datetime.date` globally, we patch ``date`` in the
Michael Foord944e02d2012-03-25 23:12:55 +0100600module that *uses* it. See :ref:`where to patch <where-to-patch>`.
601
Georg Brandl7ad3df62014-10-31 07:59:37 +0100602When ``date.today()`` is called a known date is returned, but calls to the
603``date(...)`` constructor still return normal dates. Without this you can find
Michael Foord944e02d2012-03-25 23:12:55 +0100604yourself having to calculate an expected result using exactly the same
605algorithm as the code under test, which is a classic testing anti-pattern.
606
Georg Brandl7ad3df62014-10-31 07:59:37 +0100607Calls to the date constructor are recorded in the ``mock_date`` attributes
608(``call_count`` and friends) which may also be useful for your tests.
Michael Foord944e02d2012-03-25 23:12:55 +0100609
610An alternative way of dealing with mocking dates, or other builtin classes,
611is discussed in `this blog entry
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300612<https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/>`_.
Michael Foord944e02d2012-03-25 23:12:55 +0100613
614
615Mocking a Generator Method
Georg Brandl7fc972a2013-02-03 14:00:04 +0100616~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100617
Georg Brandl728e4de2014-10-29 09:00:30 +0100618A Python generator is a function or method that uses the :keyword:`yield` statement
619to return a series of values when iterated over [#]_.
Michael Foord944e02d2012-03-25 23:12:55 +0100620
621A generator method / function is called to return the generator object. It is
622the generator object that is then iterated over. The protocol method for
Georg Brandl728e4de2014-10-29 09:00:30 +0100623iteration is :meth:`~container.__iter__`, so we can
Georg Brandl7ad3df62014-10-31 07:59:37 +0100624mock this using a :class:`MagicMock`.
Michael Foord944e02d2012-03-25 23:12:55 +0100625
626Here's an example class with an "iter" method implemented as a generator:
627
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200628 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100629 ... def iter(self):
630 ... for i in [1, 2, 3]:
631 ... yield i
632 ...
633 >>> foo = Foo()
634 >>> list(foo.iter())
635 [1, 2, 3]
636
637
638How would we mock this class, and in particular its "iter" method?
639
640To configure the values returned from the iteration (implicit in the call to
Georg Brandl7ad3df62014-10-31 07:59:37 +0100641:class:`list`), we need to configure the object returned by the call to ``foo.iter()``.
Michael Foord944e02d2012-03-25 23:12:55 +0100642
643 >>> mock_foo = MagicMock()
644 >>> mock_foo.iter.return_value = iter([1, 2, 3])
645 >>> list(mock_foo.iter())
646 [1, 2, 3]
647
648.. [#] There are also generator expressions and more `advanced uses
649 <http://www.dabeaz.com/coroutines/index.html>`_ of generators, but we aren't
650 concerned about them here. A very good introduction to generators and how
651 powerful they are is: `Generator Tricks for Systems Programmers
652 <http://www.dabeaz.com/generators/>`_.
653
654
655Applying the same patch to every test method
Georg Brandl7fc972a2013-02-03 14:00:04 +0100656~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100657
658If you want several patches in place for multiple test methods the obvious way
659is to apply the patch decorators to every method. This can feel like unnecessary
Georg Brandl7ad3df62014-10-31 07:59:37 +0100660repetition. For Python 2.6 or more recent you can use :func:`patch` (in all its
Michael Foord944e02d2012-03-25 23:12:55 +0100661various forms) as a class decorator. This applies the patches to all test
662methods on the class. A test method is identified by methods whose names start
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200663with ``test``::
Michael Foord944e02d2012-03-25 23:12:55 +0100664
665 >>> @patch('mymodule.SomeClass')
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200666 ... class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100667 ...
668 ... def test_one(self, MockSomeClass):
Ezio Melottie2123702013-01-10 03:43:33 +0200669 ... self.assertIs(mymodule.SomeClass, MockSomeClass)
Michael Foord944e02d2012-03-25 23:12:55 +0100670 ...
671 ... def test_two(self, MockSomeClass):
Ezio Melottie2123702013-01-10 03:43:33 +0200672 ... self.assertIs(mymodule.SomeClass, MockSomeClass)
Michael Foord944e02d2012-03-25 23:12:55 +0100673 ...
674 ... def not_a_test(self):
675 ... return 'something'
676 ...
677 >>> MyTest('test_one').test_one()
678 >>> MyTest('test_two').test_two()
679 >>> MyTest('test_two').not_a_test()
680 'something'
681
682An alternative way of managing patches is to use the :ref:`start-and-stop`.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100683These allow you to move the patching into your ``setUp`` and ``tearDown`` methods.
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200684::
Michael Foord944e02d2012-03-25 23:12:55 +0100685
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200686 >>> class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100687 ... def setUp(self):
688 ... self.patcher = patch('mymodule.foo')
689 ... self.mock_foo = self.patcher.start()
690 ...
691 ... def test_foo(self):
Ezio Melottie2123702013-01-10 03:43:33 +0200692 ... self.assertIs(mymodule.foo, self.mock_foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100693 ...
694 ... def tearDown(self):
695 ... self.patcher.stop()
696 ...
697 >>> MyTest('test_foo').run()
698
699If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +0100700calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foord944e02d2012-03-25 23:12:55 +0100701exception is raised in the setUp then tearDown is not called.
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200702:meth:`unittest.TestCase.addCleanup` makes this easier::
Michael Foord944e02d2012-03-25 23:12:55 +0100703
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200704 >>> class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100705 ... def setUp(self):
706 ... patcher = patch('mymodule.foo')
707 ... self.addCleanup(patcher.stop)
708 ... self.mock_foo = patcher.start()
709 ...
710 ... def test_foo(self):
Ezio Melottie2123702013-01-10 03:43:33 +0200711 ... self.assertIs(mymodule.foo, self.mock_foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100712 ...
713 >>> MyTest('test_foo').run()
714
715
716Mocking Unbound Methods
Georg Brandl7fc972a2013-02-03 14:00:04 +0100717~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100718
719Whilst writing tests today I needed to patch an *unbound method* (patching the
720method on the class rather than on the instance). I needed self to be passed
721in as the first argument because I want to make asserts about which objects
722were calling this particular method. The issue is that you can't patch with a
723mock for this, because if you replace an unbound method with a mock it doesn't
724become a bound method when fetched from the instance, and so it doesn't get
725self passed in. The workaround is to patch the unbound method with a real
726function instead. The :func:`patch` decorator makes it so simple to
727patch out methods with a mock that having to create a real function becomes a
728nuisance.
729
Georg Brandl7ad3df62014-10-31 07:59:37 +0100730If you pass ``autospec=True`` to patch then it does the patching with a
Michael Foord944e02d2012-03-25 23:12:55 +0100731*real* function object. This function object has the same signature as the one
732it is replacing, but delegates to a mock under the hood. You still get your
733mock auto-created in exactly the same way as before. What it means though, is
734that if you use it to patch out an unbound method on a class the mocked
735function will be turned into a bound method if it is fetched from an instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100736It will have ``self`` passed in as the first argument, which is exactly what I
Michael Foord944e02d2012-03-25 23:12:55 +0100737wanted:
738
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200739 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100740 ... def foo(self):
741 ... pass
742 ...
743 >>> with patch.object(Foo, 'foo', autospec=True) as mock_foo:
744 ... mock_foo.return_value = 'foo'
745 ... foo = Foo()
746 ... foo.foo()
747 ...
748 'foo'
749 >>> mock_foo.assert_called_once_with(foo)
750
Georg Brandl7ad3df62014-10-31 07:59:37 +0100751If we don't use ``autospec=True`` then the unbound method is patched out
752with a Mock instance instead, and isn't called with ``self``.
Michael Foord944e02d2012-03-25 23:12:55 +0100753
754
755Checking multiple calls with mock
Georg Brandl7fc972a2013-02-03 14:00:04 +0100756~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100757
758mock has a nice API for making assertions about how your mock objects are used.
759
760 >>> mock = Mock()
761 >>> mock.foo_bar.return_value = None
762 >>> mock.foo_bar('baz', spam='eggs')
763 >>> mock.foo_bar.assert_called_with('baz', spam='eggs')
764
765If your mock is only being called once you can use the
766:meth:`assert_called_once_with` method that also asserts that the
767:attr:`call_count` is one.
768
769 >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
770 >>> mock.foo_bar()
771 >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
772 Traceback (most recent call last):
773 ...
774 AssertionError: Expected to be called once. Called 2 times.
775
Georg Brandl7ad3df62014-10-31 07:59:37 +0100776Both ``assert_called_with`` and ``assert_called_once_with`` make assertions about
Michael Foord944e02d2012-03-25 23:12:55 +0100777the *most recent* call. If your mock is going to be called several times, and
778you want to make assertions about *all* those calls you can use
779:attr:`~Mock.call_args_list`:
780
781 >>> mock = Mock(return_value=None)
782 >>> mock(1, 2, 3)
783 >>> mock(4, 5, 6)
784 >>> mock()
785 >>> mock.call_args_list
786 [call(1, 2, 3), call(4, 5, 6), call()]
787
788The :data:`call` helper makes it easy to make assertions about these calls. You
Georg Brandl7ad3df62014-10-31 07:59:37 +0100789can build up a list of expected calls and compare it to ``call_args_list``. This
790looks remarkably similar to the repr of the ``call_args_list``:
Michael Foord944e02d2012-03-25 23:12:55 +0100791
792 >>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
793 >>> mock.call_args_list == expected
794 True
795
796
797Coping with mutable arguments
Georg Brandl7fc972a2013-02-03 14:00:04 +0100798~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100799
800Another situation is rare, but can bite you, is when your mock is called with
Georg Brandl7ad3df62014-10-31 07:59:37 +0100801mutable arguments. ``call_args`` and ``call_args_list`` store *references* to the
Michael Foord944e02d2012-03-25 23:12:55 +0100802arguments. If the arguments are mutated by the code under test then you can no
803longer make assertions about what the values were when the mock was called.
804
805Here's some example code that shows the problem. Imagine the following functions
806defined in 'mymodule'::
807
808 def frob(val):
809 pass
810
811 def grob(val):
812 "First frob and then clear val"
813 frob(val)
814 val.clear()
815
Georg Brandl7ad3df62014-10-31 07:59:37 +0100816When we try to test that ``grob`` calls ``frob`` with the correct argument look
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200817what happens::
Michael Foord944e02d2012-03-25 23:12:55 +0100818
819 >>> with patch('mymodule.frob') as mock_frob:
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200820 ... val = {6}
Michael Foord944e02d2012-03-25 23:12:55 +0100821 ... mymodule.grob(val)
822 ...
823 >>> val
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200824 set()
825 >>> mock_frob.assert_called_with({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100826 Traceback (most recent call last):
827 ...
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200828 AssertionError: Expected: (({6},), {})
829 Called with: ((set(),), {})
Michael Foord944e02d2012-03-25 23:12:55 +0100830
831One possibility would be for mock to copy the arguments you pass in. This
832could then cause problems if you do assertions that rely on object identity
833for equality.
834
835Here's one solution that uses the :attr:`side_effect`
Georg Brandl7ad3df62014-10-31 07:59:37 +0100836functionality. If you provide a ``side_effect`` function for a mock then
837``side_effect`` will be called with the same args as the mock. This gives us an
Michael Foord944e02d2012-03-25 23:12:55 +0100838opportunity to copy the arguments and store them for later assertions. In this
839example I'm using *another* mock to store the arguments so that I can use the
840mock methods for doing the assertion. Again a helper function sets this up for
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200841me. ::
Michael Foord944e02d2012-03-25 23:12:55 +0100842
843 >>> from copy import deepcopy
844 >>> from unittest.mock import Mock, patch, DEFAULT
845 >>> def copy_call_args(mock):
846 ... new_mock = Mock()
847 ... def side_effect(*args, **kwargs):
848 ... args = deepcopy(args)
849 ... kwargs = deepcopy(kwargs)
850 ... new_mock(*args, **kwargs)
851 ... return DEFAULT
852 ... mock.side_effect = side_effect
853 ... return new_mock
854 ...
855 >>> with patch('mymodule.frob') as mock_frob:
856 ... new_mock = copy_call_args(mock_frob)
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200857 ... val = {6}
Michael Foord944e02d2012-03-25 23:12:55 +0100858 ... mymodule.grob(val)
859 ...
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200860 >>> new_mock.assert_called_with({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100861 >>> new_mock.call_args
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200862 call({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100863
Georg Brandl7ad3df62014-10-31 07:59:37 +0100864``copy_call_args`` is called with the mock that will be called. It returns a new
865mock that we do the assertion on. The ``side_effect`` function makes a copy of
866the args and calls our ``new_mock`` with the copy.
Michael Foord944e02d2012-03-25 23:12:55 +0100867
868.. note::
869
870 If your mock is only going to be used once there is an easier way of
871 checking arguments at the point they are called. You can simply do the
Georg Brandl7ad3df62014-10-31 07:59:37 +0100872 checking inside a ``side_effect`` function.
Michael Foord944e02d2012-03-25 23:12:55 +0100873
874 >>> def side_effect(arg):
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200875 ... assert arg == {6}
Michael Foord944e02d2012-03-25 23:12:55 +0100876 ...
877 >>> mock = Mock(side_effect=side_effect)
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200878 >>> mock({6})
Michael Foord944e02d2012-03-25 23:12:55 +0100879 >>> mock(set())
880 Traceback (most recent call last):
881 ...
882 AssertionError
883
Georg Brandl7ad3df62014-10-31 07:59:37 +0100884An alternative approach is to create a subclass of :class:`Mock` or
885:class:`MagicMock` that copies (using :func:`copy.deepcopy`) the arguments.
Michael Foord944e02d2012-03-25 23:12:55 +0100886Here's an example implementation:
887
888 >>> from copy import deepcopy
889 >>> class CopyingMock(MagicMock):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300890 ... def __call__(self, /, *args, **kwargs):
Michael Foord944e02d2012-03-25 23:12:55 +0100891 ... args = deepcopy(args)
892 ... kwargs = deepcopy(kwargs)
893 ... return super(CopyingMock, self).__call__(*args, **kwargs)
894 ...
895 >>> c = CopyingMock(return_value=None)
896 >>> arg = set()
897 >>> c(arg)
898 >>> arg.add(1)
899 >>> c.assert_called_with(set())
900 >>> c.assert_called_with(arg)
901 Traceback (most recent call last):
902 ...
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200903 AssertionError: Expected call: mock({1})
904 Actual call: mock(set())
Michael Foord944e02d2012-03-25 23:12:55 +0100905 >>> c.foo
906 <CopyingMock name='mock.foo' id='...'>
907
Georg Brandl7ad3df62014-10-31 07:59:37 +0100908When you subclass ``Mock`` or ``MagicMock`` all dynamically created attributes,
909and the ``return_value`` will use your subclass automatically. That means all
910children of a ``CopyingMock`` will also have the type ``CopyingMock``.
Michael Foord944e02d2012-03-25 23:12:55 +0100911
912
Michael Foord944e02d2012-03-25 23:12:55 +0100913Nesting Patches
Georg Brandl7fc972a2013-02-03 14:00:04 +0100914~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100915
916Using patch as a context manager is nice, but if you do multiple patches you
917can end up with nested with statements indenting further and further to the
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200918right::
Michael Foord944e02d2012-03-25 23:12:55 +0100919
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200920 >>> class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100921 ...
922 ... def test_foo(self):
923 ... with patch('mymodule.Foo') as mock_foo:
924 ... with patch('mymodule.Bar') as mock_bar:
925 ... with patch('mymodule.Spam') as mock_spam:
926 ... assert mymodule.Foo is mock_foo
927 ... assert mymodule.Bar is mock_bar
928 ... assert mymodule.Spam is mock_spam
929 ...
930 >>> original = mymodule.Foo
931 >>> MyTest('test_foo').test_foo()
932 >>> assert mymodule.Foo is original
933
Georg Brandl7ad3df62014-10-31 07:59:37 +0100934With unittest ``cleanup`` functions and the :ref:`start-and-stop` we can
Michael Foord944e02d2012-03-25 23:12:55 +0100935achieve the same effect without the nested indentation. A simple helper
Georg Brandl7ad3df62014-10-31 07:59:37 +0100936method, ``create_patch``, puts the patch in place and returns the created mock
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200937for us::
Michael Foord944e02d2012-03-25 23:12:55 +0100938
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200939 >>> class MyTest(unittest.TestCase):
Michael Foord944e02d2012-03-25 23:12:55 +0100940 ...
941 ... def create_patch(self, name):
942 ... patcher = patch(name)
943 ... thing = patcher.start()
944 ... self.addCleanup(patcher.stop)
945 ... return thing
946 ...
947 ... def test_foo(self):
948 ... mock_foo = self.create_patch('mymodule.Foo')
949 ... mock_bar = self.create_patch('mymodule.Bar')
950 ... mock_spam = self.create_patch('mymodule.Spam')
951 ...
952 ... assert mymodule.Foo is mock_foo
953 ... assert mymodule.Bar is mock_bar
954 ... assert mymodule.Spam is mock_spam
955 ...
956 >>> original = mymodule.Foo
957 >>> MyTest('test_foo').run()
958 >>> assert mymodule.Foo is original
959
960
961Mocking a dictionary with MagicMock
Georg Brandl7fc972a2013-02-03 14:00:04 +0100962~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100963
964You may want to mock a dictionary, or other container object, recording all
965access to it whilst having it still behave like a dictionary.
966
967We can do this with :class:`MagicMock`, which will behave like a dictionary,
968and using :data:`~Mock.side_effect` to delegate dictionary access to a real
969underlying dictionary that is under our control.
970
Georg Brandl7ad3df62014-10-31 07:59:37 +0100971When the :meth:`__getitem__` and :meth:`__setitem__` methods of our ``MagicMock`` are called
972(normal dictionary access) then ``side_effect`` is called with the key (and in
973the case of ``__setitem__`` the value too). We can also control what is returned.
Michael Foord944e02d2012-03-25 23:12:55 +0100974
Georg Brandl7ad3df62014-10-31 07:59:37 +0100975After the ``MagicMock`` has been used we can use attributes like
Michael Foord944e02d2012-03-25 23:12:55 +0100976:data:`~Mock.call_args_list` to assert about how the dictionary was used:
977
978 >>> my_dict = {'a': 1, 'b': 2, 'c': 3}
979 >>> def getitem(name):
980 ... return my_dict[name]
981 ...
982 >>> def setitem(name, val):
983 ... my_dict[name] = val
984 ...
985 >>> mock = MagicMock()
986 >>> mock.__getitem__.side_effect = getitem
987 >>> mock.__setitem__.side_effect = setitem
988
989.. note::
990
Georg Brandl7ad3df62014-10-31 07:59:37 +0100991 An alternative to using ``MagicMock`` is to use ``Mock`` and *only* provide
Michael Foord944e02d2012-03-25 23:12:55 +0100992 the magic methods you specifically want:
993
994 >>> mock = Mock()
Éric Araujo0b1be1a2014-03-17 16:48:13 -0400995 >>> mock.__getitem__ = Mock(side_effect=getitem)
996 >>> mock.__setitem__ = Mock(side_effect=setitem)
Michael Foord944e02d2012-03-25 23:12:55 +0100997
Georg Brandl7ad3df62014-10-31 07:59:37 +0100998 A *third* option is to use ``MagicMock`` but passing in ``dict`` as the *spec*
999 (or *spec_set*) argument so that the ``MagicMock`` created only has
Michael Foord944e02d2012-03-25 23:12:55 +01001000 dictionary magic methods available:
1001
1002 >>> mock = MagicMock(spec_set=dict)
1003 >>> mock.__getitem__.side_effect = getitem
1004 >>> mock.__setitem__.side_effect = setitem
1005
Georg Brandl7ad3df62014-10-31 07:59:37 +01001006With these side effect functions in place, the ``mock`` will behave like a normal
1007dictionary but recording the access. It even raises a :exc:`KeyError` if you try
Michael Foord944e02d2012-03-25 23:12:55 +01001008to access a key that doesn't exist.
1009
1010 >>> mock['a']
1011 1
1012 >>> mock['c']
1013 3
1014 >>> mock['d']
1015 Traceback (most recent call last):
1016 ...
1017 KeyError: 'd'
1018 >>> mock['b'] = 'fish'
1019 >>> mock['d'] = 'eggs'
1020 >>> mock['b']
1021 'fish'
1022 >>> mock['d']
1023 'eggs'
1024
1025After it has been used you can make assertions about the access using the normal
1026mock methods and attributes:
1027
1028 >>> mock.__getitem__.call_args_list
1029 [call('a'), call('c'), call('d'), call('b'), call('d')]
1030 >>> mock.__setitem__.call_args_list
1031 [call('b', 'fish'), call('d', 'eggs')]
1032 >>> my_dict
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001033 {'a': 1, 'b': 'fish', 'c': 3, 'd': 'eggs'}
Michael Foord944e02d2012-03-25 23:12:55 +01001034
1035
1036Mock subclasses and their attributes
Georg Brandl7fc972a2013-02-03 14:00:04 +01001037~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001038
Georg Brandl7ad3df62014-10-31 07:59:37 +01001039There are various reasons why you might want to subclass :class:`Mock`. One
1040reason might be to add helper methods. Here's a silly example:
Michael Foord944e02d2012-03-25 23:12:55 +01001041
1042 >>> class MyMock(MagicMock):
1043 ... def has_been_called(self):
1044 ... return self.called
1045 ...
1046 >>> mymock = MyMock(return_value=None)
1047 >>> mymock
1048 <MyMock id='...'>
1049 >>> mymock.has_been_called()
1050 False
1051 >>> mymock()
1052 >>> mymock.has_been_called()
1053 True
1054
Georg Brandl7ad3df62014-10-31 07:59:37 +01001055The standard behaviour for ``Mock`` instances is that attributes and the return
Michael Foord944e02d2012-03-25 23:12:55 +01001056value mocks are of the same type as the mock they are accessed on. This ensures
Georg Brandl7ad3df62014-10-31 07:59:37 +01001057that ``Mock`` attributes are ``Mocks`` and ``MagicMock`` attributes are ``MagicMocks``
Michael Foord944e02d2012-03-25 23:12:55 +01001058[#]_. So if you're subclassing to add helper methods then they'll also be
1059available on the attributes and return value mock of instances of your
1060subclass.
1061
1062 >>> mymock.foo
1063 <MyMock name='mock.foo' id='...'>
1064 >>> mymock.foo.has_been_called()
1065 False
1066 >>> mymock.foo()
1067 <MyMock name='mock.foo()' id='...'>
1068 >>> mymock.foo.has_been_called()
1069 True
1070
1071Sometimes this is inconvenient. For example, `one user
Sanyam Khurana338cd832018-01-20 05:55:37 +05301072<https://code.google.com/archive/p/mock/issues/105>`_ is subclassing mock to
Michael Foord944e02d2012-03-25 23:12:55 +01001073created a `Twisted adaptor
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001074<https://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html>`_.
Michael Foord944e02d2012-03-25 23:12:55 +01001075Having this applied to attributes too actually causes errors.
1076
Georg Brandl7ad3df62014-10-31 07:59:37 +01001077``Mock`` (in all its flavours) uses a method called ``_get_child_mock`` to create
Michael Foord944e02d2012-03-25 23:12:55 +01001078these "sub-mocks" for attributes and return values. You can prevent your
1079subclass being used for attributes by overriding this method. The signature is
Georg Brandl7ad3df62014-10-31 07:59:37 +01001080that it takes arbitrary keyword arguments (``**kwargs``) which are then passed
Michael Foord944e02d2012-03-25 23:12:55 +01001081onto the mock constructor:
1082
1083 >>> class Subclass(MagicMock):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001084 ... def _get_child_mock(self, /, **kwargs):
Michael Foord944e02d2012-03-25 23:12:55 +01001085 ... return MagicMock(**kwargs)
1086 ...
1087 >>> mymock = Subclass()
1088 >>> mymock.foo
1089 <MagicMock name='mock.foo' id='...'>
1090 >>> assert isinstance(mymock, Subclass)
1091 >>> assert not isinstance(mymock.foo, Subclass)
1092 >>> assert not isinstance(mymock(), Subclass)
1093
1094.. [#] An exception to this rule are the non-callable mocks. Attributes use the
1095 callable variant because otherwise non-callable mocks couldn't have callable
1096 methods.
1097
1098
1099Mocking imports with patch.dict
Georg Brandl7fc972a2013-02-03 14:00:04 +01001100~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001101
1102One situation where mocking can be hard is where you have a local import inside
1103a function. These are harder to mock because they aren't using an object from
1104the module namespace that we can patch out.
1105
1106Generally local imports are to be avoided. They are sometimes done to prevent
1107circular dependencies, for which there is *usually* a much better way to solve
1108the problem (refactor the code) or to prevent "up front costs" by delaying the
1109import. This can also be solved in better ways than an unconditional local
1110import (store the module as a class or module attribute and only do the import
1111on first use).
1112
Georg Brandl7ad3df62014-10-31 07:59:37 +01001113That aside there is a way to use ``mock`` to affect the results of an import.
1114Importing fetches an *object* from the :data:`sys.modules` dictionary. Note that it
Michael Foord944e02d2012-03-25 23:12:55 +01001115fetches an *object*, which need not be a module. Importing a module for the
1116first time results in a module object being put in `sys.modules`, so usually
1117when you import something you get a module back. This need not be the case
1118however.
1119
1120This means you can use :func:`patch.dict` to *temporarily* put a mock in place
Georg Brandl7ad3df62014-10-31 07:59:37 +01001121in :data:`sys.modules`. Any imports whilst this patch is active will fetch the mock.
Michael Foord944e02d2012-03-25 23:12:55 +01001122When the patch is complete (the decorated function exits, the with statement
Georg Brandl7ad3df62014-10-31 07:59:37 +01001123body is complete or ``patcher.stop()`` is called) then whatever was there
Michael Foord944e02d2012-03-25 23:12:55 +01001124previously will be restored safely.
1125
1126Here's an example that mocks out the 'fooble' module.
1127
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001128 >>> import sys
Michael Foord944e02d2012-03-25 23:12:55 +01001129 >>> mock = Mock()
1130 >>> with patch.dict('sys.modules', {'fooble': mock}):
1131 ... import fooble
1132 ... fooble.blob()
1133 ...
1134 <Mock name='mock.blob()' id='...'>
1135 >>> assert 'fooble' not in sys.modules
1136 >>> mock.blob.assert_called_once_with()
1137
Georg Brandl7ad3df62014-10-31 07:59:37 +01001138As you can see the ``import fooble`` succeeds, but on exit there is no 'fooble'
1139left in :data:`sys.modules`.
Michael Foord944e02d2012-03-25 23:12:55 +01001140
Georg Brandl7ad3df62014-10-31 07:59:37 +01001141This also works for the ``from module import name`` form:
Michael Foord944e02d2012-03-25 23:12:55 +01001142
1143 >>> mock = Mock()
1144 >>> with patch.dict('sys.modules', {'fooble': mock}):
1145 ... from fooble import blob
1146 ... blob.blip()
1147 ...
1148 <Mock name='mock.blob.blip()' id='...'>
1149 >>> mock.blob.blip.assert_called_once_with()
1150
1151With slightly more work you can also mock package imports:
1152
1153 >>> mock = Mock()
1154 >>> modules = {'package': mock, 'package.module': mock.module}
1155 >>> with patch.dict('sys.modules', modules):
1156 ... from package.module import fooble
1157 ... fooble()
1158 ...
1159 <Mock name='mock.module.fooble()' id='...'>
1160 >>> mock.module.fooble.assert_called_once_with()
1161
1162
1163Tracking order of calls and less verbose call assertions
Georg Brandl7fc972a2013-02-03 14:00:04 +01001164~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001165
1166The :class:`Mock` class allows you to track the *order* of method calls on
1167your mock objects through the :attr:`~Mock.method_calls` attribute. This
1168doesn't allow you to track the order of calls between separate mock objects,
1169however we can use :attr:`~Mock.mock_calls` to achieve the same effect.
1170
Georg Brandl7ad3df62014-10-31 07:59:37 +01001171Because mocks track calls to child mocks in ``mock_calls``, and accessing an
Michael Foord944e02d2012-03-25 23:12:55 +01001172arbitrary attribute of a mock creates a child mock, we can create our separate
1173mocks from a parent one. Calls to those child mock will then all be recorded,
Georg Brandl7ad3df62014-10-31 07:59:37 +01001174in order, in the ``mock_calls`` of the parent:
Michael Foord944e02d2012-03-25 23:12:55 +01001175
1176 >>> manager = Mock()
1177 >>> mock_foo = manager.foo
1178 >>> mock_bar = manager.bar
1179
1180 >>> mock_foo.something()
1181 <Mock name='mock.foo.something()' id='...'>
1182 >>> mock_bar.other.thing()
1183 <Mock name='mock.bar.other.thing()' id='...'>
1184
1185 >>> manager.mock_calls
1186 [call.foo.something(), call.bar.other.thing()]
1187
1188We can then assert about the calls, including the order, by comparing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01001189the ``mock_calls`` attribute on the manager mock:
Michael Foord944e02d2012-03-25 23:12:55 +01001190
1191 >>> expected_calls = [call.foo.something(), call.bar.other.thing()]
1192 >>> manager.mock_calls == expected_calls
1193 True
1194
Georg Brandl7ad3df62014-10-31 07:59:37 +01001195If ``patch`` is creating, and putting in place, your mocks then you can attach
Michael Foord944e02d2012-03-25 23:12:55 +01001196them to a manager mock using the :meth:`~Mock.attach_mock` method. After
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001197attaching calls will be recorded in ``mock_calls`` of the manager. ::
Michael Foord944e02d2012-03-25 23:12:55 +01001198
1199 >>> manager = MagicMock()
1200 >>> with patch('mymodule.Class1') as MockClass1:
1201 ... with patch('mymodule.Class2') as MockClass2:
1202 ... manager.attach_mock(MockClass1, 'MockClass1')
1203 ... manager.attach_mock(MockClass2, 'MockClass2')
1204 ... MockClass1().foo()
1205 ... MockClass2().bar()
Michael Foord944e02d2012-03-25 23:12:55 +01001206 <MagicMock name='mock.MockClass1().foo()' id='...'>
1207 <MagicMock name='mock.MockClass2().bar()' id='...'>
1208 >>> manager.mock_calls
1209 [call.MockClass1(),
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001210 call.MockClass1().foo(),
1211 call.MockClass2(),
1212 call.MockClass2().bar()]
Michael Foord944e02d2012-03-25 23:12:55 +01001213
1214If many calls have been made, but you're only interested in a particular
1215sequence of them then an alternative is to use the
1216:meth:`~Mock.assert_has_calls` method. This takes a list of calls (constructed
1217with the :data:`call` object). If that sequence of calls are in
1218:attr:`~Mock.mock_calls` then the assert succeeds.
1219
1220 >>> m = MagicMock()
1221 >>> m().foo().bar().baz()
1222 <MagicMock name='mock().foo().bar().baz()' id='...'>
1223 >>> m.one().two().three()
1224 <MagicMock name='mock.one().two().three()' id='...'>
1225 >>> calls = call.one().two().three().call_list()
1226 >>> m.assert_has_calls(calls)
1227
Georg Brandl7ad3df62014-10-31 07:59:37 +01001228Even though the chained call ``m.one().two().three()`` aren't the only calls that
Michael Foord944e02d2012-03-25 23:12:55 +01001229have been made to the mock, the assert still succeeds.
1230
1231Sometimes a mock may have several calls made to it, and you are only interested
1232in asserting about *some* of those calls. You may not even care about the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001233order. In this case you can pass ``any_order=True`` to ``assert_has_calls``:
Michael Foord944e02d2012-03-25 23:12:55 +01001234
1235 >>> m = MagicMock()
1236 >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
1237 (...)
1238 >>> calls = [call.fifty('50'), call(1), call.seven(7)]
1239 >>> m.assert_has_calls(calls, any_order=True)
1240
1241
1242More complex argument matching
Georg Brandl7fc972a2013-02-03 14:00:04 +01001243~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001244
1245Using the same basic concept as :data:`ANY` we can implement matchers to do more
1246complex assertions on objects used as arguments to mocks.
1247
1248Suppose we expect some object to be passed to a mock that by default
1249compares equal based on object identity (which is the Python default for user
1250defined classes). To use :meth:`~Mock.assert_called_with` we would need to pass
1251in the exact same object. If we are only interested in some of the attributes
1252of this object then we can create a matcher that will check these attributes
1253for us.
1254
Georg Brandl7ad3df62014-10-31 07:59:37 +01001255You can see in this example how a 'standard' call to ``assert_called_with`` isn't
Michael Foord944e02d2012-03-25 23:12:55 +01001256sufficient:
1257
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001258 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +01001259 ... def __init__(self, a, b):
1260 ... self.a, self.b = a, b
1261 ...
1262 >>> mock = Mock(return_value=None)
1263 >>> mock(Foo(1, 2))
1264 >>> mock.assert_called_with(Foo(1, 2))
1265 Traceback (most recent call last):
1266 ...
1267 AssertionError: Expected: call(<__main__.Foo object at 0x...>)
1268 Actual call: call(<__main__.Foo object at 0x...>)
1269
Georg Brandl7ad3df62014-10-31 07:59:37 +01001270A comparison function for our ``Foo`` class might look something like this:
Michael Foord944e02d2012-03-25 23:12:55 +01001271
1272 >>> def compare(self, other):
1273 ... if not type(self) == type(other):
1274 ... return False
1275 ... if self.a != other.a:
1276 ... return False
1277 ... if self.b != other.b:
1278 ... return False
1279 ... return True
1280 ...
1281
1282And a matcher object that can use comparison functions like this for its
1283equality operation would look something like this:
1284
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001285 >>> class Matcher:
Michael Foord944e02d2012-03-25 23:12:55 +01001286 ... def __init__(self, compare, some_obj):
1287 ... self.compare = compare
1288 ... self.some_obj = some_obj
1289 ... def __eq__(self, other):
1290 ... return self.compare(self.some_obj, other)
1291 ...
1292
1293Putting all this together:
1294
1295 >>> match_foo = Matcher(compare, Foo(1, 2))
1296 >>> mock.assert_called_with(match_foo)
1297
Georg Brandl7ad3df62014-10-31 07:59:37 +01001298The ``Matcher`` is instantiated with our compare function and the ``Foo`` object
1299we want to compare against. In ``assert_called_with`` the ``Matcher`` equality
Michael Foord944e02d2012-03-25 23:12:55 +01001300method will be called, which compares the object the mock was called with
1301against the one we created our matcher with. If they match then
Georg Brandl7ad3df62014-10-31 07:59:37 +01001302``assert_called_with`` passes, and if they don't an :exc:`AssertionError` is raised:
Michael Foord944e02d2012-03-25 23:12:55 +01001303
1304 >>> match_wrong = Matcher(compare, Foo(3, 4))
1305 >>> mock.assert_called_with(match_wrong)
1306 Traceback (most recent call last):
1307 ...
1308 AssertionError: Expected: ((<Matcher object at 0x...>,), {})
1309 Called with: ((<Foo object at 0x...>,), {})
1310
1311With a bit of tweaking you could have the comparison function raise the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001312:exc:`AssertionError` directly and provide a more useful failure message.
Michael Foord944e02d2012-03-25 23:12:55 +01001313
1314As of version 1.5, the Python testing library `PyHamcrest
Sanyam Khurana338cd832018-01-20 05:55:37 +05301315<https://pyhamcrest.readthedocs.io/>`_ provides similar functionality,
Michael Foord944e02d2012-03-25 23:12:55 +01001316that may be useful here, in the form of its equality matcher
1317(`hamcrest.library.integration.match_equality
Sanyam Khurana338cd832018-01-20 05:55:37 +05301318<https://pyhamcrest.readthedocs.io/en/release-1.8/integration/#module-hamcrest.library.integration.match_equality>`_).