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