• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`unittest.mock` --- getting started
2========================================
3
4.. moduleauthor:: Michael Foord <michael@python.org>
5.. currentmodule:: unittest.mock
6
7.. versionadded:: 3.3
8
9
10.. _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
31Once our mock has been used (``real.method`` in this example) it has methods
32and 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
37    are interchangeable. As the ``MagicMock`` is the more capable class it makes
38    a sensible one to use by default.
39
40Once the mock has been called its :attr:`~Mock.called` attribute is set to
41``True``. More importantly we can use the :meth:`~Mock.assert_called_with` or
42:meth:`~Mock.assert_called_once_with` method to check that it was called with
43the correct arguments.
44
45This example tests that calling ``ProductionClass().method`` results in a call to
46the ``something`` method:
47
48    >>> class ProductionClass:
49    ...     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
69The simple ``ProductionClass`` below has a ``closer`` method. If it is called with
70an object then it calls ``close`` on it.
71
72    >>> class ProductionClass:
73    ...     def closer(self, something):
74    ...         something.close()
75    ...
76
77So to test it we need to pass in an object with a ``close`` method and check
78that 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
99In 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
102by modifying the mock :attr:`~Mock.return_value`.
103
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
144If you make an assertion about ``mock_calls`` and any unexpected methods
145have 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
150``mock_calls``:
151
152    >>> expected = [call.method(), call.attribute.method(10, x=53)]
153    >>> mock.mock_calls == expected
154    True
155
156However, 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
165
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
197``mock.connection.cursor().execute("SELECT 1")``. If we wanted this call to
198return 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
214It is the call to ``.call_list()`` that turns our call object into a list of
215calls 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
235``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
237times, and you want each call to return a different value. When you set
238``side_effect`` to an iterable every call to the mock returns the next value
239from 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
251depending on what the mock is called with, ``side_effect`` can be a function.
252The 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
271class 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
274your tests will continue to pass even though your code is now broken!
275
276:class:`Mock` allows you to provide an object as a specification for the mock,
277using the *spec* keyword argument. Accessing methods / attributes on the
278mock 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
289Using 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
303If 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
305*spec_set* instead of *spec*.
306
307
308
309Patch Decorators
310----------------
311
312.. note::
313
314   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
316   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
325mock 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
328also 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
333``patch.object``:
334
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
350If you are patching a module (including :mod:`builtins`) then use :func:`patch`
351instead of :func:`patch.object`:
352
353    >>> mock = MagicMock(return_value=sentinel.file_handle)
354    >>> with patch('builtins.open', mock):
355    ...     handle = open('filename', 'r')
356    ...
357    >>> mock.assert_called_with('filename', 'r')
358    >>> assert handle == sentinel.file_handle, "incorrect file handle returned"
359
360The module name can be 'dotted', in the form ``package.module`` if needed:
361
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
371    >>> class MyTest(unittest.TestCase):
372    ...     @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
380If 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
382passed into the test function / method:
383
384    >>> class MyTest(unittest.TestCase):
385    ...     @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
394    >>> class MyTest(unittest.TestCase):
395    ...     @patch('package.module.ClassName1')
396    ...     @patch('package.module.ClassName2')
397    ...     def test_something(self, MockClass2, MockClass1):
398    ...         self.assertIs(package.module.ClassName1, MockClass1)
399    ...         self.assertIs(package.module.ClassName2, MockClass2)
400    ...
401    >>> MyTest('test_something').test_something()
402
403When you nest patch decorators the mocks are passed in to the decorated
404function in the same order they applied (the normal *Python* order that
405decorators are applied). This means from the bottom up, so in the example
406above the mock for ``test_module.ClassName2`` is passed in first.
407
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
419``patch``, ``patch.object`` and ``patch.dict`` can all be used as context managers.
420
421Where you use :func:`patch` to create a mock for you, you can get a reference to the
422mock using the "as" form of the with statement:
423
424    >>> class ProductionClass:
425    ...     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
436As an alternative ``patch``, ``patch.object`` and ``patch.dict`` can be used as
437class decorators. When used in this way it is the same as applying the
438decorator individually to every method whose name starts with "test".
439
440
441.. _further-examples:
442
443Further Examples
444----------------
445
446
447Here are some more examples for some slightly more advanced scenarios.
448
449
450Mocking chained calls
451~~~~~~~~~~~~~~~~~~~~~
452
453Mocking chained calls is actually straightforward with mock once you
454understand the :attr:`~Mock.return_value` attribute. When a mock is called for
455the first time, or you fetch its ``return_value`` before it has been called, a
456new :class:`Mock` is created.
457
458This means that you can see how the object returned from a call to a mocked
459object has been used by interrogating the ``return_value`` mock:
460
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
472    >>> class Something:
473    ...     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
479Assuming 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.
482
483As this chain of calls is made from an instance attribute we can monkey patch
484the ``backend`` attribute on a ``Something`` instance. In this particular case
485we are only interested in the return value from the final call to
486``start_call`` so we don't have much configuration to do. Let's assume the
487object it returns is 'file-like', so we'll ensure that our response object
488uses the builtin :func:`open` as its ``spec``.
489
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
492``start_call`` we could do this::
493
494    mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response
495
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()
500    >>> mock_response = Mock(spec=open)
501    >>> 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
513several entries in ``mock_calls``. We can use :meth:`call.call_list` to create
514this 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
522~~~~~~~~~~~~~~~
523
524In some tests I wanted to mock out a call to :meth:`datetime.date.today`
525to return a known date, but I didn't want to prevent the code under test from
526creating 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.
528
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
534mock out the ``date`` class in the module under test. The :attr:`side_effect`
535attribute 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
537constructed and returned by ``side_effect``.
538
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
548Note that we don't patch :class:`datetime.date` globally, we patch ``date`` in the
549module that *uses* it. See :ref:`where to patch <where-to-patch>`.
550
551When ``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
553yourself having to calculate an expected result using exactly the same
554algorithm as the code under test, which is a classic testing anti-pattern.
555
556Calls to the date constructor are recorded in the ``mock_date`` attributes
557(``call_count`` and friends) which may also be useful for your tests.
558
559An alternative way of dealing with mocking dates, or other builtin classes,
560is discussed in `this blog entry
561<https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/>`_.
562
563
564Mocking a Generator Method
565~~~~~~~~~~~~~~~~~~~~~~~~~~
566
567A Python generator is a function or method that uses the :keyword:`yield` statement
568to return a series of values when iterated over [#]_.
569
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
572iteration is :meth:`~container.__iter__`, so we can
573mock this using a :class:`MagicMock`.
574
575Here's an example class with an "iter" method implemented as a generator:
576
577    >>> class Foo:
578    ...     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
590:class:`list`), we need to configure the object returned by the call to ``foo.iter()``.
591
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
605~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
606
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
609repetition. For Python 2.6 or more recent you can use :func:`patch` (in all its
610various 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
612with ``test``:
613
614    >>> @patch('mymodule.SomeClass')
615    ... class MyTest(TestCase):
616    ...
617    ...     def test_one(self, MockSomeClass):
618    ...         self.assertIs(mymodule.SomeClass, MockSomeClass)
619    ...
620    ...     def test_two(self, MockSomeClass):
621    ...         self.assertIs(mymodule.SomeClass, MockSomeClass)
622    ...
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`.
632These allow you to move the patching into your ``setUp`` and ``tearDown`` methods.
633
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):
640    ...         self.assertIs(mymodule.foo, self.mock_foo)
641    ...
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
648calling ``stop``. This can be fiddlier than you might think, because if an
649exception 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):
659    ...         self.assertIs(mymodule.foo, self.mock_foo)
660    ...
661    >>> MyTest('test_foo').run()
662
663
664Mocking Unbound Methods
665~~~~~~~~~~~~~~~~~~~~~~~
666
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
678If you pass ``autospec=True`` to patch then it does the patching with a
679*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.
684It will have ``self`` passed in as the first argument, which is exactly what I
685wanted:
686
687    >>> class Foo:
688    ...   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
699If we don't use ``autospec=True`` then the unbound method is patched out
700with a Mock instance instead, and isn't called with ``self``.
701
702
703Checking multiple calls with mock
704~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
705
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
724Both ``assert_called_with`` and ``assert_called_once_with`` make assertions about
725the *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
737can 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``:
739
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
746~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
747
748Another situation is rare, but can bite you, is when your mock is called with
749mutable arguments. ``call_args`` and ``call_args_list`` store *references* to the
750arguments. 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
764When we try to test that ``grob`` calls ``frob`` with the correct argument look
765what happens:
766
767    >>> with patch('mymodule.frob') as mock_frob:
768    ...     val = {6}
769    ...     mymodule.grob(val)
770    ...
771    >>> val
772    set()
773    >>> mock_frob.assert_called_with({6})
774    Traceback (most recent call last):
775        ...
776    AssertionError: Expected: (({6},), {})
777    Called with: ((set(),), {})
778
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`
784functionality. 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
786opportunity 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)
805    ...     val = {6}
806    ...     mymodule.grob(val)
807    ...
808    >>> new_mock.assert_called_with({6})
809    >>> new_mock.call_args
810    call({6})
811
812``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.
815
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
820    checking inside a ``side_effect`` function.
821
822        >>> def side_effect(arg):
823        ...     assert arg == {6}
824        ...
825        >>> mock = Mock(side_effect=side_effect)
826        >>> mock({6})
827        >>> mock(set())
828        Traceback (most recent call last):
829            ...
830        AssertionError
831
832An alternative approach is to create a subclass of :class:`Mock` or
833:class:`MagicMock` that copies (using :func:`copy.deepcopy`) the arguments.
834Here'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        ...
851    AssertionError: Expected call: mock({1})
852    Actual call: mock(set())
853    >>> c.foo
854    <CopyingMock name='mock.foo' id='...'>
855
856When 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``.
859
860
861Nesting Patches
862~~~~~~~~~~~~~~~
863
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
882With unittest ``cleanup`` functions and the :ref:`start-and-stop` we can
883achieve the same effect without the nested indentation. A simple helper
884method, ``create_patch``, puts the patch in place and returns the created mock
885for 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
910~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
911
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
919When 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.
922
923After the ``MagicMock`` has been used we can use attributes like
924: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
939    An alternative to using ``MagicMock`` is to use ``Mock`` and *only* provide
940    the magic methods you specifically want:
941
942        >>> mock = Mock()
943        >>> mock.__getitem__ = Mock(side_effect=getitem)
944        >>> mock.__setitem__ = Mock(side_effect=setitem)
945
946    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
948    dictionary magic methods available:
949
950        >>> mock = MagicMock(spec_set=dict)
951        >>> mock.__getitem__.side_effect = getitem
952        >>> mock.__setitem__.side_effect = setitem
953
954With 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
956to 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
985~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
986
987There are various reasons why you might want to subclass :class:`Mock`. One
988reason might be to add helper methods. Here's a silly example:
989
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
1003The standard behaviour for ``Mock`` instances is that attributes and the return
1004value mocks are of the same type as the mock they are accessed on. This ensures
1005that ``Mock`` attributes are ``Mocks`` and ``MagicMock`` attributes are ``MagicMocks``
1006[#]_. 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
1020<https://code.google.com/archive/p/mock/issues/105>`_ is subclassing mock to
1021created a `Twisted adaptor
1022<https://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html>`_.
1023Having this applied to attributes too actually causes errors.
1024
1025``Mock`` (in all its flavours) uses a method called ``_get_child_mock`` to create
1026these "sub-mocks" for attributes and return values. You can prevent your
1027subclass being used for attributes by overriding this method. The signature is
1028that it takes arbitrary keyword arguments (``**kwargs``) which are then passed
1029onto 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
1048~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1049
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
1061That 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
1063fetches 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
1069in :data:`sys.modules`. Any imports whilst this patch is active will fetch the mock.
1070When the patch is complete (the decorated function exits, the with statement
1071body is complete or ``patcher.stop()`` is called) then whatever was there
1072previously 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
1085As you can see the ``import fooble`` succeeds, but on exit there is no 'fooble'
1086left in :data:`sys.modules`.
1087
1088This also works for the ``from module import name`` form:
1089
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
1111~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1112
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
1118Because mocks track calls to child mocks in ``mock_calls``, and accessing an
1119arbitrary 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,
1121in order, in the ``mock_calls`` of the parent:
1122
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
1136the ``mock_calls`` attribute on the manager mock:
1137
1138    >>> expected_calls = [call.foo.something(), call.bar.other.thing()]
1139    >>> manager.mock_calls == expected_calls
1140    True
1141
1142If ``patch`` is creating, and putting in place, your mocks then you can attach
1143them to a manager mock using the :meth:`~Mock.attach_mock` method. After
1144attaching calls will be recorded in ``mock_calls`` of the manager.
1145
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
1176Even though the chained call ``m.one().two().three()`` aren't the only calls that
1177have 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
1181order. In this case you can pass ``any_order=True`` to ``assert_has_calls``:
1182
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
1191~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1192
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
1203You can see in this example how a 'standard' call to ``assert_called_with`` isn't
1204sufficient:
1205
1206    >>> class Foo:
1207    ...     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
1218A comparison function for our ``Foo`` class might look something like this:
1219
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
1233    >>> class Matcher:
1234    ...     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
1246The ``Matcher`` is instantiated with our compare function and the ``Foo`` object
1247we want to compare against. In ``assert_called_with`` the ``Matcher`` equality
1248method will be called, which compares the object the mock was called with
1249against the one we created our matcher with. If they match then
1250``assert_called_with`` passes, and if they don't an :exc:`AssertionError` is raised:
1251
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
1260:exc:`AssertionError` directly and provide a more useful failure message.
1261
1262As of version 1.5, the Python testing library `PyHamcrest
1263<https://pyhamcrest.readthedocs.io/>`_ provides similar functionality,
1264that may be useful here, in the form of its equality matcher
1265(`hamcrest.library.integration.match_equality
1266<https://pyhamcrest.readthedocs.io/en/release-1.8/integration/#module-hamcrest.library.integration.match_equality>`_).
1267