blob: 71b73860adb7e0dcbfa99de861fbb45395077a88 [file] [log] [blame]
Michael Foord944e02d2012-03-25 23:12:55 +01001:mod:`unittest.mock` --- mock object library
2============================================
3
4.. module:: unittest.mock
5 :synopsis: Mock object library.
6.. moduleauthor:: Michael Foord <michael@python.org>
7.. currentmodule:: unittest.mock
8
9.. versionadded:: 3.3
10
11:mod:`unittest.mock` is a library for testing in Python. It allows you to
12replace parts of your system under test with mock objects and make assertions
13about how they have been used.
14
15`unittest.mock` provides a core :class:`Mock` class removing the need to
16create a host of stubs throughout your test suite. After performing an
17action, you can make assertions about which methods / attributes were used
18and arguments they were called with. You can also specify return values and
19set needed attributes in the normal way.
20
21Additionally, mock provides a :func:`patch` decorator that handles patching
22module and class level attributes within the scope of a test, along with
23:const:`sentinel` for creating unique objects. See the `quick guide`_ for
24some examples of how to use :class:`Mock`, :class:`MagicMock` and
25:func:`patch`.
26
27Mock is very easy to use and is designed for use with :mod:`unittest`. Mock
28is based on the 'action -> assertion' pattern instead of `'record -> replay'`
29used by many mocking frameworks.
30
31There is a backport of `unittest.mock` for earlier versions of Python,
32available as `mock on PyPI <http://pypi.python.org/pypi/mock>`_.
33
34**Source code:** :source:`Lib/unittest/mock.py`
35
36
37Quick Guide
38-----------
39
40:class:`Mock` and :class:`MagicMock` objects create all attributes and
41methods as you access them and store details of how they have been used. You
42can configure them, to specify return values or limit what attributes are
43available, and then make assertions about how they have been used:
44
45 >>> from unittest.mock import MagicMock
46 >>> thing = ProductionClass()
47 >>> thing.method = MagicMock(return_value=3)
48 >>> thing.method(3, 4, 5, key='value')
49 3
50 >>> thing.method.assert_called_with(3, 4, 5, key='value')
51
52:attr:`side_effect` allows you to perform side effects, including raising an
53exception when a mock is called:
54
55 >>> mock = Mock(side_effect=KeyError('foo'))
56 >>> mock()
57 Traceback (most recent call last):
58 ...
59 KeyError: 'foo'
60
61 >>> values = {'a': 1, 'b': 2, 'c': 3}
62 >>> def side_effect(arg):
63 ... return values[arg]
64 ...
65 >>> mock.side_effect = side_effect
66 >>> mock('a'), mock('b'), mock('c')
67 (1, 2, 3)
68 >>> mock.side_effect = [5, 4, 3, 2, 1]
69 >>> mock(), mock(), mock()
70 (5, 4, 3)
71
72Mock has many other ways you can configure it and control its behaviour. For
73example the `spec` argument configures the mock to take its specification
74from another object. Attempting to access attributes or methods on the mock
75that don't exist on the spec will fail with an `AttributeError`.
76
77The :func:`patch` decorator / context manager makes it easy to mock classes or
78objects in a module under test. The object you specify will be replaced with a
79mock (or other object) during the test and restored when the test ends:
80
81 >>> from unittest.mock import patch
82 >>> @patch('module.ClassName2')
83 ... @patch('module.ClassName1')
84 ... def test(MockClass1, MockClass2):
85 ... module.ClassName1()
86 ... module.ClassName2()
87
88 ... assert MockClass1 is module.ClassName1
89 ... assert MockClass2 is module.ClassName2
90 ... assert MockClass1.called
91 ... assert MockClass2.called
92 ...
93 >>> test()
94
95.. note::
96
97 When you nest patch decorators the mocks are passed in to the decorated
98 function in the same order they applied (the normal *python* order that
99 decorators are applied). This means from the bottom up, so in the example
100 above the mock for `module.ClassName1` is passed in first.
101
102 With `patch` it matters that you patch objects in the namespace where they
103 are looked up. This is normally straightforward, but for a quick guide
104 read :ref:`where to patch <where-to-patch>`.
105
106As well as a decorator `patch` can be used as a context manager in a with
107statement:
108
109 >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
110 ... thing = ProductionClass()
111 ... thing.method(1, 2, 3)
112 ...
113 >>> mock_method.assert_called_once_with(1, 2, 3)
114
115
116There is also :func:`patch.dict` for setting values in a dictionary just
117during a scope and restoring the dictionary to its original state when the test
118ends:
119
120 >>> foo = {'key': 'value'}
121 >>> original = foo.copy()
122 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
123 ... assert foo == {'newkey': 'newvalue'}
124 ...
125 >>> assert foo == original
126
127Mock supports the mocking of Python :ref:`magic methods <magic-methods>`. The
128easiest way of using magic methods is with the :class:`MagicMock` class. It
129allows you to do things like:
130
131 >>> mock = MagicMock()
132 >>> mock.__str__.return_value = 'foobarbaz'
133 >>> str(mock)
134 'foobarbaz'
135 >>> mock.__str__.assert_called_with()
136
137Mock allows you to assign functions (or other Mock instances) to magic methods
138and they will be called appropriately. The `MagicMock` class is just a Mock
139variant that has all of the magic methods pre-created for you (well, all the
140useful ones anyway).
141
142The following is an example of using magic methods with the ordinary Mock
143class:
144
145 >>> mock = Mock()
146 >>> mock.__str__ = Mock(return_value='wheeeeee')
147 >>> str(mock)
148 'wheeeeee'
149
150For ensuring that the mock objects in your tests have the same api as the
151objects they are replacing, you can use :ref:`auto-speccing <auto-speccing>`.
152Auto-speccing can be done through the `autospec` argument to patch, or the
153:func:`create_autospec` function. Auto-speccing creates mock objects that
154have the same attributes and methods as the objects they are replacing, and
155any functions and methods (including constructors) have the same call
156signature as the real object.
157
158This ensures that your mocks will fail in the same way as your production
159code if they are used incorrectly:
160
161 >>> from unittest.mock import create_autospec
162 >>> def function(a, b, c):
163 ... pass
164 ...
165 >>> mock_function = create_autospec(function, return_value='fishy')
166 >>> mock_function(1, 2, 3)
167 'fishy'
168 >>> mock_function.assert_called_once_with(1, 2, 3)
169 >>> mock_function('wrong arguments')
170 Traceback (most recent call last):
171 ...
172 TypeError: <lambda>() takes exactly 3 arguments (1 given)
173
174`create_autospec` can also be used on classes, where it copies the signature of
175the `__init__` method, and on callable objects where it copies the signature of
176the `__call__` method.
177
178
179
180The Mock Class
181--------------
182
183
184`Mock` is a flexible mock object intended to replace the use of stubs and
185test doubles throughout your code. Mocks are callable and create attributes as
186new mocks when you access them [#]_. Accessing the same attribute will always
187return the same mock. Mocks record how you use them, allowing you to make
188assertions about what your code has done to them.
189
190:class:`MagicMock` is a subclass of `Mock` with all the magic methods
191pre-created and ready to use. There are also non-callable variants, useful
192when you are mocking out objects that aren't callable:
193:class:`NonCallableMock` and :class:`NonCallableMagicMock`
194
195The :func:`patch` decorators makes it easy to temporarily replace classes
196in a particular module with a `Mock` object. By default `patch` will create
197a `MagicMock` for you. You can specify an alternative class of `Mock` using
198the `new_callable` argument to `patch`.
199
200
201.. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, **kwargs)
202
203 Create a new `Mock` object. `Mock` takes several optional arguments
204 that specify the behaviour of the Mock object:
205
206 * `spec`: This can be either a list of strings or an existing object (a
207 class or instance) that acts as the specification for the mock object. If
208 you pass in an object then a list of strings is formed by calling dir on
209 the object (excluding unsupported magic attributes and methods).
210 Accessing any attribute not in this list will raise an `AttributeError`.
211
212 If `spec` is an object (rather than a list of strings) then
213 :attr:`__class__` returns the class of the spec object. This allows mocks
214 to pass `isinstance` tests.
215
216 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
217 or get an attribute on the mock that isn't on the object passed as
218 `spec_set` will raise an `AttributeError`.
219
220 * `side_effect`: A function to be called whenever the Mock is called. See
221 the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or
222 dynamically changing return values. The function is called with the same
223 arguments as the mock, and unless it returns :data:`DEFAULT`, the return
224 value of this function is used as the return value.
225
226 Alternatively `side_effect` can be an exception class or instance. In
227 this case the exception will be raised when the mock is called.
228
229 If `side_effect` is an iterable then each call to the mock will return
230 the next value from the iterable.
231
232 A `side_effect` can be cleared by setting it to `None`.
233
234 * `return_value`: The value returned when the mock is called. By default
235 this is a new Mock (created on first access). See the
236 :attr:`return_value` attribute.
237
238 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
239 calling the Mock will pass the call through to the wrapped object
240 (returning the real result and ignoring `return_value`). Attribute access
241 on the mock will return a Mock object that wraps the corresponding
242 attribute of the wrapped object (so attempting to access an attribute
243 that doesn't exist will raise an `AttributeError`).
244
245 If the mock has an explicit `return_value` set then calls are not passed
246 to the wrapped object and the `return_value` is returned instead.
247
248 * `name`: If the mock has a name then it will be used in the repr of the
249 mock. This can be useful for debugging. The name is propagated to child
250 mocks.
251
252 Mocks can also be called with arbitrary keyword arguments. These will be
253 used to set attributes on the mock after it is created. See the
254 :meth:`configure_mock` method for details.
255
256
257 .. method:: assert_called_with(*args, **kwargs)
258
259 This method is a convenient way of asserting that calls are made in a
260 particular way:
261
262 >>> mock = Mock()
263 >>> mock.method(1, 2, 3, test='wow')
264 <Mock name='mock.method()' id='...'>
265 >>> mock.method.assert_called_with(1, 2, 3, test='wow')
266
267
268 .. method:: assert_called_once_with(*args, **kwargs)
269
270 Assert that the mock was called exactly once and with the specified
271 arguments.
272
273 >>> mock = Mock(return_value=None)
274 >>> mock('foo', bar='baz')
275 >>> mock.assert_called_once_with('foo', bar='baz')
276 >>> mock('foo', bar='baz')
277 >>> mock.assert_called_once_with('foo', bar='baz')
278 Traceback (most recent call last):
279 ...
280 AssertionError: Expected to be called once. Called 2 times.
281
282
283 .. method:: assert_any_call(*args, **kwargs)
284
285 assert the mock has been called with the specified arguments.
286
287 The assert passes if the mock has *ever* been called, unlike
288 :meth:`assert_called_with` and :meth:`assert_called_once_with` that
289 only pass if the call is the most recent one.
290
291 >>> mock = Mock(return_value=None)
292 >>> mock(1, 2, arg='thing')
293 >>> mock('some', 'thing', 'else')
294 >>> mock.assert_any_call(1, 2, arg='thing')
295
296
297 .. method:: assert_has_calls(calls, any_order=False)
298
299 assert the mock has been called with the specified calls.
300 The `mock_calls` list is checked for the calls.
301
302 If `any_order` is False (the default) then the calls must be
303 sequential. There can be extra calls before or after the
304 specified calls.
305
306 If `any_order` is True then the calls can be in any order, but
307 they must all appear in :attr:`mock_calls`.
308
309 >>> mock = Mock(return_value=None)
310 >>> mock(1)
311 >>> mock(2)
312 >>> mock(3)
313 >>> mock(4)
314 >>> calls = [call(2), call(3)]
315 >>> mock.assert_has_calls(calls)
316 >>> calls = [call(4), call(2), call(3)]
317 >>> mock.assert_has_calls(calls, any_order=True)
318
319
320 .. method:: reset_mock()
321
322 The reset_mock method resets all the call attributes on a mock object:
323
324 >>> mock = Mock(return_value=None)
325 >>> mock('hello')
326 >>> mock.called
327 True
328 >>> mock.reset_mock()
329 >>> mock.called
330 False
331
332 This can be useful where you want to make a series of assertions that
333 reuse the same object. Note that `reset_mock` *doesn't* clear the
334 return value, :attr:`side_effect` or any child attributes you have
335 set using normal assignment. Child mocks and the return value mock
336 (if any) are reset as well.
337
338
339 .. method:: mock_add_spec(spec, spec_set=False)
340
341 Add a spec to a mock. `spec` can either be an object or a
342 list of strings. Only attributes on the `spec` can be fetched as
343 attributes from the mock.
344
345 If `spec_set` is `True` then only attributes on the spec can be set.
346
347
348 .. method:: attach_mock(mock, attribute)
349
350 Attach a mock as an attribute of this one, replacing its name and
351 parent. Calls to the attached mock will be recorded in the
352 :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
353
354
355 .. method:: configure_mock(**kwargs)
356
357 Set attributes on the mock through keyword arguments.
358
359 Attributes plus return values and side effects can be set on child
360 mocks using standard dot notation and unpacking a dictionary in the
361 method call:
362
363 >>> mock = Mock()
364 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
365 >>> mock.configure_mock(**attrs)
366 >>> mock.method()
367 3
368 >>> mock.other()
369 Traceback (most recent call last):
370 ...
371 KeyError
372
373 The same thing can be achieved in the constructor call to mocks:
374
375 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
376 >>> mock = Mock(some_attribute='eggs', **attrs)
377 >>> mock.some_attribute
378 'eggs'
379 >>> mock.method()
380 3
381 >>> mock.other()
382 Traceback (most recent call last):
383 ...
384 KeyError
385
386 `configure_mock` exists to make it easier to do configuration
387 after the mock has been created.
388
389
390 .. method:: __dir__()
391
392 `Mock` objects limit the results of `dir(some_mock)` to useful results.
393 For mocks with a `spec` this includes all the permitted attributes
394 for the mock.
395
396 See :data:`FILTER_DIR` for what this filtering does, and how to
397 switch it off.
398
399
400 .. method:: _get_child_mock(**kw)
401
402 Create the child mocks for attributes and return value.
403 By default child mocks will be the same type as the parent.
404 Subclasses of Mock may want to override this to customize the way
405 child mocks are made.
406
407 For non-callable mocks the callable variant will be used (rather than
408 any custom subclass).
409
410
411 .. attribute:: called
412
413 A boolean representing whether or not the mock object has been called:
414
415 >>> mock = Mock(return_value=None)
416 >>> mock.called
417 False
418 >>> mock()
419 >>> mock.called
420 True
421
422 .. attribute:: call_count
423
424 An integer telling you how many times the mock object has been called:
425
426 >>> mock = Mock(return_value=None)
427 >>> mock.call_count
428 0
429 >>> mock()
430 >>> mock()
431 >>> mock.call_count
432 2
433
434
435 .. attribute:: return_value
436
437 Set this to configure the value returned by calling the mock:
438
439 >>> mock = Mock()
440 >>> mock.return_value = 'fish'
441 >>> mock()
442 'fish'
443
444 The default return value is a mock object and you can configure it in
445 the normal way:
446
447 >>> mock = Mock()
448 >>> mock.return_value.attribute = sentinel.Attribute
449 >>> mock.return_value()
450 <Mock name='mock()()' id='...'>
451 >>> mock.return_value.assert_called_with()
452
453 `return_value` can also be set in the constructor:
454
455 >>> mock = Mock(return_value=3)
456 >>> mock.return_value
457 3
458 >>> mock()
459 3
460
461
462 .. attribute:: side_effect
463
464 This can either be a function to be called when the mock is called,
465 or an exception (class or instance) to be raised.
466
467 If you pass in a function it will be called with same arguments as the
468 mock and unless the function returns the :data:`DEFAULT` singleton the
469 call to the mock will then return whatever the function returns. If the
470 function returns :data:`DEFAULT` then the mock will return its normal
471 value (from the :attr:`return_value`.
472
473 An example of a mock that raises an exception (to test exception
474 handling of an API):
475
476 >>> mock = Mock()
477 >>> mock.side_effect = Exception('Boom!')
478 >>> mock()
479 Traceback (most recent call last):
480 ...
481 Exception: Boom!
482
483 Using `side_effect` to return a sequence of values:
484
485 >>> mock = Mock()
486 >>> mock.side_effect = [3, 2, 1]
487 >>> mock(), mock(), mock()
488 (3, 2, 1)
489
490 The `side_effect` function is called with the same arguments as the
491 mock (so it is wise for it to take arbitrary args and keyword
492 arguments) and whatever it returns is used as the return value for
493 the call. The exception is if `side_effect` returns :data:`DEFAULT`,
494 in which case the normal :attr:`return_value` is used.
495
496 >>> mock = Mock(return_value=3)
497 >>> def side_effect(*args, **kwargs):
498 ... return DEFAULT
499 ...
500 >>> mock.side_effect = side_effect
501 >>> mock()
502 3
503
504 `side_effect` can be set in the constructor. Here's an example that
505 adds one to the value the mock is called with and returns it:
506
507 >>> side_effect = lambda value: value + 1
508 >>> mock = Mock(side_effect=side_effect)
509 >>> mock(3)
510 4
511 >>> mock(-8)
512 -7
513
514 Setting `side_effect` to `None` clears it:
515
516 >>> m = Mock(side_effect=KeyError, return_value=3)
517 >>> m()
518 Traceback (most recent call last):
519 ...
520 KeyError
521 >>> m.side_effect = None
522 >>> m()
523 3
524
525
526 .. attribute:: call_args
527
528 This is either `None` (if the mock hasn't been called), or the
529 arguments that the mock was last called with. This will be in the
530 form of a tuple: the first member is any ordered arguments the mock
531 was called with (or an empty tuple) and the second member is any
532 keyword arguments (or an empty dictionary).
533
534 >>> mock = Mock(return_value=None)
535 >>> print mock.call_args
536 None
537 >>> mock()
538 >>> mock.call_args
539 call()
540 >>> mock.call_args == ()
541 True
542 >>> mock(3, 4)
543 >>> mock.call_args
544 call(3, 4)
545 >>> mock.call_args == ((3, 4),)
546 True
547 >>> mock(3, 4, 5, key='fish', next='w00t!')
548 >>> mock.call_args
549 call(3, 4, 5, key='fish', next='w00t!')
550
551 `call_args`, along with members of the lists :attr:`call_args_list`,
552 :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
553 These are tuples, so they can be unpacked to get at the individual
554 arguments and make more complex assertions. See
555 :ref:`calls as tuples <calls-as-tuples>`.
556
557
558 .. attribute:: call_args_list
559
560 This is a list of all the calls made to the mock object in sequence
561 (so the length of the list is the number of times it has been
562 called). Before any calls have been made it is an empty list. The
563 :data:`call` object can be used for conveniently constructing lists of
564 calls to compare with `call_args_list`.
565
566 >>> mock = Mock(return_value=None)
567 >>> mock()
568 >>> mock(3, 4)
569 >>> mock(key='fish', next='w00t!')
570 >>> mock.call_args_list
571 [call(), call(3, 4), call(key='fish', next='w00t!')]
572 >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
573 >>> mock.call_args_list == expected
574 True
575
576 Members of `call_args_list` are :data:`call` objects. These can be
577 unpacked as tuples to get at the individual arguments. See
578 :ref:`calls as tuples <calls-as-tuples>`.
579
580
581 .. attribute:: method_calls
582
583 As well as tracking calls to themselves, mocks also track calls to
584 methods and attributes, and *their* methods and attributes:
585
586 >>> mock = Mock()
587 >>> mock.method()
588 <Mock name='mock.method()' id='...'>
589 >>> mock.property.method.attribute()
590 <Mock name='mock.property.method.attribute()' id='...'>
591 >>> mock.method_calls
592 [call.method(), call.property.method.attribute()]
593
594 Members of `method_calls` are :data:`call` objects. These can be
595 unpacked as tuples to get at the individual arguments. See
596 :ref:`calls as tuples <calls-as-tuples>`.
597
598
599 .. attribute:: mock_calls
600
601 `mock_calls` records *all* calls to the mock object, its methods, magic
602 methods *and* return value mocks.
603
604 >>> mock = MagicMock()
605 >>> result = mock(1, 2, 3)
606 >>> mock.first(a=3)
607 <MagicMock name='mock.first()' id='...'>
608 >>> mock.second()
609 <MagicMock name='mock.second()' id='...'>
610 >>> int(mock)
611 1
612 >>> result(1)
613 <MagicMock name='mock()()' id='...'>
614 >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
615 ... call.__int__(), call()(1)]
616 >>> mock.mock_calls == expected
617 True
618
619 Members of `mock_calls` are :data:`call` objects. These can be
620 unpacked as tuples to get at the individual arguments. See
621 :ref:`calls as tuples <calls-as-tuples>`.
622
623
624 .. attribute:: __class__
625
626 Normally the `__class__` attribute of an object will return its type.
627 For a mock object with a `spec` `__class__` returns the spec class
628 instead. This allows mock objects to pass `isinstance` tests for the
629 object they are replacing / masquerading as:
630
631 >>> mock = Mock(spec=3)
632 >>> isinstance(mock, int)
633 True
634
635 `__class__` is assignable to, this allows a mock to pass an
636 `isinstance` check without forcing you to use a spec:
637
638 >>> mock = Mock()
639 >>> mock.__class__ = dict
640 >>> isinstance(mock, dict)
641 True
642
643.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
644
645 A non-callable version of `Mock`. The constructor parameters have the same
646 meaning of `Mock`, with the exception of `return_value` and `side_effect`
647 which have no meaning on a non-callable mock.
648
649Mock objects that use a class or an instance as a `spec` or `spec_set` are able
650to pass `isintance` tests:
651
652 >>> mock = Mock(spec=SomeClass)
653 >>> isinstance(mock, SomeClass)
654 True
655 >>> mock = Mock(spec_set=SomeClass())
656 >>> isinstance(mock, SomeClass)
657 True
658
659The `Mock` classes have support for mocking magic methods. See :ref:`magic
660methods <magic-methods>` for the full details.
661
662The mock classes and the :func:`patch` decorators all take arbitrary keyword
663arguments for configuration. For the `patch` decorators the keywords are
664passed to the constructor of the mock being created. The keyword arguments
665are for configuring attributes of the mock:
666
667 >>> m = MagicMock(attribute=3, other='fish')
668 >>> m.attribute
669 3
670 >>> m.other
671 'fish'
672
673The return value and side effect of child mocks can be set in the same way,
674using dotted notation. As you can't use dotted names directly in a call you
675have to create a dictionary and unpack it using `**`:
676
677 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
678 >>> mock = Mock(some_attribute='eggs', **attrs)
679 >>> mock.some_attribute
680 'eggs'
681 >>> mock.method()
682 3
683 >>> mock.other()
684 Traceback (most recent call last):
685 ...
686 KeyError
687
688
689.. class:: PropertyMock(*args, **kwargs)
690
691 A mock intended to be used as a property, or other descriptor, on a class.
692 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
693 a return value when it is fetched.
694
695 Fetching a `PropertyMock` instance from an object calls the mock, with
696 no args. Setting it calls the mock with the value being set.
697
698 >>> class Foo(object):
699 ... @property
700 ... def foo(self):
701 ... return 'something'
702 ... @foo.setter
703 ... def foo(self, value):
704 ... pass
705 ...
706 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
707 ... mock_foo.return_value = 'mockity-mock'
708 ... this_foo = Foo()
709 ... print this_foo.foo
710 ... this_foo.foo = 6
711 ...
712 mockity-mock
713 >>> mock_foo.mock_calls
714 [call(), call(6)]
715
716
717Calling
718~~~~~~~
719
720Mock objects are callable. The call will return the value set as the
721:attr:`~Mock.return_value` attribute. The default return value is a new Mock
722object; it is created the first time the return value is accessed (either
723explicitly or by calling the Mock) - but it is stored and the same one
724returned each time.
725
726Calls made to the object will be recorded in the attributes
727like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
728
729If :attr:`~Mock.side_effect` is set then it will be called after the call has
730been recorded, so if `side_effect` raises an exception the call is still
731recorded.
732
733The simplest way to make a mock raise an exception when called is to make
734:attr:`~Mock.side_effect` an exception class or instance:
735
736 >>> m = MagicMock(side_effect=IndexError)
737 >>> m(1, 2, 3)
738 Traceback (most recent call last):
739 ...
740 IndexError
741 >>> m.mock_calls
742 [call(1, 2, 3)]
743 >>> m.side_effect = KeyError('Bang!')
744 >>> m('two', 'three', 'four')
745 Traceback (most recent call last):
746 ...
747 KeyError: 'Bang!'
748 >>> m.mock_calls
749 [call(1, 2, 3), call('two', 'three', 'four')]
750
751If `side_effect` is a function then whatever that function returns is what
752calls to the mock return. The `side_effect` function is called with the
753same arguments as the mock. This allows you to vary the return value of the
754call dynamically, based on the input:
755
756 >>> def side_effect(value):
757 ... return value + 1
758 ...
759 >>> m = MagicMock(side_effect=side_effect)
760 >>> m(1)
761 2
762 >>> m(2)
763 3
764 >>> m.mock_calls
765 [call(1), call(2)]
766
767If you want the mock to still return the default return value (a new mock), or
768any set return value, then there are two ways of doing this. Either return
769`mock.return_value` from inside `side_effect`, or return :data:`DEFAULT`:
770
771 >>> m = MagicMock()
772 >>> def side_effect(*args, **kwargs):
773 ... return m.return_value
774 ...
775 >>> m.side_effect = side_effect
776 >>> m.return_value = 3
777 >>> m()
778 3
779 >>> def side_effect(*args, **kwargs):
780 ... return DEFAULT
781 ...
782 >>> m.side_effect = side_effect
783 >>> m()
784 3
785
786To remove a `side_effect`, and return to the default behaviour, set the
787`side_effect` to `None`:
788
789 >>> m = MagicMock(return_value=6)
790 >>> def side_effect(*args, **kwargs):
791 ... return 3
792 ...
793 >>> m.side_effect = side_effect
794 >>> m()
795 3
796 >>> m.side_effect = None
797 >>> m()
798 6
799
800The `side_effect` can also be any iterable object. Repeated calls to the mock
801will return values from the iterable (until the iterable is exhausted and
802a `StopIteration` is raised):
803
804 >>> m = MagicMock(side_effect=[1, 2, 3])
805 >>> m()
806 1
807 >>> m()
808 2
809 >>> m()
810 3
811 >>> m()
812 Traceback (most recent call last):
813 ...
814 StopIteration
815
816
817.. _deleting-attributes:
818
819Deleting Attributes
820~~~~~~~~~~~~~~~~~~~
821
822Mock objects create attributes on demand. This allows them to pretend to be
823objects of any type.
824
825You may want a mock object to return `False` to a `hasattr` call, or raise an
826`AttributeError` when an attribute is fetched. You can do this by providing
827an object as a `spec` for a mock, but that isn't always convenient.
828
829You "block" attributes by deleting them. Once deleted, accessing an attribute
830will raise an `AttributeError`.
831
832 >>> mock = MagicMock()
833 >>> hasattr(mock, 'm')
834 True
835 >>> del mock.m
836 >>> hasattr(mock, 'm')
837 False
838 >>> del mock.f
839 >>> mock.f
840 Traceback (most recent call last):
841 ...
842 AttributeError: f
843
844
845Attaching Mocks as Attributes
846~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
847
848When you attach a mock as an attribute of another mock (or as the return
849value) it becomes a "child" of that mock. Calls to the child are recorded in
850the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
851parent. This is useful for configuring child mocks and then attaching them to
852the parent, or for attaching mocks to a parent that records all calls to the
853children and allows you to make assertions about the order of calls between
854mocks:
855
856 >>> parent = MagicMock()
857 >>> child1 = MagicMock(return_value=None)
858 >>> child2 = MagicMock(return_value=None)
859 >>> parent.child1 = child1
860 >>> parent.child2 = child2
861 >>> child1(1)
862 >>> child2(2)
863 >>> parent.mock_calls
864 [call.child1(1), call.child2(2)]
865
866The exception to this is if the mock has a name. This allows you to prevent
867the "parenting" if for some reason you don't want it to happen.
868
869 >>> mock = MagicMock()
870 >>> not_a_child = MagicMock(name='not-a-child')
871 >>> mock.attribute = not_a_child
872 >>> mock.attribute()
873 <MagicMock name='not-a-child()' id='...'>
874 >>> mock.mock_calls
875 []
876
877Mocks created for you by :func:`patch` are automatically given names. To
878attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
879method:
880
881 >>> thing1 = object()
882 >>> thing2 = object()
883 >>> parent = MagicMock()
884 >>> with patch('__main__.thing1', return_value=None) as child1:
885 ... with patch('__main__.thing2', return_value=None) as child2:
886 ... parent.attach_mock(child1, 'child1')
887 ... parent.attach_mock(child2, 'child2')
888 ... child1('one')
889 ... child2('two')
890 ...
891 >>> parent.mock_calls
892 [call.child1('one'), call.child2('two')]
893
894
895.. [#] The only exceptions are magic methods and attributes (those that have
896 leading and trailing double underscores). Mock doesn't create these but
897 instead of raises an ``AttributeError``. This is because the interpreter
898 will often implicitly request these methods, and gets *very* confused to
899 get a new Mock object when it expects a magic method. If you need magic
900 method support see :ref:`magic methods <magic-methods>`.