• 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 
12 
13 .. testsetup::
14 
15     import asyncio
16     import unittest
17     from unittest.mock import Mock, MagicMock, AsyncMock, patch, call, sentinel
18 
19     class SomeClass:
20         attribute = 'this is a doctest'
21 
22         @staticmethod
23         def static_method():
24             pass
25 
26 Using Mock
27 ----------
28 
29 Mock Patching Methods
30 ~~~~~~~~~~~~~~~~~~~~~
31 
32 Common uses for :class:`Mock` objects include:
33 
34 * Patching methods
35 * Recording method calls on objects
36 
37 You might want to replace a method on an object to check that
38 it 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 
45 Once our mock has been used (``real.method`` in this example) it has methods
46 and 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
51     are interchangeable. As the ``MagicMock`` is the more capable class it makes
52     a sensible one to use by default.
53 
54 Once the mock has been called its :attr:`~Mock.called` attribute is set to
55 ``True``. More importantly we can use the :meth:`~Mock.assert_called_with` or
56 :meth:`~Mock.assert_called_once_with` method to check that it was called with
57 the correct arguments.
58 
59 This example tests that calling ``ProductionClass().method`` results in a call to
60 the ``something`` method:
61 
62     >>> class ProductionClass:
63     ...     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 
75 Mock for Method Calls on an Object
76 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
77 
78 In the last example we patched a method directly on an object to check that it
79 was called correctly. Another common use case is to pass an object into a
80 method (or some part of the system under test) and then check that it is used
81 in the correct way.
82 
83 The simple ``ProductionClass`` below has a ``closer`` method. If it is called with
84 an object then it calls ``close`` on it.
85 
86     >>> class ProductionClass:
87     ...     def closer(self, something):
88     ...         something.close()
89     ...
90 
91 So to test it we need to pass in an object with a ``close`` method and check
92 that it was called correctly.
93 
94     >>> real = ProductionClass()
95     >>> mock = Mock()
96     >>> real.closer(mock)
97     >>> mock.close.assert_called_with()
98 
99 We don't have to do any work to provide the 'close' method on our mock.
100 Accessing close creates it. So, if 'close' hasn't already been called then
101 accessing it in the test will create it, but :meth:`~Mock.assert_called_with`
102 will raise a failure exception.
103 
104 
105 Mocking Classes
106 ~~~~~~~~~~~~~~~
107 
108 A common use case is to mock out classes instantiated by your code under test.
109 When you patch a class, then that class is replaced with a mock. Instances
110 are created by *calling the class*. This means you access the "mock instance"
111 by looking at the return value of the mocked class.
112 
113 In the example below we have a function ``some_function`` that instantiates ``Foo``
114 and calls a method on it. The call to :func:`patch` replaces the class ``Foo`` with a
115 mock. The ``Foo`` instance is the result of calling the mock, so it is configured
116 by modifying the mock :attr:`~Mock.return_value`. ::
117 
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 
129 Naming your mocks
130 ~~~~~~~~~~~~~~~~~
131 
132 It can be useful to give your mocks a name. The name is shown in the repr of
133 the mock and can be helpful when the mock appears in test failure messages. The
134 name 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 
143 Tracking all Calls
144 ~~~~~~~~~~~~~~~~~~
145 
146 Often you want to track more than a single call to a method. The
147 :attr:`~Mock.mock_calls` attribute records all calls
148 to 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 
158 If you make an assertion about ``mock_calls`` and any unexpected methods
159 have been called, then the assertion will fail. This is useful because as well
160 as asserting that the calls you expected have been made, you are also checking
161 that they were made in the right order and with no additional calls:
162 
163 You use the :data:`call` object to construct lists for comparing with
164 ``mock_calls``:
165 
166     >>> expected = [call.method(), call.attribute.method(10, x=53)]
167     >>> mock.mock_calls == expected
168     True
169 
170 However, parameters to calls that return mocks are not recorded, which means it is not
171 possible 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 
179 
180 Setting Return Values and Attributes
181 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
182 
183 Setting the return values on a mock object is trivially easy:
184 
185     >>> mock = Mock()
186     >>> mock.return_value = 3
187     >>> mock()
188     3
189 
190 Of 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 
197 The return value can also be set in the constructor:
198 
199     >>> mock = Mock(return_value=3)
200     >>> mock()
201     3
202 
203 If 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 
210 Sometimes you want to mock up a more complex situation, like for example
211 ``mock.connection.cursor().execute("SELECT 1")``. If we wanted this call to
212 return a list, then we have to configure the result of the nested call.
213 
214 We can use :data:`call` to construct the set of calls in a "chained call" like
215 this 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 
228 It is the call to ``.call_list()`` that turns our call object into a list of
229 calls representing the chained calls.
230 
231 
232 Raising exceptions with mocks
233 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
234 
235 A useful attribute is :attr:`~Mock.side_effect`. If you set this to an
236 exception class or instance then the exception will be raised when the mock
237 is called.
238 
239     >>> mock = Mock(side_effect=Exception('Boom!'))
240     >>> mock()
241     Traceback (most recent call last):
242       ...
243     Exception: Boom!
244 
245 
246 Side effect functions and iterables
247 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
248 
249 ``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
251 times, and you want each call to return a different value. When you set
252 ``side_effect`` to an iterable every call to the mock returns the next value
253 from 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 
264 For more advanced use cases, like dynamically varying the return values
265 depending on what the mock is called with, ``side_effect`` can be a function.
266 The function will be called with the same arguments as the mock. Whatever the
267 function 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 
280 Mocking asynchronous iterators
281 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
282 
283 Since Python 3.8, ``AsyncMock`` and ``MagicMock`` have support to mock
284 :ref:`async-iterators` through ``__aiter__``. The :attr:`~Mock.return_value`
285 attribute of ``__aiter__`` can be used to set the return values to be used for
286 iteration.
287 
288     >>> mock = MagicMock()  # AsyncMock also works here
289     >>> mock.__aiter__.return_value = [1, 2, 3]
290     >>> async def main():
291     ...     return [i async for i in mock]
292     ...
293     >>> asyncio.run(main())
294     [1, 2, 3]
295 
296 
297 Mocking asynchronous context manager
298 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
299 
300 Since Python 3.8, ``AsyncMock`` and ``MagicMock`` have support to mock
301 :ref:`async-context-managers` through ``__aenter__`` and ``__aexit__``.
302 By default, ``__aenter__`` and ``__aexit__`` are ``AsyncMock`` instances that
303 return an async function.
304 
305     >>> class AsyncContextManager:
306     ...     async def __aenter__(self):
307     ...         return self
308     ...     async def __aexit__(self, exc_type, exc, tb):
309     ...         pass
310     ...
311     >>> mock_instance = MagicMock(AsyncContextManager())  # AsyncMock also works here
312     >>> async def main():
313     ...     async with mock_instance as result:
314     ...         pass
315     ...
316     >>> asyncio.run(main())
317     >>> mock_instance.__aenter__.assert_awaited_once()
318     >>> mock_instance.__aexit__.assert_awaited_once()
319 
320 
321 Creating a Mock from an Existing Object
322 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
323 
324 One problem with over use of mocking is that it couples your tests to the
325 implementation of your mocks rather than your real code. Suppose you have a
326 class that implements ``some_method``. In a test for another class, you
327 provide a mock of this object that *also* provides ``some_method``. If later
328 you refactor the first class, so that it no longer has ``some_method`` - then
329 your tests will continue to pass even though your code is now broken!
330 
331 :class:`Mock` allows you to provide an object as a specification for the mock,
332 using the *spec* keyword argument. Accessing methods / attributes on the
333 mock that don't exist on your specification object will immediately raise an
334 attribute error. If you change the implementation of your specification, then
335 tests that use that class will start failing immediately without you having to
336 instantiate the class in those tests.
337 
338     >>> mock = Mock(spec=SomeClass)
339     >>> mock.old_method()
340     Traceback (most recent call last):
341        ...
342     AttributeError: object has no attribute 'old_method'
343 
344 Using a specification also enables a smarter matching of calls made to the
345 mock, regardless of whether some parameters were passed as positional or
346 named arguments::
347 
348    >>> def f(a, b, c): pass
349    ...
350    >>> mock = Mock(spec=f)
351    >>> mock(1, 2, 3)
352    <Mock name='mock()' id='140161580456576'>
353    >>> mock.assert_called_with(a=1, b=2, c=3)
354 
355 If you want this smarter matching to also work with method calls on the mock,
356 you can use :ref:`auto-speccing <auto-speccing>`.
357 
358 If you want a stronger form of specification that prevents the setting
359 of arbitrary attributes as well as the getting of them then you can use
360 *spec_set* instead of *spec*.
361 
362 
363 
364 Patch Decorators
365 ----------------
366 
367 .. note::
368 
369    With :func:`patch` it matters that you patch objects in the namespace where
370    they are looked up. This is normally straightforward, but for a quick guide
371    read :ref:`where to patch <where-to-patch>`.
372 
373 
374 A common need in tests is to patch a class attribute or a module attribute,
375 for example patching a builtin or patching a class in a module to test that it
376 is instantiated. Modules and classes are effectively global, so patching on
377 them has to be undone after the test or the patch will persist into other
378 tests and cause hard to diagnose problems.
379 
380 mock provides three convenient decorators for this: :func:`patch`, :func:`patch.object` and
381 :func:`patch.dict`. ``patch`` takes a single string, of the form
382 ``package.module.Class.attribute`` to specify the attribute you are patching. It
383 also optionally takes a value that you want the attribute (or class or
384 whatever) to be replaced with. 'patch.object' takes an object and the name of
385 the attribute you would like patched, plus optionally the value to patch it
386 with.
387 
388 ``patch.object``::
389 
390     >>> original = SomeClass.attribute
391     >>> @patch.object(SomeClass, 'attribute', sentinel.attribute)
392     ... def test():
393     ...     assert SomeClass.attribute == sentinel.attribute
394     ...
395     >>> test()
396     >>> assert SomeClass.attribute == original
397 
398     >>> @patch('package.module.attribute', sentinel.attribute)
399     ... def test():
400     ...     from package.module import attribute
401     ...     assert attribute is sentinel.attribute
402     ...
403     >>> test()
404 
405 If you are patching a module (including :mod:`builtins`) then use :func:`patch`
406 instead of :func:`patch.object`:
407 
408     >>> mock = MagicMock(return_value=sentinel.file_handle)
409     >>> with patch('builtins.open', mock):
410     ...     handle = open('filename', 'r')
411     ...
412     >>> mock.assert_called_with('filename', 'r')
413     >>> assert handle == sentinel.file_handle, "incorrect file handle returned"
414 
415 The module name can be 'dotted', in the form ``package.module`` if needed::
416 
417     >>> @patch('package.module.ClassName.attribute', sentinel.attribute)
418     ... def test():
419     ...     from package.module import ClassName
420     ...     assert ClassName.attribute == sentinel.attribute
421     ...
422     >>> test()
423 
424 A nice pattern is to actually decorate test methods themselves:
425 
426     >>> class MyTest(unittest.TestCase):
427     ...     @patch.object(SomeClass, 'attribute', sentinel.attribute)
428     ...     def test_something(self):
429     ...         self.assertEqual(SomeClass.attribute, sentinel.attribute)
430     ...
431     >>> original = SomeClass.attribute
432     >>> MyTest('test_something').test_something()
433     >>> assert SomeClass.attribute == original
434 
435 If you want to patch with a Mock, you can use :func:`patch` with only one argument
436 (or :func:`patch.object` with two arguments). The mock will be created for you and
437 passed into the test function / method:
438 
439     >>> class MyTest(unittest.TestCase):
440     ...     @patch.object(SomeClass, 'static_method')
441     ...     def test_something(self, mock_method):
442     ...         SomeClass.static_method()
443     ...         mock_method.assert_called_with()
444     ...
445     >>> MyTest('test_something').test_something()
446 
447 You can stack up multiple patch decorators using this pattern::
448 
449     >>> class MyTest(unittest.TestCase):
450     ...     @patch('package.module.ClassName1')
451     ...     @patch('package.module.ClassName2')
452     ...     def test_something(self, MockClass2, MockClass1):
453     ...         self.assertIs(package.module.ClassName1, MockClass1)
454     ...         self.assertIs(package.module.ClassName2, MockClass2)
455     ...
456     >>> MyTest('test_something').test_something()
457 
458 When you nest patch decorators the mocks are passed in to the decorated
459 function in the same order they applied (the normal *Python* order that
460 decorators are applied). This means from the bottom up, so in the example
461 above the mock for ``test_module.ClassName2`` is passed in first.
462 
463 There is also :func:`patch.dict` for setting values in a dictionary just
464 during a scope and restoring the dictionary to its original state when the test
465 ends:
466 
467    >>> foo = {'key': 'value'}
468    >>> original = foo.copy()
469    >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
470    ...     assert foo == {'newkey': 'newvalue'}
471    ...
472    >>> assert foo == original
473 
474 ``patch``, ``patch.object`` and ``patch.dict`` can all be used as context managers.
475 
476 Where you use :func:`patch` to create a mock for you, you can get a reference to the
477 mock using the "as" form of the with statement:
478 
479     >>> class ProductionClass:
480     ...     def method(self):
481     ...         pass
482     ...
483     >>> with patch.object(ProductionClass, 'method') as mock_method:
484     ...     mock_method.return_value = None
485     ...     real = ProductionClass()
486     ...     real.method(1, 2, 3)
487     ...
488     >>> mock_method.assert_called_with(1, 2, 3)
489 
490 
491 As an alternative ``patch``, ``patch.object`` and ``patch.dict`` can be used as
492 class decorators. When used in this way it is the same as applying the
493 decorator individually to every method whose name starts with "test".
494 
495 
496 .. _further-examples:
497 
498 Further Examples
499 ----------------
500 
501 
502 Here are some more examples for some slightly more advanced scenarios.
503 
504 
505 Mocking chained calls
506 ~~~~~~~~~~~~~~~~~~~~~
507 
508 Mocking chained calls is actually straightforward with mock once you
509 understand the :attr:`~Mock.return_value` attribute. When a mock is called for
510 the first time, or you fetch its ``return_value`` before it has been called, a
511 new :class:`Mock` is created.
512 
513 This means that you can see how the object returned from a call to a mocked
514 object has been used by interrogating the ``return_value`` mock:
515 
516     >>> mock = Mock()
517     >>> mock().foo(a=2, b=3)
518     <Mock name='mock().foo()' id='...'>
519     >>> mock.return_value.foo.assert_called_with(a=2, b=3)
520 
521 From here it is a simple step to configure and then make assertions about
522 chained calls. Of course another alternative is writing your code in a more
523 testable way in the first place...
524 
525 So, suppose we have some code that looks a little bit like this:
526 
527     >>> class Something:
528     ...     def __init__(self):
529     ...         self.backend = BackendProvider()
530     ...     def method(self):
531     ...         response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
532     ...         # more code
533 
534 Assuming that ``BackendProvider`` is already well tested, how do we test
535 ``method()``? Specifically, we want to test that the code section ``# more
536 code`` uses the response object in the correct way.
537 
538 As this chain of calls is made from an instance attribute we can monkey patch
539 the ``backend`` attribute on a ``Something`` instance. In this particular case
540 we are only interested in the return value from the final call to
541 ``start_call`` so we don't have much configuration to do. Let's assume the
542 object it returns is 'file-like', so we'll ensure that our response object
543 uses the builtin :func:`open` as its ``spec``.
544 
545 To do this we create a mock instance as our mock backend and create a mock
546 response object for it. To set the response as the return value for that final
547 ``start_call`` we could do this::
548 
549     mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response
550 
551 We can do that in a slightly nicer way using the :meth:`~Mock.configure_mock`
552 method to directly set the return value for us::
553 
554     >>> something = Something()
555     >>> mock_response = Mock(spec=open)
556     >>> mock_backend = Mock()
557     >>> config = {'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response}
558     >>> mock_backend.configure_mock(**config)
559 
560 With these we monkey patch the "mock backend" in place and can make the real
561 call::
562 
563     >>> something.backend = mock_backend
564     >>> something.method()
565 
566 Using :attr:`~Mock.mock_calls` we can check the chained call with a single
567 assert. A chained call is several calls in one line of code, so there will be
568 several entries in ``mock_calls``. We can use :meth:`call.call_list` to create
569 this list of calls for us::
570 
571     >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
572     >>> call_list = chained.call_list()
573     >>> assert mock_backend.mock_calls == call_list
574 
575 
576 Partial mocking
577 ~~~~~~~~~~~~~~~
578 
579 In some tests I wanted to mock out a call to :meth:`datetime.date.today`
580 to return a known date, but I didn't want to prevent the code under test from
581 creating new date objects. Unfortunately :class:`datetime.date` is written in C, and
582 so I couldn't just monkey-patch out the static :meth:`date.today` method.
583 
584 I found a simple way of doing this that involved effectively wrapping the date
585 class with a mock, but passing through calls to the constructor to the real
586 class (and returning real instances).
587 
588 The :func:`patch decorator <patch>` is used here to
589 mock out the ``date`` class in the module under test. The :attr:`side_effect`
590 attribute on the mock date class is then set to a lambda function that returns
591 a real date. When the mock date class is called a real date will be
592 constructed and returned by ``side_effect``. ::
593 
594     >>> from datetime import date
595     >>> with patch('mymodule.date') as mock_date:
596     ...     mock_date.today.return_value = date(2010, 10, 8)
597     ...     mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
598     ...
599     ...     assert mymodule.date.today() == date(2010, 10, 8)
600     ...     assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
601 
602 Note that we don't patch :class:`datetime.date` globally, we patch ``date`` in the
603 module that *uses* it. See :ref:`where to patch <where-to-patch>`.
604 
605 When ``date.today()`` is called a known date is returned, but calls to the
606 ``date(...)`` constructor still return normal dates. Without this you can find
607 yourself having to calculate an expected result using exactly the same
608 algorithm as the code under test, which is a classic testing anti-pattern.
609 
610 Calls to the date constructor are recorded in the ``mock_date`` attributes
611 (``call_count`` and friends) which may also be useful for your tests.
612 
613 An alternative way of dealing with mocking dates, or other builtin classes,
614 is discussed in `this blog entry
615 <https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/>`_.
616 
617 
618 Mocking a Generator Method
619 ~~~~~~~~~~~~~~~~~~~~~~~~~~
620 
621 A Python generator is a function or method that uses the :keyword:`yield` statement
622 to return a series of values when iterated over [#]_.
623 
624 A generator method / function is called to return the generator object. It is
625 the generator object that is then iterated over. The protocol method for
626 iteration is :meth:`~container.__iter__`, so we can
627 mock this using a :class:`MagicMock`.
628 
629 Here's an example class with an "iter" method implemented as a generator:
630 
631     >>> class Foo:
632     ...     def iter(self):
633     ...         for i in [1, 2, 3]:
634     ...             yield i
635     ...
636     >>> foo = Foo()
637     >>> list(foo.iter())
638     [1, 2, 3]
639 
640 
641 How would we mock this class, and in particular its "iter" method?
642 
643 To configure the values returned from the iteration (implicit in the call to
644 :class:`list`), we need to configure the object returned by the call to ``foo.iter()``.
645 
646     >>> mock_foo = MagicMock()
647     >>> mock_foo.iter.return_value = iter([1, 2, 3])
648     >>> list(mock_foo.iter())
649     [1, 2, 3]
650 
651 .. [#] There are also generator expressions and more `advanced uses
652     <http://www.dabeaz.com/coroutines/index.html>`_ of generators, but we aren't
653     concerned about them here. A very good introduction to generators and how
654     powerful they are is: `Generator Tricks for Systems Programmers
655     <http://www.dabeaz.com/generators/>`_.
656 
657 
658 Applying the same patch to every test method
659 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
660 
661 If you want several patches in place for multiple test methods the obvious way
662 is to apply the patch decorators to every method. This can feel like unnecessary
663 repetition. For Python 2.6 or more recent you can use :func:`patch` (in all its
664 various forms) as a class decorator. This applies the patches to all test
665 methods on the class. A test method is identified by methods whose names start
666 with ``test``::
667 
668     >>> @patch('mymodule.SomeClass')
669     ... class MyTest(unittest.TestCase):
670     ...
671     ...     def test_one(self, MockSomeClass):
672     ...         self.assertIs(mymodule.SomeClass, MockSomeClass)
673     ...
674     ...     def test_two(self, MockSomeClass):
675     ...         self.assertIs(mymodule.SomeClass, MockSomeClass)
676     ...
677     ...     def not_a_test(self):
678     ...         return 'something'
679     ...
680     >>> MyTest('test_one').test_one()
681     >>> MyTest('test_two').test_two()
682     >>> MyTest('test_two').not_a_test()
683     'something'
684 
685 An alternative way of managing patches is to use the :ref:`start-and-stop`.
686 These allow you to move the patching into your ``setUp`` and ``tearDown`` methods.
687 ::
688 
689     >>> class MyTest(unittest.TestCase):
690     ...     def setUp(self):
691     ...         self.patcher = patch('mymodule.foo')
692     ...         self.mock_foo = self.patcher.start()
693     ...
694     ...     def test_foo(self):
695     ...         self.assertIs(mymodule.foo, self.mock_foo)
696     ...
697     ...     def tearDown(self):
698     ...         self.patcher.stop()
699     ...
700     >>> MyTest('test_foo').run()
701 
702 If you use this technique you must ensure that the patching is "undone" by
703 calling ``stop``. This can be fiddlier than you might think, because if an
704 exception is raised in the setUp then tearDown is not called.
705 :meth:`unittest.TestCase.addCleanup` makes this easier::
706 
707     >>> class MyTest(unittest.TestCase):
708     ...     def setUp(self):
709     ...         patcher = patch('mymodule.foo')
710     ...         self.addCleanup(patcher.stop)
711     ...         self.mock_foo = patcher.start()
712     ...
713     ...     def test_foo(self):
714     ...         self.assertIs(mymodule.foo, self.mock_foo)
715     ...
716     >>> MyTest('test_foo').run()
717 
718 
719 Mocking Unbound Methods
720 ~~~~~~~~~~~~~~~~~~~~~~~
721 
722 Whilst writing tests today I needed to patch an *unbound method* (patching the
723 method on the class rather than on the instance). I needed self to be passed
724 in as the first argument because I want to make asserts about which objects
725 were calling this particular method. The issue is that you can't patch with a
726 mock for this, because if you replace an unbound method with a mock it doesn't
727 become a bound method when fetched from the instance, and so it doesn't get
728 self passed in. The workaround is to patch the unbound method with a real
729 function instead. The :func:`patch` decorator makes it so simple to
730 patch out methods with a mock that having to create a real function becomes a
731 nuisance.
732 
733 If you pass ``autospec=True`` to patch then it does the patching with a
734 *real* function object. This function object has the same signature as the one
735 it is replacing, but delegates to a mock under the hood. You still get your
736 mock auto-created in exactly the same way as before. What it means though, is
737 that if you use it to patch out an unbound method on a class the mocked
738 function will be turned into a bound method if it is fetched from an instance.
739 It will have ``self`` passed in as the first argument, which is exactly what I
740 wanted:
741 
742     >>> class Foo:
743     ...   def foo(self):
744     ...     pass
745     ...
746     >>> with patch.object(Foo, 'foo', autospec=True) as mock_foo:
747     ...   mock_foo.return_value = 'foo'
748     ...   foo = Foo()
749     ...   foo.foo()
750     ...
751     'foo'
752     >>> mock_foo.assert_called_once_with(foo)
753 
754 If we don't use ``autospec=True`` then the unbound method is patched out
755 with a Mock instance instead, and isn't called with ``self``.
756 
757 
758 Checking multiple calls with mock
759 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
760 
761 mock has a nice API for making assertions about how your mock objects are used.
762 
763     >>> mock = Mock()
764     >>> mock.foo_bar.return_value = None
765     >>> mock.foo_bar('baz', spam='eggs')
766     >>> mock.foo_bar.assert_called_with('baz', spam='eggs')
767 
768 If your mock is only being called once you can use the
769 :meth:`assert_called_once_with` method that also asserts that the
770 :attr:`call_count` is one.
771 
772     >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
773     >>> mock.foo_bar()
774     >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
775     Traceback (most recent call last):
776         ...
777     AssertionError: Expected to be called once. Called 2 times.
778 
779 Both ``assert_called_with`` and ``assert_called_once_with`` make assertions about
780 the *most recent* call. If your mock is going to be called several times, and
781 you want to make assertions about *all* those calls you can use
782 :attr:`~Mock.call_args_list`:
783 
784     >>> mock = Mock(return_value=None)
785     >>> mock(1, 2, 3)
786     >>> mock(4, 5, 6)
787     >>> mock()
788     >>> mock.call_args_list
789     [call(1, 2, 3), call(4, 5, 6), call()]
790 
791 The :data:`call` helper makes it easy to make assertions about these calls. You
792 can build up a list of expected calls and compare it to ``call_args_list``. This
793 looks remarkably similar to the repr of the ``call_args_list``:
794 
795     >>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
796     >>> mock.call_args_list == expected
797     True
798 
799 
800 Coping with mutable arguments
801 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
802 
803 Another situation is rare, but can bite you, is when your mock is called with
804 mutable arguments. ``call_args`` and ``call_args_list`` store *references* to the
805 arguments. If the arguments are mutated by the code under test then you can no
806 longer make assertions about what the values were when the mock was called.
807 
808 Here's some example code that shows the problem. Imagine the following functions
809 defined in 'mymodule'::
810 
811     def frob(val):
812         pass
813 
814     def grob(val):
815         "First frob and then clear val"
816         frob(val)
817         val.clear()
818 
819 When we try to test that ``grob`` calls ``frob`` with the correct argument look
820 what happens::
821 
822     >>> with patch('mymodule.frob') as mock_frob:
823     ...     val = {6}
824     ...     mymodule.grob(val)
825     ...
826     >>> val
827     set()
828     >>> mock_frob.assert_called_with({6})
829     Traceback (most recent call last):
830         ...
831     AssertionError: Expected: (({6},), {})
832     Called with: ((set(),), {})
833 
834 One possibility would be for mock to copy the arguments you pass in. This
835 could then cause problems if you do assertions that rely on object identity
836 for equality.
837 
838 Here's one solution that uses the :attr:`side_effect`
839 functionality. If you provide a ``side_effect`` function for a mock then
840 ``side_effect`` will be called with the same args as the mock. This gives us an
841 opportunity to copy the arguments and store them for later assertions. In this
842 example I'm using *another* mock to store the arguments so that I can use the
843 mock methods for doing the assertion. Again a helper function sets this up for
844 me. ::
845 
846     >>> from copy import deepcopy
847     >>> from unittest.mock import Mock, patch, DEFAULT
848     >>> def copy_call_args(mock):
849     ...     new_mock = Mock()
850     ...     def side_effect(*args, **kwargs):
851     ...         args = deepcopy(args)
852     ...         kwargs = deepcopy(kwargs)
853     ...         new_mock(*args, **kwargs)
854     ...         return DEFAULT
855     ...     mock.side_effect = side_effect
856     ...     return new_mock
857     ...
858     >>> with patch('mymodule.frob') as mock_frob:
859     ...     new_mock = copy_call_args(mock_frob)
860     ...     val = {6}
861     ...     mymodule.grob(val)
862     ...
863     >>> new_mock.assert_called_with({6})
864     >>> new_mock.call_args
865     call({6})
866 
867 ``copy_call_args`` is called with the mock that will be called. It returns a new
868 mock that we do the assertion on. The ``side_effect`` function makes a copy of
869 the args and calls our ``new_mock`` with the copy.
870 
871 .. note::
872 
873     If your mock is only going to be used once there is an easier way of
874     checking arguments at the point they are called. You can simply do the
875     checking inside a ``side_effect`` function.
876 
877         >>> def side_effect(arg):
878         ...     assert arg == {6}
879         ...
880         >>> mock = Mock(side_effect=side_effect)
881         >>> mock({6})
882         >>> mock(set())
883         Traceback (most recent call last):
884             ...
885         AssertionError
886 
887 An alternative approach is to create a subclass of :class:`Mock` or
888 :class:`MagicMock` that copies (using :func:`copy.deepcopy`) the arguments.
889 Here's an example implementation:
890 
891     >>> from copy import deepcopy
892     >>> class CopyingMock(MagicMock):
893     ...     def __call__(self, /, *args, **kwargs):
894     ...         args = deepcopy(args)
895     ...         kwargs = deepcopy(kwargs)
896     ...         return super().__call__(*args, **kwargs)
897     ...
898     >>> c = CopyingMock(return_value=None)
899     >>> arg = set()
900     >>> c(arg)
901     >>> arg.add(1)
902     >>> c.assert_called_with(set())
903     >>> c.assert_called_with(arg)
904     Traceback (most recent call last):
905         ...
906     AssertionError: Expected call: mock({1})
907     Actual call: mock(set())
908     >>> c.foo
909     <CopyingMock name='mock.foo' id='...'>
910 
911 When you subclass ``Mock`` or ``MagicMock`` all dynamically created attributes,
912 and the ``return_value`` will use your subclass automatically. That means all
913 children of a ``CopyingMock`` will also have the type ``CopyingMock``.
914 
915 
916 Nesting Patches
917 ~~~~~~~~~~~~~~~
918 
919 Using patch as a context manager is nice, but if you do multiple patches you
920 can end up with nested with statements indenting further and further to the
921 right::
922 
923     >>> class MyTest(unittest.TestCase):
924     ...
925     ...     def test_foo(self):
926     ...         with patch('mymodule.Foo') as mock_foo:
927     ...             with patch('mymodule.Bar') as mock_bar:
928     ...                 with patch('mymodule.Spam') as mock_spam:
929     ...                     assert mymodule.Foo is mock_foo
930     ...                     assert mymodule.Bar is mock_bar
931     ...                     assert mymodule.Spam is mock_spam
932     ...
933     >>> original = mymodule.Foo
934     >>> MyTest('test_foo').test_foo()
935     >>> assert mymodule.Foo is original
936 
937 With unittest ``cleanup`` functions and the :ref:`start-and-stop` we can
938 achieve the same effect without the nested indentation. A simple helper
939 method, ``create_patch``, puts the patch in place and returns the created mock
940 for us::
941 
942     >>> class MyTest(unittest.TestCase):
943     ...
944     ...     def create_patch(self, name):
945     ...         patcher = patch(name)
946     ...         thing = patcher.start()
947     ...         self.addCleanup(patcher.stop)
948     ...         return thing
949     ...
950     ...     def test_foo(self):
951     ...         mock_foo = self.create_patch('mymodule.Foo')
952     ...         mock_bar = self.create_patch('mymodule.Bar')
953     ...         mock_spam = self.create_patch('mymodule.Spam')
954     ...
955     ...         assert mymodule.Foo is mock_foo
956     ...         assert mymodule.Bar is mock_bar
957     ...         assert mymodule.Spam is mock_spam
958     ...
959     >>> original = mymodule.Foo
960     >>> MyTest('test_foo').run()
961     >>> assert mymodule.Foo is original
962 
963 
964 Mocking a dictionary with MagicMock
965 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
966 
967 You may want to mock a dictionary, or other container object, recording all
968 access to it whilst having it still behave like a dictionary.
969 
970 We can do this with :class:`MagicMock`, which will behave like a dictionary,
971 and using :data:`~Mock.side_effect` to delegate dictionary access to a real
972 underlying dictionary that is under our control.
973 
974 When the :meth:`__getitem__` and :meth:`__setitem__` methods of our ``MagicMock`` are called
975 (normal dictionary access) then ``side_effect`` is called with the key (and in
976 the case of ``__setitem__`` the value too). We can also control what is returned.
977 
978 After the ``MagicMock`` has been used we can use attributes like
979 :data:`~Mock.call_args_list` to assert about how the dictionary was used:
980 
981     >>> my_dict = {'a': 1, 'b': 2, 'c': 3}
982     >>> def getitem(name):
983     ...      return my_dict[name]
984     ...
985     >>> def setitem(name, val):
986     ...     my_dict[name] = val
987     ...
988     >>> mock = MagicMock()
989     >>> mock.__getitem__.side_effect = getitem
990     >>> mock.__setitem__.side_effect = setitem
991 
992 .. note::
993 
994     An alternative to using ``MagicMock`` is to use ``Mock`` and *only* provide
995     the magic methods you specifically want:
996 
997         >>> mock = Mock()
998         >>> mock.__getitem__ = Mock(side_effect=getitem)
999         >>> mock.__setitem__ = Mock(side_effect=setitem)
1000 
1001     A *third* option is to use ``MagicMock`` but passing in ``dict`` as the *spec*
1002     (or *spec_set*) argument so that the ``MagicMock`` created only has
1003     dictionary magic methods available:
1004 
1005         >>> mock = MagicMock(spec_set=dict)
1006         >>> mock.__getitem__.side_effect = getitem
1007         >>> mock.__setitem__.side_effect = setitem
1008 
1009 With these side effect functions in place, the ``mock`` will behave like a normal
1010 dictionary but recording the access. It even raises a :exc:`KeyError` if you try
1011 to access a key that doesn't exist.
1012 
1013     >>> mock['a']
1014     1
1015     >>> mock['c']
1016     3
1017     >>> mock['d']
1018     Traceback (most recent call last):
1019         ...
1020     KeyError: 'd'
1021     >>> mock['b'] = 'fish'
1022     >>> mock['d'] = 'eggs'
1023     >>> mock['b']
1024     'fish'
1025     >>> mock['d']
1026     'eggs'
1027 
1028 After it has been used you can make assertions about the access using the normal
1029 mock methods and attributes:
1030 
1031     >>> mock.__getitem__.call_args_list
1032     [call('a'), call('c'), call('d'), call('b'), call('d')]
1033     >>> mock.__setitem__.call_args_list
1034     [call('b', 'fish'), call('d', 'eggs')]
1035     >>> my_dict
1036     {'a': 1, 'b': 'fish', 'c': 3, 'd': 'eggs'}
1037 
1038 
1039 Mock subclasses and their attributes
1040 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1041 
1042 There are various reasons why you might want to subclass :class:`Mock`. One
1043 reason might be to add helper methods. Here's a silly example:
1044 
1045     >>> class MyMock(MagicMock):
1046     ...     def has_been_called(self):
1047     ...         return self.called
1048     ...
1049     >>> mymock = MyMock(return_value=None)
1050     >>> mymock
1051     <MyMock id='...'>
1052     >>> mymock.has_been_called()
1053     False
1054     >>> mymock()
1055     >>> mymock.has_been_called()
1056     True
1057 
1058 The standard behaviour for ``Mock`` instances is that attributes and the return
1059 value mocks are of the same type as the mock they are accessed on. This ensures
1060 that ``Mock`` attributes are ``Mocks`` and ``MagicMock`` attributes are ``MagicMocks``
1061 [#]_. So if you're subclassing to add helper methods then they'll also be
1062 available on the attributes and return value mock of instances of your
1063 subclass.
1064 
1065     >>> mymock.foo
1066     <MyMock name='mock.foo' id='...'>
1067     >>> mymock.foo.has_been_called()
1068     False
1069     >>> mymock.foo()
1070     <MyMock name='mock.foo()' id='...'>
1071     >>> mymock.foo.has_been_called()
1072     True
1073 
1074 Sometimes this is inconvenient. For example, `one user
1075 <https://code.google.com/archive/p/mock/issues/105>`_ is subclassing mock to
1076 created a `Twisted adaptor
1077 <https://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html>`_.
1078 Having this applied to attributes too actually causes errors.
1079 
1080 ``Mock`` (in all its flavours) uses a method called ``_get_child_mock`` to create
1081 these "sub-mocks" for attributes and return values. You can prevent your
1082 subclass being used for attributes by overriding this method. The signature is
1083 that it takes arbitrary keyword arguments (``**kwargs``) which are then passed
1084 onto the mock constructor:
1085 
1086     >>> class Subclass(MagicMock):
1087     ...     def _get_child_mock(self, /, **kwargs):
1088     ...         return MagicMock(**kwargs)
1089     ...
1090     >>> mymock = Subclass()
1091     >>> mymock.foo
1092     <MagicMock name='mock.foo' id='...'>
1093     >>> assert isinstance(mymock, Subclass)
1094     >>> assert not isinstance(mymock.foo, Subclass)
1095     >>> assert not isinstance(mymock(), Subclass)
1096 
1097 .. [#] An exception to this rule are the non-callable mocks. Attributes use the
1098     callable variant because otherwise non-callable mocks couldn't have callable
1099     methods.
1100 
1101 
1102 Mocking imports with patch.dict
1103 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1104 
1105 One situation where mocking can be hard is where you have a local import inside
1106 a function. These are harder to mock because they aren't using an object from
1107 the module namespace that we can patch out.
1108 
1109 Generally local imports are to be avoided. They are sometimes done to prevent
1110 circular dependencies, for which there is *usually* a much better way to solve
1111 the problem (refactor the code) or to prevent "up front costs" by delaying the
1112 import. This can also be solved in better ways than an unconditional local
1113 import (store the module as a class or module attribute and only do the import
1114 on first use).
1115 
1116 That aside there is a way to use ``mock`` to affect the results of an import.
1117 Importing fetches an *object* from the :data:`sys.modules` dictionary. Note that it
1118 fetches an *object*, which need not be a module. Importing a module for the
1119 first time results in a module object being put in `sys.modules`, so usually
1120 when you import something you get a module back. This need not be the case
1121 however.
1122 
1123 This means you can use :func:`patch.dict` to *temporarily* put a mock in place
1124 in :data:`sys.modules`. Any imports whilst this patch is active will fetch the mock.
1125 When the patch is complete (the decorated function exits, the with statement
1126 body is complete or ``patcher.stop()`` is called) then whatever was there
1127 previously will be restored safely.
1128 
1129 Here's an example that mocks out the 'fooble' module.
1130 
1131     >>> import sys
1132     >>> mock = Mock()
1133     >>> with patch.dict('sys.modules', {'fooble': mock}):
1134     ...    import fooble
1135     ...    fooble.blob()
1136     ...
1137     <Mock name='mock.blob()' id='...'>
1138     >>> assert 'fooble' not in sys.modules
1139     >>> mock.blob.assert_called_once_with()
1140 
1141 As you can see the ``import fooble`` succeeds, but on exit there is no 'fooble'
1142 left in :data:`sys.modules`.
1143 
1144 This also works for the ``from module import name`` form:
1145 
1146     >>> mock = Mock()
1147     >>> with patch.dict('sys.modules', {'fooble': mock}):
1148     ...    from fooble import blob
1149     ...    blob.blip()
1150     ...
1151     <Mock name='mock.blob.blip()' id='...'>
1152     >>> mock.blob.blip.assert_called_once_with()
1153 
1154 With slightly more work you can also mock package imports:
1155 
1156     >>> mock = Mock()
1157     >>> modules = {'package': mock, 'package.module': mock.module}
1158     >>> with patch.dict('sys.modules', modules):
1159     ...    from package.module import fooble
1160     ...    fooble()
1161     ...
1162     <Mock name='mock.module.fooble()' id='...'>
1163     >>> mock.module.fooble.assert_called_once_with()
1164 
1165 
1166 Tracking order of calls and less verbose call assertions
1167 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1168 
1169 The :class:`Mock` class allows you to track the *order* of method calls on
1170 your mock objects through the :attr:`~Mock.method_calls` attribute. This
1171 doesn't allow you to track the order of calls between separate mock objects,
1172 however we can use :attr:`~Mock.mock_calls` to achieve the same effect.
1173 
1174 Because mocks track calls to child mocks in ``mock_calls``, and accessing an
1175 arbitrary attribute of a mock creates a child mock, we can create our separate
1176 mocks from a parent one. Calls to those child mock will then all be recorded,
1177 in order, in the ``mock_calls`` of the parent:
1178 
1179     >>> manager = Mock()
1180     >>> mock_foo = manager.foo
1181     >>> mock_bar = manager.bar
1182 
1183     >>> mock_foo.something()
1184     <Mock name='mock.foo.something()' id='...'>
1185     >>> mock_bar.other.thing()
1186     <Mock name='mock.bar.other.thing()' id='...'>
1187 
1188     >>> manager.mock_calls
1189     [call.foo.something(), call.bar.other.thing()]
1190 
1191 We can then assert about the calls, including the order, by comparing with
1192 the ``mock_calls`` attribute on the manager mock:
1193 
1194     >>> expected_calls = [call.foo.something(), call.bar.other.thing()]
1195     >>> manager.mock_calls == expected_calls
1196     True
1197 
1198 If ``patch`` is creating, and putting in place, your mocks then you can attach
1199 them to a manager mock using the :meth:`~Mock.attach_mock` method. After
1200 attaching calls will be recorded in ``mock_calls`` of the manager. ::
1201 
1202     >>> manager = MagicMock()
1203     >>> with patch('mymodule.Class1') as MockClass1:
1204     ...     with patch('mymodule.Class2') as MockClass2:
1205     ...         manager.attach_mock(MockClass1, 'MockClass1')
1206     ...         manager.attach_mock(MockClass2, 'MockClass2')
1207     ...         MockClass1().foo()
1208     ...         MockClass2().bar()
1209     <MagicMock name='mock.MockClass1().foo()' id='...'>
1210     <MagicMock name='mock.MockClass2().bar()' id='...'>
1211     >>> manager.mock_calls
1212     [call.MockClass1(),
1213     call.MockClass1().foo(),
1214     call.MockClass2(),
1215     call.MockClass2().bar()]
1216 
1217 If many calls have been made, but you're only interested in a particular
1218 sequence of them then an alternative is to use the
1219 :meth:`~Mock.assert_has_calls` method. This takes a list of calls (constructed
1220 with the :data:`call` object). If that sequence of calls are in
1221 :attr:`~Mock.mock_calls` then the assert succeeds.
1222 
1223     >>> m = MagicMock()
1224     >>> m().foo().bar().baz()
1225     <MagicMock name='mock().foo().bar().baz()' id='...'>
1226     >>> m.one().two().three()
1227     <MagicMock name='mock.one().two().three()' id='...'>
1228     >>> calls = call.one().two().three().call_list()
1229     >>> m.assert_has_calls(calls)
1230 
1231 Even though the chained call ``m.one().two().three()`` aren't the only calls that
1232 have been made to the mock, the assert still succeeds.
1233 
1234 Sometimes a mock may have several calls made to it, and you are only interested
1235 in asserting about *some* of those calls. You may not even care about the
1236 order. In this case you can pass ``any_order=True`` to ``assert_has_calls``:
1237 
1238     >>> m = MagicMock()
1239     >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
1240     (...)
1241     >>> calls = [call.fifty('50'), call(1), call.seven(7)]
1242     >>> m.assert_has_calls(calls, any_order=True)
1243 
1244 
1245 More complex argument matching
1246 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1247 
1248 Using the same basic concept as :data:`ANY` we can implement matchers to do more
1249 complex assertions on objects used as arguments to mocks.
1250 
1251 Suppose we expect some object to be passed to a mock that by default
1252 compares equal based on object identity (which is the Python default for user
1253 defined classes). To use :meth:`~Mock.assert_called_with` we would need to pass
1254 in the exact same object. If we are only interested in some of the attributes
1255 of this object then we can create a matcher that will check these attributes
1256 for us.
1257 
1258 You can see in this example how a 'standard' call to ``assert_called_with`` isn't
1259 sufficient:
1260 
1261     >>> class Foo:
1262     ...     def __init__(self, a, b):
1263     ...         self.a, self.b = a, b
1264     ...
1265     >>> mock = Mock(return_value=None)
1266     >>> mock(Foo(1, 2))
1267     >>> mock.assert_called_with(Foo(1, 2))
1268     Traceback (most recent call last):
1269         ...
1270     AssertionError: Expected: call(<__main__.Foo object at 0x...>)
1271     Actual call: call(<__main__.Foo object at 0x...>)
1272 
1273 A comparison function for our ``Foo`` class might look something like this:
1274 
1275     >>> def compare(self, other):
1276     ...     if not type(self) == type(other):
1277     ...         return False
1278     ...     if self.a != other.a:
1279     ...         return False
1280     ...     if self.b != other.b:
1281     ...         return False
1282     ...     return True
1283     ...
1284 
1285 And a matcher object that can use comparison functions like this for its
1286 equality operation would look something like this:
1287 
1288     >>> class Matcher:
1289     ...     def __init__(self, compare, some_obj):
1290     ...         self.compare = compare
1291     ...         self.some_obj = some_obj
1292     ...     def __eq__(self, other):
1293     ...         return self.compare(self.some_obj, other)
1294     ...
1295 
1296 Putting all this together:
1297 
1298     >>> match_foo = Matcher(compare, Foo(1, 2))
1299     >>> mock.assert_called_with(match_foo)
1300 
1301 The ``Matcher`` is instantiated with our compare function and the ``Foo`` object
1302 we want to compare against. In ``assert_called_with`` the ``Matcher`` equality
1303 method will be called, which compares the object the mock was called with
1304 against the one we created our matcher with. If they match then
1305 ``assert_called_with`` passes, and if they don't an :exc:`AssertionError` is raised:
1306 
1307     >>> match_wrong = Matcher(compare, Foo(3, 4))
1308     >>> mock.assert_called_with(match_wrong)
1309     Traceback (most recent call last):
1310         ...
1311     AssertionError: Expected: ((<Matcher object at 0x...>,), {})
1312     Called with: ((<Foo object at 0x...>,), {})
1313 
1314 With a bit of tweaking you could have the comparison function raise the
1315 :exc:`AssertionError` directly and provide a more useful failure message.
1316 
1317 As of version 1.5, the Python testing library `PyHamcrest
1318 <https://pyhamcrest.readthedocs.io/>`_ provides similar functionality,
1319 that may be useful here, in the form of its equality matcher
1320 (`hamcrest.library.integration.match_equality
1321 <https://pyhamcrest.readthedocs.io/en/release-1.8/integration/#module-hamcrest.library.integration.match_equality>`_).
1322