blob: 4f588924433db6be8a774f08924ba586f64ae99a [file] [log] [blame]
Andrew Svetlov7ea6f702012-10-31 11:29:52 +02001
Michael Foord944e02d2012-03-25 23:12:55 +01002:mod:`unittest.mock` --- mock object library
3============================================
4
5.. module:: unittest.mock
6 :synopsis: Mock object library.
7.. moduleauthor:: Michael Foord <michael@python.org>
8.. currentmodule:: unittest.mock
9
10.. versionadded:: 3.3
11
12:mod:`unittest.mock` is a library for testing in Python. It allows you to
13replace parts of your system under test with mock objects and make assertions
14about how they have been used.
15
16`unittest.mock` provides a core :class:`Mock` class removing the need to
17create a host of stubs throughout your test suite. After performing an
18action, you can make assertions about which methods / attributes were used
19and arguments they were called with. You can also specify return values and
20set needed attributes in the normal way.
21
22Additionally, mock provides a :func:`patch` decorator that handles patching
23module and class level attributes within the scope of a test, along with
24:const:`sentinel` for creating unique objects. See the `quick guide`_ for
25some examples of how to use :class:`Mock`, :class:`MagicMock` and
26:func:`patch`.
27
28Mock is very easy to use and is designed for use with :mod:`unittest`. Mock
29is based on the 'action -> assertion' pattern instead of `'record -> replay'`
30used by many mocking frameworks.
31
32There is a backport of `unittest.mock` for earlier versions of Python,
33available as `mock on PyPI <http://pypi.python.org/pypi/mock>`_.
34
35**Source code:** :source:`Lib/unittest/mock.py`
36
37
38Quick Guide
39-----------
40
41:class:`Mock` and :class:`MagicMock` objects create all attributes and
42methods as you access them and store details of how they have been used. You
43can configure them, to specify return values or limit what attributes are
44available, and then make assertions about how they have been used:
45
46 >>> from unittest.mock import MagicMock
47 >>> thing = ProductionClass()
48 >>> thing.method = MagicMock(return_value=3)
49 >>> thing.method(3, 4, 5, key='value')
50 3
51 >>> thing.method.assert_called_with(3, 4, 5, key='value')
52
53:attr:`side_effect` allows you to perform side effects, including raising an
54exception when a mock is called:
55
56 >>> mock = Mock(side_effect=KeyError('foo'))
57 >>> mock()
58 Traceback (most recent call last):
59 ...
60 KeyError: 'foo'
61
62 >>> values = {'a': 1, 'b': 2, 'c': 3}
63 >>> def side_effect(arg):
64 ... return values[arg]
65 ...
66 >>> mock.side_effect = side_effect
67 >>> mock('a'), mock('b'), mock('c')
68 (1, 2, 3)
69 >>> mock.side_effect = [5, 4, 3, 2, 1]
70 >>> mock(), mock(), mock()
71 (5, 4, 3)
72
73Mock has many other ways you can configure it and control its behaviour. For
74example the `spec` argument configures the mock to take its specification
75from another object. Attempting to access attributes or methods on the mock
76that don't exist on the spec will fail with an `AttributeError`.
77
78The :func:`patch` decorator / context manager makes it easy to mock classes or
79objects in a module under test. The object you specify will be replaced with a
80mock (or other object) during the test and restored when the test ends:
81
82 >>> from unittest.mock import patch
83 >>> @patch('module.ClassName2')
84 ... @patch('module.ClassName1')
85 ... def test(MockClass1, MockClass2):
86 ... module.ClassName1()
87 ... module.ClassName2()
Michael Foord944e02d2012-03-25 23:12:55 +010088 ... 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
Kushal Das8c145342014-04-16 23:32:21 +0530201.. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)
Michael Foord944e02d2012-03-25 23:12:55 +0100202
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
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300213 :attr:`~instance.__class__` returns the class of the spec object. This
214 allows mocks to pass `isinstance` tests.
Michael Foord944e02d2012-03-25 23:12:55 +0100215
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
Kushal Das8c145342014-04-16 23:32:21 +0530238 * `unsafe`: By default if any attribute starts with *assert* or
239 *assret* will raise an `AttributeError`. Passing `unsafe=True` will allow
240 access to these attributes.
241
242 .. versionadded:: 3.5
243
Michael Foord944e02d2012-03-25 23:12:55 +0100244 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
245 calling the Mock will pass the call through to the wrapped object
Michael Foord0682a0c2012-04-13 20:51:20 +0100246 (returning the real result). Attribute access on the mock will return a
247 Mock object that wraps the corresponding attribute of the wrapped
248 object (so attempting to access an attribute that doesn't exist will
249 raise an `AttributeError`).
Michael Foord944e02d2012-03-25 23:12:55 +0100250
251 If the mock has an explicit `return_value` set then calls are not passed
252 to the wrapped object and the `return_value` is returned instead.
253
254 * `name`: If the mock has a name then it will be used in the repr of the
255 mock. This can be useful for debugging. The name is propagated to child
256 mocks.
257
258 Mocks can also be called with arbitrary keyword arguments. These will be
259 used to set attributes on the mock after it is created. See the
260 :meth:`configure_mock` method for details.
261
262
263 .. method:: assert_called_with(*args, **kwargs)
264
265 This method is a convenient way of asserting that calls are made in a
266 particular way:
267
268 >>> mock = Mock()
269 >>> mock.method(1, 2, 3, test='wow')
270 <Mock name='mock.method()' id='...'>
271 >>> mock.method.assert_called_with(1, 2, 3, test='wow')
272
Michael Foord944e02d2012-03-25 23:12:55 +0100273 .. method:: assert_called_once_with(*args, **kwargs)
274
275 Assert that the mock was called exactly once and with the specified
276 arguments.
277
278 >>> mock = Mock(return_value=None)
279 >>> mock('foo', bar='baz')
280 >>> mock.assert_called_once_with('foo', bar='baz')
281 >>> mock('foo', bar='baz')
282 >>> mock.assert_called_once_with('foo', bar='baz')
283 Traceback (most recent call last):
284 ...
Michael Foord28d591c2012-09-28 16:15:22 +0100285 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foord944e02d2012-03-25 23:12:55 +0100286
287
288 .. method:: assert_any_call(*args, **kwargs)
289
290 assert the mock has been called with the specified arguments.
291
292 The assert passes if the mock has *ever* been called, unlike
293 :meth:`assert_called_with` and :meth:`assert_called_once_with` that
294 only pass if the call is the most recent one.
295
296 >>> mock = Mock(return_value=None)
297 >>> mock(1, 2, arg='thing')
298 >>> mock('some', 'thing', 'else')
299 >>> mock.assert_any_call(1, 2, arg='thing')
300
301
302 .. method:: assert_has_calls(calls, any_order=False)
303
304 assert the mock has been called with the specified calls.
305 The `mock_calls` list is checked for the calls.
306
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200307 If `any_order` is false (the default) then the calls must be
Michael Foord944e02d2012-03-25 23:12:55 +0100308 sequential. There can be extra calls before or after the
309 specified calls.
310
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200311 If `any_order` is true then the calls can be in any order, but
Michael Foord944e02d2012-03-25 23:12:55 +0100312 they must all appear in :attr:`mock_calls`.
313
314 >>> mock = Mock(return_value=None)
315 >>> mock(1)
316 >>> mock(2)
317 >>> mock(3)
318 >>> mock(4)
319 >>> calls = [call(2), call(3)]
320 >>> mock.assert_has_calls(calls)
321 >>> calls = [call(4), call(2), call(3)]
322 >>> mock.assert_has_calls(calls, any_order=True)
323
Kushal Das8af9db32014-04-17 01:36:14 +0530324 .. method:: assert_not_called(*args, **kwargs)
325
326 Assert the mock was never called.
327
328 >>> m = Mock()
329 >>> m.hello.assert_not_called()
330 >>> obj = m.hello()
331 >>> m.hello.assert_not_called()
332 Traceback (most recent call last):
333 ...
334 AssertionError: Expected 'hello' to not have been called. Called 1 times.
335
336 .. versionadded:: 3.5
337
Michael Foord944e02d2012-03-25 23:12:55 +0100338
339 .. method:: reset_mock()
340
341 The reset_mock method resets all the call attributes on a mock object:
342
343 >>> mock = Mock(return_value=None)
344 >>> mock('hello')
345 >>> mock.called
346 True
347 >>> mock.reset_mock()
348 >>> mock.called
349 False
350
351 This can be useful where you want to make a series of assertions that
352 reuse the same object. Note that `reset_mock` *doesn't* clear the
353 return value, :attr:`side_effect` or any child attributes you have
354 set using normal assignment. Child mocks and the return value mock
355 (if any) are reset as well.
356
357
358 .. method:: mock_add_spec(spec, spec_set=False)
359
360 Add a spec to a mock. `spec` can either be an object or a
361 list of strings. Only attributes on the `spec` can be fetched as
362 attributes from the mock.
363
364 If `spec_set` is `True` then only attributes on the spec can be set.
365
366
367 .. method:: attach_mock(mock, attribute)
368
369 Attach a mock as an attribute of this one, replacing its name and
370 parent. Calls to the attached mock will be recorded in the
371 :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
372
373
374 .. method:: configure_mock(**kwargs)
375
376 Set attributes on the mock through keyword arguments.
377
378 Attributes plus return values and side effects can be set on child
379 mocks using standard dot notation and unpacking a dictionary in the
380 method call:
381
382 >>> mock = Mock()
383 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
384 >>> mock.configure_mock(**attrs)
385 >>> mock.method()
386 3
387 >>> mock.other()
388 Traceback (most recent call last):
389 ...
390 KeyError
391
392 The same thing can be achieved in the constructor call to mocks:
393
394 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
395 >>> mock = Mock(some_attribute='eggs', **attrs)
396 >>> mock.some_attribute
397 'eggs'
398 >>> mock.method()
399 3
400 >>> mock.other()
401 Traceback (most recent call last):
402 ...
403 KeyError
404
405 `configure_mock` exists to make it easier to do configuration
406 after the mock has been created.
407
408
409 .. method:: __dir__()
410
411 `Mock` objects limit the results of `dir(some_mock)` to useful results.
412 For mocks with a `spec` this includes all the permitted attributes
413 for the mock.
414
415 See :data:`FILTER_DIR` for what this filtering does, and how to
416 switch it off.
417
418
419 .. method:: _get_child_mock(**kw)
420
421 Create the child mocks for attributes and return value.
422 By default child mocks will be the same type as the parent.
423 Subclasses of Mock may want to override this to customize the way
424 child mocks are made.
425
426 For non-callable mocks the callable variant will be used (rather than
427 any custom subclass).
428
429
430 .. attribute:: called
431
432 A boolean representing whether or not the mock object has been called:
433
434 >>> mock = Mock(return_value=None)
435 >>> mock.called
436 False
437 >>> mock()
438 >>> mock.called
439 True
440
441 .. attribute:: call_count
442
443 An integer telling you how many times the mock object has been called:
444
445 >>> mock = Mock(return_value=None)
446 >>> mock.call_count
447 0
448 >>> mock()
449 >>> mock()
450 >>> mock.call_count
451 2
452
453
454 .. attribute:: return_value
455
456 Set this to configure the value returned by calling the mock:
457
458 >>> mock = Mock()
459 >>> mock.return_value = 'fish'
460 >>> mock()
461 'fish'
462
463 The default return value is a mock object and you can configure it in
464 the normal way:
465
466 >>> mock = Mock()
467 >>> mock.return_value.attribute = sentinel.Attribute
468 >>> mock.return_value()
469 <Mock name='mock()()' id='...'>
470 >>> mock.return_value.assert_called_with()
471
472 `return_value` can also be set in the constructor:
473
474 >>> mock = Mock(return_value=3)
475 >>> mock.return_value
476 3
477 >>> mock()
478 3
479
480
481 .. attribute:: side_effect
482
483 This can either be a function to be called when the mock is called,
484 or an exception (class or instance) to be raised.
485
486 If you pass in a function it will be called with same arguments as the
487 mock and unless the function returns the :data:`DEFAULT` singleton the
488 call to the mock will then return whatever the function returns. If the
489 function returns :data:`DEFAULT` then the mock will return its normal
Brett Cannon533f1ed2013-05-25 11:28:20 -0400490 value (from the :attr:`return_value`).
Michael Foord944e02d2012-03-25 23:12:55 +0100491
492 An example of a mock that raises an exception (to test exception
493 handling of an API):
494
495 >>> mock = Mock()
496 >>> mock.side_effect = Exception('Boom!')
497 >>> mock()
498 Traceback (most recent call last):
499 ...
500 Exception: Boom!
501
502 Using `side_effect` to return a sequence of values:
503
504 >>> mock = Mock()
505 >>> mock.side_effect = [3, 2, 1]
506 >>> mock(), mock(), mock()
507 (3, 2, 1)
508
509 The `side_effect` function is called with the same arguments as the
510 mock (so it is wise for it to take arbitrary args and keyword
511 arguments) and whatever it returns is used as the return value for
512 the call. The exception is if `side_effect` returns :data:`DEFAULT`,
513 in which case the normal :attr:`return_value` is used.
514
515 >>> mock = Mock(return_value=3)
516 >>> def side_effect(*args, **kwargs):
517 ... return DEFAULT
518 ...
519 >>> mock.side_effect = side_effect
520 >>> mock()
521 3
522
523 `side_effect` can be set in the constructor. Here's an example that
524 adds one to the value the mock is called with and returns it:
525
526 >>> side_effect = lambda value: value + 1
527 >>> mock = Mock(side_effect=side_effect)
528 >>> mock(3)
529 4
530 >>> mock(-8)
531 -7
532
533 Setting `side_effect` to `None` clears it:
534
535 >>> m = Mock(side_effect=KeyError, return_value=3)
536 >>> m()
537 Traceback (most recent call last):
538 ...
539 KeyError
540 >>> m.side_effect = None
541 >>> m()
542 3
543
544
545 .. attribute:: call_args
546
547 This is either `None` (if the mock hasn't been called), or the
548 arguments that the mock was last called with. This will be in the
549 form of a tuple: the first member is any ordered arguments the mock
550 was called with (or an empty tuple) and the second member is any
551 keyword arguments (or an empty dictionary).
552
553 >>> mock = Mock(return_value=None)
554 >>> print mock.call_args
555 None
556 >>> mock()
557 >>> mock.call_args
558 call()
559 >>> mock.call_args == ()
560 True
561 >>> mock(3, 4)
562 >>> mock.call_args
563 call(3, 4)
564 >>> mock.call_args == ((3, 4),)
565 True
566 >>> mock(3, 4, 5, key='fish', next='w00t!')
567 >>> mock.call_args
568 call(3, 4, 5, key='fish', next='w00t!')
569
570 `call_args`, along with members of the lists :attr:`call_args_list`,
571 :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
572 These are tuples, so they can be unpacked to get at the individual
573 arguments and make more complex assertions. See
574 :ref:`calls as tuples <calls-as-tuples>`.
575
576
577 .. attribute:: call_args_list
578
579 This is a list of all the calls made to the mock object in sequence
580 (so the length of the list is the number of times it has been
581 called). Before any calls have been made it is an empty list. The
582 :data:`call` object can be used for conveniently constructing lists of
583 calls to compare with `call_args_list`.
584
585 >>> mock = Mock(return_value=None)
586 >>> mock()
587 >>> mock(3, 4)
588 >>> mock(key='fish', next='w00t!')
589 >>> mock.call_args_list
590 [call(), call(3, 4), call(key='fish', next='w00t!')]
591 >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
592 >>> mock.call_args_list == expected
593 True
594
595 Members of `call_args_list` are :data:`call` objects. These can be
596 unpacked as tuples to get at the individual arguments. See
597 :ref:`calls as tuples <calls-as-tuples>`.
598
599
600 .. attribute:: method_calls
601
602 As well as tracking calls to themselves, mocks also track calls to
603 methods and attributes, and *their* methods and attributes:
604
605 >>> mock = Mock()
606 >>> mock.method()
607 <Mock name='mock.method()' id='...'>
608 >>> mock.property.method.attribute()
609 <Mock name='mock.property.method.attribute()' id='...'>
610 >>> mock.method_calls
611 [call.method(), call.property.method.attribute()]
612
613 Members of `method_calls` are :data:`call` objects. These can be
614 unpacked as tuples to get at the individual arguments. See
615 :ref:`calls as tuples <calls-as-tuples>`.
616
617
618 .. attribute:: mock_calls
619
620 `mock_calls` records *all* calls to the mock object, its methods, magic
621 methods *and* return value mocks.
622
623 >>> mock = MagicMock()
624 >>> result = mock(1, 2, 3)
625 >>> mock.first(a=3)
626 <MagicMock name='mock.first()' id='...'>
627 >>> mock.second()
628 <MagicMock name='mock.second()' id='...'>
629 >>> int(mock)
630 1
631 >>> result(1)
632 <MagicMock name='mock()()' id='...'>
633 >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
634 ... call.__int__(), call()(1)]
635 >>> mock.mock_calls == expected
636 True
637
638 Members of `mock_calls` are :data:`call` objects. These can be
639 unpacked as tuples to get at the individual arguments. See
640 :ref:`calls as tuples <calls-as-tuples>`.
641
642
643 .. attribute:: __class__
644
645 Normally the `__class__` attribute of an object will return its type.
646 For a mock object with a `spec` `__class__` returns the spec class
647 instead. This allows mock objects to pass `isinstance` tests for the
648 object they are replacing / masquerading as:
649
650 >>> mock = Mock(spec=3)
651 >>> isinstance(mock, int)
652 True
653
654 `__class__` is assignable to, this allows a mock to pass an
655 `isinstance` check without forcing you to use a spec:
656
657 >>> mock = Mock()
658 >>> mock.__class__ = dict
659 >>> isinstance(mock, dict)
660 True
661
662.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
663
664 A non-callable version of `Mock`. The constructor parameters have the same
665 meaning of `Mock`, with the exception of `return_value` and `side_effect`
666 which have no meaning on a non-callable mock.
667
668Mock objects that use a class or an instance as a `spec` or `spec_set` are able
Andrew Svetlov7ea6f702012-10-31 11:29:52 +0200669to pass `isinstance` tests:
Michael Foord944e02d2012-03-25 23:12:55 +0100670
671 >>> mock = Mock(spec=SomeClass)
672 >>> isinstance(mock, SomeClass)
673 True
674 >>> mock = Mock(spec_set=SomeClass())
675 >>> isinstance(mock, SomeClass)
676 True
677
678The `Mock` classes have support for mocking magic methods. See :ref:`magic
679methods <magic-methods>` for the full details.
680
681The mock classes and the :func:`patch` decorators all take arbitrary keyword
682arguments for configuration. For the `patch` decorators the keywords are
683passed to the constructor of the mock being created. The keyword arguments
684are for configuring attributes of the mock:
685
686 >>> m = MagicMock(attribute=3, other='fish')
687 >>> m.attribute
688 3
689 >>> m.other
690 'fish'
691
692The return value and side effect of child mocks can be set in the same way,
693using dotted notation. As you can't use dotted names directly in a call you
694have to create a dictionary and unpack it using `**`:
695
696 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
697 >>> mock = Mock(some_attribute='eggs', **attrs)
698 >>> mock.some_attribute
699 'eggs'
700 >>> mock.method()
701 3
702 >>> mock.other()
703 Traceback (most recent call last):
704 ...
705 KeyError
706
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100707A callable mock which was created with a *spec* (or a *spec_set*) will
708introspect the specification object's signature when matching calls to
709the mock. Therefore, it can match the actual call's arguments regardless
710of whether they were passed positionally or by name::
711
712 >>> def f(a, b, c): pass
713 ...
714 >>> mock = Mock(spec=f)
715 >>> mock(1, 2, c=3)
716 <Mock name='mock()' id='140161580456576'>
717 >>> mock.assert_called_with(1, 2, 3)
718 >>> mock.assert_called_with(a=1, b=2, c=3)
719
720This applies to :meth:`~Mock.assert_called_with`,
721:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and
722:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also
723apply to method calls on the mock object.
724
725 .. versionchanged:: 3.4
726 Added signature introspection on specced and autospecced mock objects.
727
Michael Foord944e02d2012-03-25 23:12:55 +0100728
729.. class:: PropertyMock(*args, **kwargs)
730
731 A mock intended to be used as a property, or other descriptor, on a class.
732 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
733 a return value when it is fetched.
734
735 Fetching a `PropertyMock` instance from an object calls the mock, with
736 no args. Setting it calls the mock with the value being set.
737
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200738 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100739 ... @property
740 ... def foo(self):
741 ... return 'something'
742 ... @foo.setter
743 ... def foo(self, value):
744 ... pass
745 ...
746 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
747 ... mock_foo.return_value = 'mockity-mock'
748 ... this_foo = Foo()
749 ... print this_foo.foo
750 ... this_foo.foo = 6
751 ...
752 mockity-mock
753 >>> mock_foo.mock_calls
754 [call(), call(6)]
755
Michael Foordc2870622012-04-13 16:57:22 +0100756Because of the way mock attributes are stored you can't directly attach a
757`PropertyMock` to a mock object. Instead you can attach it to the mock type
758object::
759
760 >>> m = MagicMock()
761 >>> p = PropertyMock(return_value=3)
762 >>> type(m).foo = p
763 >>> m.foo
764 3
765 >>> p.assert_called_once_with()
766
Michael Foord944e02d2012-03-25 23:12:55 +0100767
768Calling
769~~~~~~~
770
771Mock objects are callable. The call will return the value set as the
772:attr:`~Mock.return_value` attribute. The default return value is a new Mock
773object; it is created the first time the return value is accessed (either
774explicitly or by calling the Mock) - but it is stored and the same one
775returned each time.
776
777Calls made to the object will be recorded in the attributes
778like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
779
780If :attr:`~Mock.side_effect` is set then it will be called after the call has
781been recorded, so if `side_effect` raises an exception the call is still
782recorded.
783
784The simplest way to make a mock raise an exception when called is to make
785:attr:`~Mock.side_effect` an exception class or instance:
786
787 >>> m = MagicMock(side_effect=IndexError)
788 >>> m(1, 2, 3)
789 Traceback (most recent call last):
790 ...
791 IndexError
792 >>> m.mock_calls
793 [call(1, 2, 3)]
794 >>> m.side_effect = KeyError('Bang!')
795 >>> m('two', 'three', 'four')
796 Traceback (most recent call last):
797 ...
798 KeyError: 'Bang!'
799 >>> m.mock_calls
800 [call(1, 2, 3), call('two', 'three', 'four')]
801
802If `side_effect` is a function then whatever that function returns is what
803calls to the mock return. The `side_effect` function is called with the
804same arguments as the mock. This allows you to vary the return value of the
805call dynamically, based on the input:
806
807 >>> def side_effect(value):
808 ... return value + 1
809 ...
810 >>> m = MagicMock(side_effect=side_effect)
811 >>> m(1)
812 2
813 >>> m(2)
814 3
815 >>> m.mock_calls
816 [call(1), call(2)]
817
818If you want the mock to still return the default return value (a new mock), or
819any set return value, then there are two ways of doing this. Either return
820`mock.return_value` from inside `side_effect`, or return :data:`DEFAULT`:
821
822 >>> m = MagicMock()
823 >>> def side_effect(*args, **kwargs):
824 ... return m.return_value
825 ...
826 >>> m.side_effect = side_effect
827 >>> m.return_value = 3
828 >>> m()
829 3
830 >>> def side_effect(*args, **kwargs):
831 ... return DEFAULT
832 ...
833 >>> m.side_effect = side_effect
834 >>> m()
835 3
836
837To remove a `side_effect`, and return to the default behaviour, set the
838`side_effect` to `None`:
839
840 >>> m = MagicMock(return_value=6)
841 >>> def side_effect(*args, **kwargs):
842 ... return 3
843 ...
844 >>> m.side_effect = side_effect
845 >>> m()
846 3
847 >>> m.side_effect = None
848 >>> m()
849 6
850
851The `side_effect` can also be any iterable object. Repeated calls to the mock
852will return values from the iterable (until the iterable is exhausted and
853a `StopIteration` is raised):
854
855 >>> m = MagicMock(side_effect=[1, 2, 3])
856 >>> m()
857 1
858 >>> m()
859 2
860 >>> m()
861 3
862 >>> m()
863 Traceback (most recent call last):
864 ...
865 StopIteration
866
Michael Foord2cd48732012-04-21 15:52:11 +0100867If any members of the iterable are exceptions they will be raised instead of
868returned::
869
870 >>> iterable = (33, ValueError, 66)
871 >>> m = MagicMock(side_effect=iterable)
872 >>> m()
873 33
874 >>> m()
875 Traceback (most recent call last):
876 ...
877 ValueError
878 >>> m()
879 66
880
Michael Foord944e02d2012-03-25 23:12:55 +0100881
882.. _deleting-attributes:
883
884Deleting Attributes
885~~~~~~~~~~~~~~~~~~~
886
887Mock objects create attributes on demand. This allows them to pretend to be
888objects of any type.
889
890You may want a mock object to return `False` to a `hasattr` call, or raise an
891`AttributeError` when an attribute is fetched. You can do this by providing
892an object as a `spec` for a mock, but that isn't always convenient.
893
894You "block" attributes by deleting them. Once deleted, accessing an attribute
895will raise an `AttributeError`.
896
897 >>> mock = MagicMock()
898 >>> hasattr(mock, 'm')
899 True
900 >>> del mock.m
901 >>> hasattr(mock, 'm')
902 False
903 >>> del mock.f
904 >>> mock.f
905 Traceback (most recent call last):
906 ...
907 AttributeError: f
908
909
Michael Foordf5752302013-03-18 15:04:03 -0700910Mock names and the name attribute
911~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
912
913Since "name" is an argument to the :class:`Mock` constructor, if you want your
914mock object to have a "name" attribute you can't just pass it in at creation
915time. There are two alternatives. One option is to use
916:meth:`~Mock.configure_mock`::
917
918 >>> mock = MagicMock()
919 >>> mock.configure_mock(name='my_name')
920 >>> mock.name
921 'my_name'
922
923A simpler option is to simply set the "name" attribute after mock creation::
924
925 >>> mock = MagicMock()
926 >>> mock.name = "foo"
927
928
Michael Foord944e02d2012-03-25 23:12:55 +0100929Attaching Mocks as Attributes
930~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
931
932When you attach a mock as an attribute of another mock (or as the return
933value) it becomes a "child" of that mock. Calls to the child are recorded in
934the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
935parent. This is useful for configuring child mocks and then attaching them to
936the parent, or for attaching mocks to a parent that records all calls to the
937children and allows you to make assertions about the order of calls between
938mocks:
939
940 >>> parent = MagicMock()
941 >>> child1 = MagicMock(return_value=None)
942 >>> child2 = MagicMock(return_value=None)
943 >>> parent.child1 = child1
944 >>> parent.child2 = child2
945 >>> child1(1)
946 >>> child2(2)
947 >>> parent.mock_calls
948 [call.child1(1), call.child2(2)]
949
950The exception to this is if the mock has a name. This allows you to prevent
951the "parenting" if for some reason you don't want it to happen.
952
953 >>> mock = MagicMock()
954 >>> not_a_child = MagicMock(name='not-a-child')
955 >>> mock.attribute = not_a_child
956 >>> mock.attribute()
957 <MagicMock name='not-a-child()' id='...'>
958 >>> mock.mock_calls
959 []
960
961Mocks created for you by :func:`patch` are automatically given names. To
962attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
963method:
964
965 >>> thing1 = object()
966 >>> thing2 = object()
967 >>> parent = MagicMock()
968 >>> with patch('__main__.thing1', return_value=None) as child1:
969 ... with patch('__main__.thing2', return_value=None) as child2:
970 ... parent.attach_mock(child1, 'child1')
971 ... parent.attach_mock(child2, 'child2')
972 ... child1('one')
973 ... child2('two')
974 ...
975 >>> parent.mock_calls
976 [call.child1('one'), call.child2('two')]
977
978
979.. [#] The only exceptions are magic methods and attributes (those that have
980 leading and trailing double underscores). Mock doesn't create these but
Zachary Ware5ea5d2c2014-02-26 09:34:43 -0600981 instead raises an ``AttributeError``. This is because the interpreter
Michael Foord944e02d2012-03-25 23:12:55 +0100982 will often implicitly request these methods, and gets *very* confused to
983 get a new Mock object when it expects a magic method. If you need magic
984 method support see :ref:`magic methods <magic-methods>`.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100985
986
987The patchers
Georg Brandlfb134382013-02-03 11:47:49 +0100988------------
Michael Foorda9e6fb22012-03-28 14:36:02 +0100989
990The patch decorators are used for patching objects only within the scope of
991the function they decorate. They automatically handle the unpatching for you,
992even if exceptions are raised. All of these functions can also be used in with
993statements or as class decorators.
994
995
996patch
Georg Brandlfb134382013-02-03 11:47:49 +0100997~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +0100998
999.. note::
1000
1001 `patch` is straightforward to use. The key is to do the patching in the
1002 right namespace. See the section `where to patch`_.
1003
1004.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1005
1006 `patch` acts as a function decorator, class decorator or a context
1007 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001008 is patched with a `new` object. When the function/with statement exits
1009 the patch is undone.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001010
Michael Foord54b3db82012-03-28 15:08:08 +01001011 If `new` is omitted, then the target is replaced with a
1012 :class:`MagicMock`. If `patch` is used as a decorator and `new` is
1013 omitted, the created mock is passed in as an extra argument to the
1014 decorated function. If `patch` is used as a context manager the created
1015 mock is returned by the context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001016
Michael Foord54b3db82012-03-28 15:08:08 +01001017 `target` should be a string in the form `'package.module.ClassName'`. The
1018 `target` is imported and the specified object replaced with the `new`
1019 object, so the `target` must be importable from the environment you are
1020 calling `patch` from. The target is imported when the decorated function
1021 is executed, not at decoration time.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001022
1023 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1024 if patch is creating one for you.
1025
1026 In addition you can pass `spec=True` or `spec_set=True`, which causes
1027 patch to pass in the object being mocked as the spec/spec_set object.
1028
1029 `new_callable` allows you to specify a different class, or callable object,
1030 that will be called to create the `new` object. By default `MagicMock` is
1031 used.
1032
1033 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1034 then the mock with be created with a spec from the object being replaced.
1035 All attributes of the mock will also have the spec of the corresponding
1036 attribute of the object being replaced. Methods and functions being mocked
1037 will have their arguments checked and will raise a `TypeError` if they are
1038 called with the wrong signature. For mocks
1039 replacing a class, their return value (the 'instance') will have the same
1040 spec as the class. See the :func:`create_autospec` function and
1041 :ref:`auto-speccing`.
1042
1043 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1044 arbitrary object as the spec instead of the one being replaced.
1045
1046 By default `patch` will fail to replace attributes that don't exist. If
1047 you pass in `create=True`, and the attribute doesn't exist, patch will
1048 create the attribute for you when the patched function is called, and
1049 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001050 attributes that your production code creates at runtime. It is off by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001051 default because it can be dangerous. With it switched on you can write
1052 passing tests against APIs that don't actually exist!
1053
Michael Foordfddcfa22014-04-14 16:25:20 -04001054 .. note::
1055
1056 .. versionchanged:: 3.5
1057 If you are patching builtins in a module then you don't
1058 need to pass `create=True`, it will be added by default.
1059
Michael Foorda9e6fb22012-03-28 14:36:02 +01001060 Patch can be used as a `TestCase` class decorator. It works by
1061 decorating each test method in the class. This reduces the boilerplate
1062 code when your test methods share a common patchings set. `patch` finds
1063 tests by looking for method names that start with `patch.TEST_PREFIX`.
1064 By default this is `test`, which matches the way `unittest` finds tests.
1065 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1066
1067 Patch can be used as a context manager, with the with statement. Here the
1068 patching applies to the indented block after the with statement. If you
1069 use "as" then the patched object will be bound to the name after the
1070 "as"; very useful if `patch` is creating a mock object for you.
1071
1072 `patch` takes arbitrary keyword arguments. These will be passed to
1073 the `Mock` (or `new_callable`) on construction.
1074
1075 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1076 available for alternate use-cases.
1077
Michael Foord90155362012-03-28 15:32:08 +01001078`patch` as function decorator, creating the mock for you and passing it into
1079the decorated function:
1080
1081 >>> @patch('__main__.SomeClass')
Michael Foord324b58b2012-03-28 15:49:08 +01001082 ... def function(normal_argument, mock_class):
Michael Foord90155362012-03-28 15:32:08 +01001083 ... print(mock_class is SomeClass)
1084 ...
Michael Foord324b58b2012-03-28 15:49:08 +01001085 >>> function(None)
Michael Foord90155362012-03-28 15:32:08 +01001086 True
Michael Foorda9e6fb22012-03-28 14:36:02 +01001087
1088Patching a class replaces the class with a `MagicMock` *instance*. If the
1089class is instantiated in the code under test then it will be the
1090:attr:`~Mock.return_value` of the mock that will be used.
1091
1092If the class is instantiated multiple times you could use
1093:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
1094can set the `return_value` to be anything you want.
1095
1096To configure return values on methods of *instances* on the patched class
1097you must do this on the `return_value`. For example:
1098
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001099 >>> class Class:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001100 ... def method(self):
1101 ... pass
1102 ...
1103 >>> with patch('__main__.Class') as MockClass:
1104 ... instance = MockClass.return_value
1105 ... instance.method.return_value = 'foo'
1106 ... assert Class() is instance
1107 ... assert Class().method() == 'foo'
1108 ...
1109
1110If you use `spec` or `spec_set` and `patch` is replacing a *class*, then the
1111return value of the created mock will have the same spec.
1112
1113 >>> Original = Class
1114 >>> patcher = patch('__main__.Class', spec=True)
1115 >>> MockClass = patcher.start()
1116 >>> instance = MockClass()
1117 >>> assert isinstance(instance, Original)
1118 >>> patcher.stop()
1119
1120The `new_callable` argument is useful where you want to use an alternative
1121class to the default :class:`MagicMock` for the created mock. For example, if
1122you wanted a :class:`NonCallableMock` to be used:
1123
1124 >>> thing = object()
1125 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
1126 ... assert thing is mock_thing
1127 ... thing()
1128 ...
1129 Traceback (most recent call last):
1130 ...
1131 TypeError: 'NonCallableMock' object is not callable
1132
Serhiy Storchakae79be872013-08-17 00:09:55 +03001133Another use case might be to replace an object with a `io.StringIO` instance:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001134
Serhiy Storchakae79be872013-08-17 00:09:55 +03001135 >>> from io import StringIO
Michael Foorda9e6fb22012-03-28 14:36:02 +01001136 >>> def foo():
1137 ... print 'Something'
1138 ...
1139 >>> @patch('sys.stdout', new_callable=StringIO)
1140 ... def test(mock_stdout):
1141 ... foo()
1142 ... assert mock_stdout.getvalue() == 'Something\n'
1143 ...
1144 >>> test()
1145
1146When `patch` is creating a mock for you, it is common that the first thing
1147you need to do is to configure the mock. Some of that configuration can be done
1148in the call to patch. Any arbitrary keywords you pass into the call will be
1149used to set attributes on the created mock:
1150
1151 >>> patcher = patch('__main__.thing', first='one', second='two')
1152 >>> mock_thing = patcher.start()
1153 >>> mock_thing.first
1154 'one'
1155 >>> mock_thing.second
1156 'two'
1157
1158As well as attributes on the created mock attributes, like the
1159:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
1160also be configured. These aren't syntactically valid to pass in directly as
1161keyword arguments, but a dictionary with these as keys can still be expanded
1162into a `patch` call using `**`:
1163
1164 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
1165 >>> patcher = patch('__main__.thing', **config)
1166 >>> mock_thing = patcher.start()
1167 >>> mock_thing.method()
1168 3
1169 >>> mock_thing.other()
1170 Traceback (most recent call last):
1171 ...
1172 KeyError
1173
1174
1175patch.object
Georg Brandlfb134382013-02-03 11:47:49 +01001176~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001177
1178.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1179
1180 patch the named member (`attribute`) on an object (`target`) with a mock
1181 object.
1182
1183 `patch.object` can be used as a decorator, class decorator or a context
1184 manager. Arguments `new`, `spec`, `create`, `spec_set`, `autospec` and
1185 `new_callable` have the same meaning as for `patch`. Like `patch`,
1186 `patch.object` takes arbitrary keyword arguments for configuring the mock
1187 object it creates.
1188
1189 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1190 for choosing which methods to wrap.
1191
1192You can either call `patch.object` with three arguments or two arguments. The
1193three argument form takes the object to be patched, the attribute name and the
1194object to replace the attribute with.
1195
1196When calling with the two argument form you omit the replacement object, and a
1197mock is created for you and passed in as an extra argument to the decorated
1198function:
1199
1200 >>> @patch.object(SomeClass, 'class_method')
1201 ... def test(mock_method):
1202 ... SomeClass.class_method(3)
1203 ... mock_method.assert_called_with(3)
1204 ...
1205 >>> test()
1206
1207`spec`, `create` and the other arguments to `patch.object` have the same
1208meaning as they do for `patch`.
1209
1210
1211patch.dict
Georg Brandlfb134382013-02-03 11:47:49 +01001212~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001213
1214.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
1215
1216 Patch a dictionary, or dictionary like object, and restore the dictionary
1217 to its original state after the test.
1218
1219 `in_dict` can be a dictionary or a mapping like container. If it is a
1220 mapping then it must at least support getting, setting and deleting items
1221 plus iterating over keys.
1222
1223 `in_dict` can also be a string specifying the name of the dictionary, which
1224 will then be fetched by importing it.
1225
1226 `values` can be a dictionary of values to set in the dictionary. `values`
1227 can also be an iterable of `(key, value)` pairs.
1228
Serhiy Storchakafbc1c262013-11-29 12:17:13 +02001229 If `clear` is true then the dictionary will be cleared before the new
Michael Foorda9e6fb22012-03-28 14:36:02 +01001230 values are set.
1231
1232 `patch.dict` can also be called with arbitrary keyword arguments to set
1233 values in the dictionary.
1234
1235 `patch.dict` can be used as a context manager, decorator or class
1236 decorator. When used as a class decorator `patch.dict` honours
1237 `patch.TEST_PREFIX` for choosing which methods to wrap.
1238
1239`patch.dict` can be used to add members to a dictionary, or simply let a test
1240change a dictionary, and ensure the dictionary is restored when the test
1241ends.
1242
1243 >>> foo = {}
1244 >>> with patch.dict(foo, {'newkey': 'newvalue'}):
1245 ... assert foo == {'newkey': 'newvalue'}
1246 ...
1247 >>> assert foo == {}
1248
1249 >>> import os
1250 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
1251 ... print os.environ['newkey']
1252 ...
1253 newvalue
1254 >>> assert 'newkey' not in os.environ
1255
1256Keywords can be used in the `patch.dict` call to set values in the dictionary:
1257
1258 >>> mymodule = MagicMock()
1259 >>> mymodule.function.return_value = 'fish'
1260 >>> with patch.dict('sys.modules', mymodule=mymodule):
1261 ... import mymodule
1262 ... mymodule.function('some', 'args')
1263 ...
1264 'fish'
1265
1266`patch.dict` can be used with dictionary like objects that aren't actually
1267dictionaries. At the very minimum they must support item getting, setting,
1268deleting and either iteration or membership test. This corresponds to the
1269magic methods `__getitem__`, `__setitem__`, `__delitem__` and either
1270`__iter__` or `__contains__`.
1271
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001272 >>> class Container:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001273 ... def __init__(self):
1274 ... self.values = {}
1275 ... def __getitem__(self, name):
1276 ... return self.values[name]
1277 ... def __setitem__(self, name, value):
1278 ... self.values[name] = value
1279 ... def __delitem__(self, name):
1280 ... del self.values[name]
1281 ... def __iter__(self):
1282 ... return iter(self.values)
1283 ...
1284 >>> thing = Container()
1285 >>> thing['one'] = 1
1286 >>> with patch.dict(thing, one=2, two=3):
1287 ... assert thing['one'] == 2
1288 ... assert thing['two'] == 3
1289 ...
1290 >>> assert thing['one'] == 1
1291 >>> assert list(thing) == ['one']
1292
1293
1294patch.multiple
Georg Brandlfb134382013-02-03 11:47:49 +01001295~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001296
1297.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1298
1299 Perform multiple patches in a single call. It takes the object to be
1300 patched (either as an object or a string to fetch the object by importing)
1301 and keyword arguments for the patches::
1302
1303 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1304 ...
1305
1306 Use :data:`DEFAULT` as the value if you want `patch.multiple` to create
1307 mocks for you. In this case the created mocks are passed into a decorated
1308 function by keyword, and a dictionary is returned when `patch.multiple` is
1309 used as a context manager.
1310
1311 `patch.multiple` can be used as a decorator, class decorator or a context
1312 manager. The arguments `spec`, `spec_set`, `create`, `autospec` and
1313 `new_callable` have the same meaning as for `patch`. These arguments will
1314 be applied to *all* patches done by `patch.multiple`.
1315
1316 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1317 for choosing which methods to wrap.
1318
1319If you want `patch.multiple` to create mocks for you, then you can use
1320:data:`DEFAULT` as the value. If you use `patch.multiple` as a decorator
1321then the created mocks are passed into the decorated function by keyword.
1322
1323 >>> thing = object()
1324 >>> other = object()
1325
1326 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1327 ... def test_function(thing, other):
1328 ... assert isinstance(thing, MagicMock)
1329 ... assert isinstance(other, MagicMock)
1330 ...
1331 >>> test_function()
1332
1333`patch.multiple` can be nested with other `patch` decorators, but put arguments
1334passed by keyword *after* any of the standard arguments created by `patch`:
1335
1336 >>> @patch('sys.exit')
1337 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1338 ... def test_function(mock_exit, other, thing):
1339 ... assert 'other' in repr(other)
1340 ... assert 'thing' in repr(thing)
1341 ... assert 'exit' in repr(mock_exit)
1342 ...
1343 >>> test_function()
1344
1345If `patch.multiple` is used as a context manager, the value returned by the
1346context manger is a dictionary where created mocks are keyed by name:
1347
1348 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1349 ... assert 'other' in repr(values['other'])
1350 ... assert 'thing' in repr(values['thing'])
1351 ... assert values['thing'] is thing
1352 ... assert values['other'] is other
1353 ...
1354
1355
1356.. _start-and-stop:
1357
1358patch methods: start and stop
Georg Brandlfb134382013-02-03 11:47:49 +01001359~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001360
1361All the patchers have `start` and `stop` methods. These make it simpler to do
1362patching in `setUp` methods or where you want to do multiple patches without
1363nesting decorators or with statements.
1364
1365To use them call `patch`, `patch.object` or `patch.dict` as normal and keep a
1366reference to the returned `patcher` object. You can then call `start` to put
1367the patch in place and `stop` to undo it.
1368
1369If you are using `patch` to create a mock for you then it will be returned by
1370the call to `patcher.start`.
1371
1372 >>> patcher = patch('package.module.ClassName')
1373 >>> from package import module
1374 >>> original = module.ClassName
1375 >>> new_mock = patcher.start()
1376 >>> assert module.ClassName is not original
1377 >>> assert module.ClassName is new_mock
1378 >>> patcher.stop()
1379 >>> assert module.ClassName is original
1380 >>> assert module.ClassName is not new_mock
1381
1382
1383A typical use case for this might be for doing multiple patches in the `setUp`
1384method of a `TestCase`:
1385
1386 >>> class MyTest(TestCase):
1387 ... def setUp(self):
1388 ... self.patcher1 = patch('package.module.Class1')
1389 ... self.patcher2 = patch('package.module.Class2')
1390 ... self.MockClass1 = self.patcher1.start()
1391 ... self.MockClass2 = self.patcher2.start()
1392 ...
1393 ... def tearDown(self):
1394 ... self.patcher1.stop()
1395 ... self.patcher2.stop()
1396 ...
1397 ... def test_something(self):
1398 ... assert package.module.Class1 is self.MockClass1
1399 ... assert package.module.Class2 is self.MockClass2
1400 ...
1401 >>> MyTest('test_something').run()
1402
1403.. caution::
1404
1405 If you use this technique you must ensure that the patching is "undone" by
1406 calling `stop`. This can be fiddlier than you might think, because if an
1407 exception is raised in the ``setUp`` then ``tearDown`` is not called.
1408 :meth:`unittest.TestCase.addCleanup` makes this easier:
1409
1410 >>> class MyTest(TestCase):
1411 ... def setUp(self):
1412 ... patcher = patch('package.module.Class')
1413 ... self.MockClass = patcher.start()
1414 ... self.addCleanup(patcher.stop)
1415 ...
1416 ... def test_something(self):
1417 ... assert package.module.Class is self.MockClass
1418 ...
1419
1420 As an added bonus you no longer need to keep a reference to the `patcher`
1421 object.
1422
Michael Foordf7c41582012-06-10 20:36:32 +01001423It is also possible to stop all patches which have been started by using
1424`patch.stopall`.
1425
1426.. function:: patch.stopall
1427
Michael Foord911fd322012-06-10 20:38:54 +01001428 Stop all active patches. Only stops patches started with `start`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001429
Michael Foordfddcfa22014-04-14 16:25:20 -04001430.. patch-builtins:
1431
1432patch builtins
1433~~~~~~~~~~~~~~~
1434You can patch any builtins within a module. The following example patches
1435builtin `ord`:
1436
1437 >>> @patch('__main__.ord')
1438 ... def test(mock_ord):
1439 ... mock_ord.return_value = 101
1440 ... print(ord('c'))
1441 ...
1442 >>> test()
1443 101
1444
Michael Foorda9e6fb22012-03-28 14:36:02 +01001445
1446TEST_PREFIX
Georg Brandlfb134382013-02-03 11:47:49 +01001447~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001448
1449All of the patchers can be used as class decorators. When used in this way
1450they wrap every test method on the class. The patchers recognise methods that
1451start with `test` as being test methods. This is the same way that the
1452:class:`unittest.TestLoader` finds test methods by default.
1453
1454It is possible that you want to use a different prefix for your tests. You can
1455inform the patchers of the different prefix by setting `patch.TEST_PREFIX`:
1456
1457 >>> patch.TEST_PREFIX = 'foo'
1458 >>> value = 3
1459 >>>
1460 >>> @patch('__main__.value', 'not three')
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001461 ... class Thing:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001462 ... def foo_one(self):
1463 ... print value
1464 ... def foo_two(self):
1465 ... print value
1466 ...
1467 >>>
1468 >>> Thing().foo_one()
1469 not three
1470 >>> Thing().foo_two()
1471 not three
1472 >>> value
1473 3
1474
1475
1476Nesting Patch Decorators
Georg Brandlfb134382013-02-03 11:47:49 +01001477~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001478
1479If you want to perform multiple patches then you can simply stack up the
1480decorators.
1481
1482You can stack up multiple patch decorators using this pattern:
1483
1484 >>> @patch.object(SomeClass, 'class_method')
1485 ... @patch.object(SomeClass, 'static_method')
1486 ... def test(mock1, mock2):
1487 ... assert SomeClass.static_method is mock1
1488 ... assert SomeClass.class_method is mock2
1489 ... SomeClass.static_method('foo')
1490 ... SomeClass.class_method('bar')
1491 ... return mock1, mock2
1492 ...
1493 >>> mock1, mock2 = test()
1494 >>> mock1.assert_called_once_with('foo')
1495 >>> mock2.assert_called_once_with('bar')
1496
1497
1498Note that the decorators are applied from the bottom upwards. This is the
1499standard way that Python applies decorators. The order of the created mocks
1500passed into your test function matches this order.
1501
1502
1503.. _where-to-patch:
1504
1505Where to patch
Georg Brandlfb134382013-02-03 11:47:49 +01001506~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001507
1508`patch` works by (temporarily) changing the object that a *name* points to with
1509another one. There can be many names pointing to any individual object, so
1510for patching to work you must ensure that you patch the name used by the system
1511under test.
1512
1513The basic principle is that you patch where an object is *looked up*, which
1514is not necessarily the same place as where it is defined. A couple of
1515examples will help to clarify this.
1516
1517Imagine we have a project that we want to test with the following structure::
1518
1519 a.py
1520 -> Defines SomeClass
1521
1522 b.py
1523 -> from a import SomeClass
1524 -> some_function instantiates SomeClass
1525
1526Now we want to test `some_function` but we want to mock out `SomeClass` using
1527`patch`. The problem is that when we import module b, which we will have to
1528do then it imports `SomeClass` from module a. If we use `patch` to mock out
1529`a.SomeClass` then it will have no effect on our test; module b already has a
1530reference to the *real* `SomeClass` and it looks like our patching had no
1531effect.
1532
1533The key is to patch out `SomeClass` where it is used (or where it is looked up
1534). In this case `some_function` will actually look up `SomeClass` in module b,
1535where we have imported it. The patching should look like::
1536
1537 @patch('b.SomeClass')
1538
1539However, consider the alternative scenario where instead of `from a import
1540SomeClass` module b does `import a` and `some_function` uses `a.SomeClass`. Both
1541of these import forms are common. In this case the class we want to patch is
1542being looked up on the a module and so we have to patch `a.SomeClass` instead::
1543
1544 @patch('a.SomeClass')
1545
1546
1547Patching Descriptors and Proxy Objects
Georg Brandlfb134382013-02-03 11:47:49 +01001548~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001549
1550Both patch_ and patch.object_ correctly patch and restore descriptors: class
1551methods, static methods and properties. You should patch these on the *class*
1552rather than an instance. They also work with *some* objects
Zachary Ware5ea5d2c2014-02-26 09:34:43 -06001553that proxy attribute access, like the `django settings object
Michael Foorda9e6fb22012-03-28 14:36:02 +01001554<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
1555
1556
Michael Foord2309ed82012-03-28 15:38:36 +01001557MagicMock and magic method support
Georg Brandlfb134382013-02-03 11:47:49 +01001558----------------------------------
Michael Foord2309ed82012-03-28 15:38:36 +01001559
1560.. _magic-methods:
1561
1562Mocking Magic Methods
Georg Brandlfb134382013-02-03 11:47:49 +01001563~~~~~~~~~~~~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001564
1565:class:`Mock` supports mocking the Python protocol methods, also known as
1566"magic methods". This allows mock objects to replace containers or other
1567objects that implement Python protocols.
1568
1569Because magic methods are looked up differently from normal methods [#]_, this
1570support has been specially implemented. This means that only specific magic
1571methods are supported. The supported list includes *almost* all of them. If
1572there are any missing that you need please let us know.
1573
1574You mock magic methods by setting the method you are interested in to a function
1575or a mock instance. If you are using a function then it *must* take ``self`` as
1576the first argument [#]_.
1577
1578 >>> def __str__(self):
1579 ... return 'fooble'
1580 ...
1581 >>> mock = Mock()
1582 >>> mock.__str__ = __str__
1583 >>> str(mock)
1584 'fooble'
1585
1586 >>> mock = Mock()
1587 >>> mock.__str__ = Mock()
1588 >>> mock.__str__.return_value = 'fooble'
1589 >>> str(mock)
1590 'fooble'
1591
1592 >>> mock = Mock()
1593 >>> mock.__iter__ = Mock(return_value=iter([]))
1594 >>> list(mock)
1595 []
1596
1597One use case for this is for mocking objects used as context managers in a
1598`with` statement:
1599
1600 >>> mock = Mock()
1601 >>> mock.__enter__ = Mock(return_value='foo')
1602 >>> mock.__exit__ = Mock(return_value=False)
1603 >>> with mock as m:
1604 ... assert m == 'foo'
1605 ...
1606 >>> mock.__enter__.assert_called_with()
1607 >>> mock.__exit__.assert_called_with(None, None, None)
1608
1609Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
1610are recorded in :attr:`~Mock.mock_calls`.
1611
1612.. note::
1613
1614 If you use the `spec` keyword argument to create a mock then attempting to
1615 set a magic method that isn't in the spec will raise an `AttributeError`.
1616
1617The full list of supported magic methods is:
1618
1619* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
1620* ``__dir__``, ``__format__`` and ``__subclasses__``
1621* ``__floor__``, ``__trunc__`` and ``__ceil__``
1622* Comparisons: ``__cmp__``, ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
1623 ``__eq__`` and ``__ne__``
1624* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
1625 ``__contains__``, ``__len__``, ``__iter__``, ``__getslice__``,
1626 ``__setslice__``, ``__reversed__`` and ``__missing__``
1627* Context manager: ``__enter__`` and ``__exit__``
1628* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
1629* The numeric methods (including right hand and in-place variants):
1630 ``__add__``, ``__sub__``, ``__mul__``, ``__div__``,
1631 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
1632 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
1633* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``,
1634 ``__index__`` and ``__coerce__``
1635* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
1636* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
1637 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
1638
1639
1640The following methods exist but are *not* supported as they are either in use
1641by mock, can't be set dynamically, or can cause problems:
1642
1643* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
1644* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
1645
1646
1647
1648Magic Mock
Georg Brandlfb134382013-02-03 11:47:49 +01001649~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001650
1651There are two `MagicMock` variants: `MagicMock` and `NonCallableMagicMock`.
1652
1653
1654.. class:: MagicMock(*args, **kw)
1655
1656 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
1657 of most of the magic methods. You can use ``MagicMock`` without having to
1658 configure the magic methods yourself.
1659
1660 The constructor parameters have the same meaning as for :class:`Mock`.
1661
1662 If you use the `spec` or `spec_set` arguments then *only* magic methods
1663 that exist in the spec will be created.
1664
1665
1666.. class:: NonCallableMagicMock(*args, **kw)
1667
1668 A non-callable version of `MagicMock`.
1669
1670 The constructor parameters have the same meaning as for
1671 :class:`MagicMock`, with the exception of `return_value` and
1672 `side_effect` which have no meaning on a non-callable mock.
1673
1674The magic methods are setup with `MagicMock` objects, so you can configure them
1675and use them in the usual way:
1676
1677 >>> mock = MagicMock()
1678 >>> mock[3] = 'fish'
1679 >>> mock.__setitem__.assert_called_with(3, 'fish')
1680 >>> mock.__getitem__.return_value = 'result'
1681 >>> mock[2]
1682 'result'
1683
1684By default many of the protocol methods are required to return objects of a
1685specific type. These methods are preconfigured with a default return value, so
1686that they can be used without you having to do anything if you aren't interested
1687in the return value. You can still *set* the return value manually if you want
1688to change the default.
1689
1690Methods and their defaults:
1691
1692* ``__lt__``: NotImplemented
1693* ``__gt__``: NotImplemented
1694* ``__le__``: NotImplemented
1695* ``__ge__``: NotImplemented
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001696* ``__int__``: 1
1697* ``__contains__``: False
1698* ``__len__``: 1
1699* ``__iter__``: iter([])
1700* ``__exit__``: False
1701* ``__complex__``: 1j
1702* ``__float__``: 1.0
1703* ``__bool__``: True
1704* ``__index__``: 1
1705* ``__hash__``: default hash for the mock
1706* ``__str__``: default str for the mock
Michael Foord2309ed82012-03-28 15:38:36 +01001707* ``__sizeof__``: default sizeof for the mock
1708
1709For example:
1710
1711 >>> mock = MagicMock()
1712 >>> int(mock)
1713 1
1714 >>> len(mock)
1715 0
1716 >>> list(mock)
1717 []
1718 >>> object() in mock
1719 False
1720
1721The two equality method, `__eq__` and `__ne__`, are special.
1722They do the default equality comparison on identity, using a side
1723effect, unless you change their return value to return something else:
1724
1725 >>> MagicMock() == 3
1726 False
1727 >>> MagicMock() != 3
1728 True
1729 >>> mock = MagicMock()
1730 >>> mock.__eq__.return_value = True
1731 >>> mock == 3
1732 True
1733
1734The return value of `MagicMock.__iter__` can be any iterable object and isn't
1735required to be an iterator:
1736
1737 >>> mock = MagicMock()
1738 >>> mock.__iter__.return_value = ['a', 'b', 'c']
1739 >>> list(mock)
1740 ['a', 'b', 'c']
1741 >>> list(mock)
1742 ['a', 'b', 'c']
1743
1744If the return value *is* an iterator, then iterating over it once will consume
1745it and subsequent iterations will result in an empty list:
1746
1747 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
1748 >>> list(mock)
1749 ['a', 'b', 'c']
1750 >>> list(mock)
1751 []
1752
1753``MagicMock`` has all of the supported magic methods configured except for some
1754of the obscure and obsolete ones. You can still set these up if you want.
1755
1756Magic methods that are supported but not setup by default in ``MagicMock`` are:
1757
1758* ``__subclasses__``
1759* ``__dir__``
1760* ``__format__``
1761* ``__get__``, ``__set__`` and ``__delete__``
1762* ``__reversed__`` and ``__missing__``
1763* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
1764 ``__getstate__`` and ``__setstate__``
1765* ``__getformat__`` and ``__setformat__``
1766
1767
1768
1769.. [#] Magic methods *should* be looked up on the class rather than the
1770 instance. Different versions of Python are inconsistent about applying this
1771 rule. The supported protocol methods should work with all supported versions
1772 of Python.
1773.. [#] The function is basically hooked up to the class, but each ``Mock``
1774 instance is kept isolated from the others.
1775
1776
Michael Foorda9e6fb22012-03-28 14:36:02 +01001777Helpers
Georg Brandlfb134382013-02-03 11:47:49 +01001778-------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001779
1780sentinel
Georg Brandlfb134382013-02-03 11:47:49 +01001781~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001782
1783.. data:: sentinel
1784
1785 The ``sentinel`` object provides a convenient way of providing unique
1786 objects for your tests.
1787
1788 Attributes are created on demand when you access them by name. Accessing
1789 the same attribute will always return the same object. The objects
1790 returned have a sensible repr so that test failure messages are readable.
1791
1792Sometimes when testing you need to test that a specific object is passed as an
1793argument to another method, or returned. It can be common to create named
1794sentinel objects to test this. `sentinel` provides a convenient way of
1795creating and testing the identity of objects like this.
1796
1797In this example we monkey patch `method` to return `sentinel.some_object`:
1798
1799 >>> real = ProductionClass()
1800 >>> real.method = Mock(name="method")
1801 >>> real.method.return_value = sentinel.some_object
1802 >>> result = real.method()
1803 >>> assert result is sentinel.some_object
1804 >>> sentinel.some_object
1805 sentinel.some_object
1806
1807
1808DEFAULT
Georg Brandlfb134382013-02-03 11:47:49 +01001809~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001810
1811
1812.. data:: DEFAULT
1813
1814 The `DEFAULT` object is a pre-created sentinel (actually
1815 `sentinel.DEFAULT`). It can be used by :attr:`~Mock.side_effect`
1816 functions to indicate that the normal return value should be used.
1817
1818
Michael Foorda9e6fb22012-03-28 14:36:02 +01001819call
Georg Brandlfb134382013-02-03 11:47:49 +01001820~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001821
1822.. function:: call(*args, **kwargs)
1823
Georg Brandl24891672012-04-01 13:48:26 +02001824 `call` is a helper object for making simpler assertions, for comparing with
1825 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
1826 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. `call` can also be
Michael Foorda9e6fb22012-03-28 14:36:02 +01001827 used with :meth:`~Mock.assert_has_calls`.
1828
1829 >>> m = MagicMock(return_value=None)
1830 >>> m(1, 2, a='foo', b='bar')
1831 >>> m()
1832 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
1833 True
1834
1835.. method:: call.call_list()
1836
1837 For a call object that represents multiple calls, `call_list`
1838 returns a list of all the intermediate calls as well as the
1839 final call.
1840
1841`call_list` is particularly useful for making assertions on "chained calls". A
1842chained call is multiple calls on a single line of code. This results in
1843multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
1844the sequence of calls can be tedious.
1845
1846:meth:`~call.call_list` can construct the sequence of calls from the same
1847chained call:
1848
1849 >>> m = MagicMock()
1850 >>> m(1).method(arg='foo').other('bar')(2.0)
1851 <MagicMock name='mock().method().other()()' id='...'>
1852 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
1853 >>> kall.call_list()
1854 [call(1),
1855 call().method(arg='foo'),
1856 call().method().other('bar'),
1857 call().method().other()(2.0)]
1858 >>> m.mock_calls == kall.call_list()
1859 True
1860
1861.. _calls-as-tuples:
1862
1863A `call` object is either a tuple of (positional args, keyword args) or
1864(name, positional args, keyword args) depending on how it was constructed. When
1865you construct them yourself this isn't particularly interesting, but the `call`
1866objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
1867:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
1868arguments they contain.
1869
1870The `call` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
1871are two-tuples of (positional args, keyword args) whereas the `call` objects
1872in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
1873three-tuples of (name, positional args, keyword args).
1874
1875You can use their "tupleness" to pull out the individual arguments for more
1876complex introspection and assertions. The positional arguments are a tuple
1877(an empty tuple if there are no positional arguments) and the keyword
1878arguments are a dictionary:
1879
1880 >>> m = MagicMock(return_value=None)
1881 >>> m(1, 2, 3, arg='one', arg2='two')
1882 >>> kall = m.call_args
1883 >>> args, kwargs = kall
1884 >>> args
1885 (1, 2, 3)
1886 >>> kwargs
1887 {'arg2': 'two', 'arg': 'one'}
1888 >>> args is kall[0]
1889 True
1890 >>> kwargs is kall[1]
1891 True
1892
1893 >>> m = MagicMock()
1894 >>> m.foo(4, 5, 6, arg='two', arg2='three')
1895 <MagicMock name='mock.foo()' id='...'>
1896 >>> kall = m.mock_calls[0]
1897 >>> name, args, kwargs = kall
1898 >>> name
1899 'foo'
1900 >>> args
1901 (4, 5, 6)
1902 >>> kwargs
1903 {'arg2': 'three', 'arg': 'two'}
1904 >>> name is m.mock_calls[0][0]
1905 True
1906
1907
1908create_autospec
Georg Brandlfb134382013-02-03 11:47:49 +01001909~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001910
1911.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
1912
1913 Create a mock object using another object as a spec. Attributes on the
1914 mock will use the corresponding attribute on the `spec` object as their
1915 spec.
1916
1917 Functions or methods being mocked will have their arguments checked to
1918 ensure that they are called with the correct signature.
1919
1920 If `spec_set` is `True` then attempting to set attributes that don't exist
1921 on the spec object will raise an `AttributeError`.
1922
1923 If a class is used as a spec then the return value of the mock (the
1924 instance of the class) will have the same spec. You can use a class as the
1925 spec for an instance object by passing `instance=True`. The returned mock
1926 will only be callable if instances of the mock are callable.
1927
1928 `create_autospec` also takes arbitrary keyword arguments that are passed to
1929 the constructor of the created mock.
1930
1931See :ref:`auto-speccing` for examples of how to use auto-speccing with
1932`create_autospec` and the `autospec` argument to :func:`patch`.
1933
1934
1935ANY
Georg Brandlfb134382013-02-03 11:47:49 +01001936~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001937
1938.. data:: ANY
1939
1940Sometimes you may need to make assertions about *some* of the arguments in a
1941call to mock, but either not care about some of the arguments or want to pull
1942them individually out of :attr:`~Mock.call_args` and make more complex
1943assertions on them.
1944
1945To ignore certain arguments you can pass in objects that compare equal to
1946*everything*. Calls to :meth:`~Mock.assert_called_with` and
1947:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
1948passed in.
1949
1950 >>> mock = Mock(return_value=None)
1951 >>> mock('foo', bar=object())
1952 >>> mock.assert_called_once_with('foo', bar=ANY)
1953
1954`ANY` can also be used in comparisons with call lists like
1955:attr:`~Mock.mock_calls`:
1956
1957 >>> m = MagicMock(return_value=None)
1958 >>> m(1)
1959 >>> m(1, 2)
1960 >>> m(object())
1961 >>> m.mock_calls == [call(1), call(1, 2), ANY]
1962 True
1963
1964
1965
1966FILTER_DIR
Georg Brandlfb134382013-02-03 11:47:49 +01001967~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001968
1969.. data:: FILTER_DIR
1970
1971`FILTER_DIR` is a module level variable that controls the way mock objects
1972respond to `dir` (only for Python 2.6 or more recent). The default is `True`,
1973which uses the filtering described below, to only show useful members. If you
1974dislike this filtering, or need to switch it off for diagnostic purposes, then
1975set `mock.FILTER_DIR = False`.
1976
1977With filtering on, `dir(some_mock)` shows only useful attributes and will
1978include any dynamically created attributes that wouldn't normally be shown.
1979If the mock was created with a `spec` (or `autospec` of course) then all the
1980attributes from the original are shown, even if they haven't been accessed
1981yet:
1982
1983 >>> dir(Mock())
1984 ['assert_any_call',
1985 'assert_called_once_with',
1986 'assert_called_with',
1987 'assert_has_calls',
1988 'attach_mock',
1989 ...
1990 >>> from urllib import request
1991 >>> dir(Mock(spec=request))
1992 ['AbstractBasicAuthHandler',
1993 'AbstractDigestAuthHandler',
1994 'AbstractHTTPHandler',
1995 'BaseHandler',
1996 ...
1997
1998Many of the not-very-useful (private to `Mock` rather than the thing being
1999mocked) underscore and double underscore prefixed attributes have been
2000filtered from the result of calling `dir` on a `Mock`. If you dislike this
2001behaviour you can switch it off by setting the module level switch
2002`FILTER_DIR`:
2003
2004 >>> from unittest import mock
2005 >>> mock.FILTER_DIR = False
2006 >>> dir(mock.Mock())
2007 ['_NonCallableMock__get_return_value',
2008 '_NonCallableMock__get_side_effect',
2009 '_NonCallableMock__return_value_doc',
2010 '_NonCallableMock__set_return_value',
2011 '_NonCallableMock__set_side_effect',
2012 '__call__',
2013 '__class__',
2014 ...
2015
2016Alternatively you can just use `vars(my_mock)` (instance members) and
2017`dir(type(my_mock))` (type members) to bypass the filtering irrespective of
2018`mock.FILTER_DIR`.
2019
2020
2021mock_open
Georg Brandlfb134382013-02-03 11:47:49 +01002022~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002023
2024.. function:: mock_open(mock=None, read_data=None)
2025
2026 A helper function to create a mock to replace the use of `open`. It works
2027 for `open` called directly or used as a context manager.
2028
2029 The `mock` argument is the mock object to configure. If `None` (the
2030 default) then a `MagicMock` will be created for you, with the API limited
2031 to methods or attributes available on standard file handles.
2032
Serhiy Storchaka98b28fd2013-10-13 23:12:09 +03002033 `read_data` is a string for the :meth:`~io.IOBase.read`,
2034 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
Michael Foord04cbe0c2013-03-19 17:22:51 -07002035 of the file handle to return. Calls to those methods will take data from
2036 `read_data` until it is depleted. The mock of these methods is pretty
2037 simplistic. If you need more control over the data that you are feeding to
2038 the tested code you will need to customize this mock for yourself.
2039 `read_data` is an empty string by default.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002040
2041Using `open` as a context manager is a great way to ensure your file handles
2042are closed properly and is becoming common::
2043
2044 with open('/some/path', 'w') as f:
2045 f.write('something')
2046
2047The issue is that even if you mock out the call to `open` it is the
2048*returned object* that is used as a context manager (and has `__enter__` and
2049`__exit__` called).
2050
2051Mocking context managers with a :class:`MagicMock` is common enough and fiddly
2052enough that a helper function is useful.
2053
2054 >>> m = mock_open()
Michael Foordfddcfa22014-04-14 16:25:20 -04002055 >>> with patch('__main__.open', m):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002056 ... with open('foo', 'w') as h:
2057 ... h.write('some stuff')
2058 ...
2059 >>> m.mock_calls
2060 [call('foo', 'w'),
2061 call().__enter__(),
2062 call().write('some stuff'),
2063 call().__exit__(None, None, None)]
2064 >>> m.assert_called_once_with('foo', 'w')
2065 >>> handle = m()
2066 >>> handle.write.assert_called_once_with('some stuff')
2067
2068And for reading files:
2069
Michael Foordfddcfa22014-04-14 16:25:20 -04002070 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002071 ... with open('foo') as h:
2072 ... result = h.read()
2073 ...
2074 >>> m.assert_called_once_with('foo')
2075 >>> assert result == 'bibble'
2076
2077
2078.. _auto-speccing:
2079
2080Autospeccing
Georg Brandlfb134382013-02-03 11:47:49 +01002081~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002082
2083Autospeccing is based on the existing `spec` feature of mock. It limits the
2084api of mocks to the api of an original object (the spec), but it is recursive
2085(implemented lazily) so that attributes of mocks only have the same api as
2086the attributes of the spec. In addition mocked functions / methods have the
2087same call signature as the original so they raise a `TypeError` if they are
2088called incorrectly.
2089
2090Before I explain how auto-speccing works, here's why it is needed.
2091
2092`Mock` is a very powerful and flexible object, but it suffers from two flaws
2093when used to mock out objects from a system under test. One of these flaws is
2094specific to the `Mock` api and the other is a more general problem with using
2095mock objects.
2096
2097First the problem specific to `Mock`. `Mock` has two assert methods that are
2098extremely handy: :meth:`~Mock.assert_called_with` and
2099:meth:`~Mock.assert_called_once_with`.
2100
2101 >>> mock = Mock(name='Thing', return_value=None)
2102 >>> mock(1, 2, 3)
2103 >>> mock.assert_called_once_with(1, 2, 3)
2104 >>> mock(1, 2, 3)
2105 >>> mock.assert_called_once_with(1, 2, 3)
2106 Traceback (most recent call last):
2107 ...
Michael Foord28d591c2012-09-28 16:15:22 +01002108 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002109
2110Because mocks auto-create attributes on demand, and allow you to call them
2111with arbitrary arguments, if you misspell one of these assert methods then
2112your assertion is gone:
2113
2114.. code-block:: pycon
2115
2116 >>> mock = Mock(name='Thing', return_value=None)
2117 >>> mock(1, 2, 3)
2118 >>> mock.assret_called_once_with(4, 5, 6)
2119
2120Your tests can pass silently and incorrectly because of the typo.
2121
2122The second issue is more general to mocking. If you refactor some of your
2123code, rename members and so on, any tests for code that is still using the
2124*old api* but uses mocks instead of the real objects will still pass. This
2125means your tests can all pass even though your code is broken.
2126
2127Note that this is another reason why you need integration tests as well as
2128unit tests. Testing everything in isolation is all fine and dandy, but if you
2129don't test how your units are "wired together" there is still lots of room
2130for bugs that tests might have caught.
2131
2132`mock` already provides a feature to help with this, called speccing. If you
2133use a class or instance as the `spec` for a mock then you can only access
2134attributes on the mock that exist on the real class:
2135
2136 >>> from urllib import request
2137 >>> mock = Mock(spec=request.Request)
2138 >>> mock.assret_called_with
2139 Traceback (most recent call last):
2140 ...
2141 AttributeError: Mock object has no attribute 'assret_called_with'
2142
2143The spec only applies to the mock itself, so we still have the same issue
2144with any methods on the mock:
2145
2146.. code-block:: pycon
2147
2148 >>> mock.has_data()
2149 <mock.Mock object at 0x...>
2150 >>> mock.has_data.assret_called_with()
2151
2152Auto-speccing solves this problem. You can either pass `autospec=True` to
2153`patch` / `patch.object` or use the `create_autospec` function to create a
2154mock with a spec. If you use the `autospec=True` argument to `patch` then the
2155object that is being replaced will be used as the spec object. Because the
2156speccing is done "lazily" (the spec is created as attributes on the mock are
2157accessed) you can use it with very complex or deeply nested objects (like
2158modules that import modules that import modules) without a big performance
2159hit.
2160
2161Here's an example of it in use:
2162
2163 >>> from urllib import request
2164 >>> patcher = patch('__main__.request', autospec=True)
2165 >>> mock_request = patcher.start()
2166 >>> request is mock_request
2167 True
2168 >>> mock_request.Request
2169 <MagicMock name='request.Request' spec='Request' id='...'>
2170
2171You can see that `request.Request` has a spec. `request.Request` takes two
2172arguments in the constructor (one of which is `self`). Here's what happens if
2173we try to call it incorrectly:
2174
2175 >>> req = request.Request()
2176 Traceback (most recent call last):
2177 ...
2178 TypeError: <lambda>() takes at least 2 arguments (1 given)
2179
2180The spec also applies to instantiated classes (i.e. the return value of
2181specced mocks):
2182
2183 >>> req = request.Request('foo')
2184 >>> req
2185 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2186
2187`Request` objects are not callable, so the return value of instantiating our
2188mocked out `request.Request` is a non-callable mock. With the spec in place
2189any typos in our asserts will raise the correct error:
2190
2191 >>> req.add_header('spam', 'eggs')
2192 <MagicMock name='request.Request().add_header()' id='...'>
2193 >>> req.add_header.assret_called_with
2194 Traceback (most recent call last):
2195 ...
2196 AttributeError: Mock object has no attribute 'assret_called_with'
2197 >>> req.add_header.assert_called_with('spam', 'eggs')
2198
2199In many cases you will just be able to add `autospec=True` to your existing
2200`patch` calls and then be protected against bugs due to typos and api
2201changes.
2202
2203As well as using `autospec` through `patch` there is a
2204:func:`create_autospec` for creating autospecced mocks directly:
2205
2206 >>> from urllib import request
2207 >>> mock_request = create_autospec(request)
2208 >>> mock_request.Request('foo', 'bar')
2209 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2210
2211This isn't without caveats and limitations however, which is why it is not
2212the default behaviour. In order to know what attributes are available on the
2213spec object, autospec has to introspect (access attributes) the spec. As you
2214traverse attributes on the mock a corresponding traversal of the original
2215object is happening under the hood. If any of your specced objects have
2216properties or descriptors that can trigger code execution then you may not be
2217able to use autospec. On the other hand it is much better to design your
2218objects so that introspection is safe [#]_.
2219
2220A more serious problem is that it is common for instance attributes to be
2221created in the `__init__` method and not to exist on the class at all.
2222`autospec` can't know about any dynamically created attributes and restricts
2223the api to visible attributes.
2224
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002225 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002226 ... def __init__(self):
2227 ... self.a = 33
2228 ...
2229 >>> with patch('__main__.Something', autospec=True):
2230 ... thing = Something()
2231 ... thing.a
2232 ...
2233 Traceback (most recent call last):
2234 ...
2235 AttributeError: Mock object has no attribute 'a'
2236
2237There are a few different ways of resolving this problem. The easiest, but
2238not necessarily the least annoying, way is to simply set the required
2239attributes on the mock after creation. Just because `autospec` doesn't allow
2240you to fetch attributes that don't exist on the spec it doesn't prevent you
2241setting them:
2242
2243 >>> with patch('__main__.Something', autospec=True):
2244 ... thing = Something()
2245 ... thing.a = 33
2246 ...
2247
2248There is a more aggressive version of both `spec` and `autospec` that *does*
2249prevent you setting non-existent attributes. This is useful if you want to
2250ensure your code only *sets* valid attributes too, but obviously it prevents
2251this particular scenario:
2252
2253 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2254 ... thing = Something()
2255 ... thing.a = 33
2256 ...
2257 Traceback (most recent call last):
2258 ...
2259 AttributeError: Mock object has no attribute 'a'
2260
2261Probably the best way of solving the problem is to add class attributes as
2262default values for instance members initialised in `__init__`. Note that if
2263you are only setting default attributes in `__init__` then providing them via
2264class attributes (shared between instances of course) is faster too. e.g.
2265
2266.. code-block:: python
2267
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002268 class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002269 a = 33
2270
2271This brings up another issue. It is relatively common to provide a default
2272value of `None` for members that will later be an object of a different type.
2273`None` would be useless as a spec because it wouldn't let you access *any*
2274attributes or methods on it. As `None` is *never* going to be useful as a
2275spec, and probably indicates a member that will normally of some other type,
2276`autospec` doesn't use a spec for members that are set to `None`. These will
2277just be ordinary mocks (well - `MagicMocks`):
2278
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002279 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002280 ... member = None
2281 ...
2282 >>> mock = create_autospec(Something)
2283 >>> mock.member.foo.bar.baz()
2284 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2285
2286If modifying your production classes to add defaults isn't to your liking
2287then there are more options. One of these is simply to use an instance as the
2288spec rather than the class. The other is to create a subclass of the
2289production class and add the defaults to the subclass without affecting the
2290production class. Both of these require you to use an alternative object as
2291the spec. Thankfully `patch` supports this - you can simply pass the
2292alternative object as the `autospec` argument:
2293
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002294 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002295 ... def __init__(self):
2296 ... self.a = 33
2297 ...
2298 >>> class SomethingForTest(Something):
2299 ... a = 33
2300 ...
2301 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2302 >>> mock = p.start()
2303 >>> mock.a
2304 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2305
2306
2307.. [#] This only applies to classes or already instantiated objects. Calling
2308 a mocked class to create a mock instance *does not* create a real instance.
2309 It is only attribute lookups - along with calls to `dir` - that are done.
2310