blob: 70fe38ac72aa4d6a9bfb91542751b27d92f42d2d [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
Georg Brandl4433ff92014-10-31 07:59:37 +010016:mod:`unittest.mock` provides a core :class:`Mock` class removing the need to
Michael Foord944e02d2012-03-25 23:12:55 +010017create 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
Georg Brandl4433ff92014-10-31 07:59:37 +010029is based on the 'action -> assertion' pattern instead of 'record -> replay'
Michael Foord944e02d2012-03-25 23:12:55 +010030used by many mocking frameworks.
31
Georg Brandl4433ff92014-10-31 07:59:37 +010032There is a backport of :mod:`unittest.mock` for earlier versions of Python,
Georg Brandle73778c2014-10-29 08:36:35 +010033available as `mock on PyPI <https://pypi.python.org/pypi/mock>`_.
Michael Foord944e02d2012-03-25 23:12:55 +010034
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
Georg Brandl4433ff92014-10-31 07:59:37 +010074example the *spec* argument configures the mock to take its specification
Michael Foord944e02d2012-03-25 23:12:55 +010075from another object. Attempting to access attributes or methods on the mock
Georg Brandl4433ff92014-10-31 07:59:37 +010076that don't exist on the spec will fail with an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +010077
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
Georg Brandl4433ff92014-10-31 07:59:37 +0100100 above the mock for ``module.ClassName1`` is passed in first.
Michael Foord944e02d2012-03-25 23:12:55 +0100101
Georg Brandl4433ff92014-10-31 07:59:37 +0100102 With :func:`patch` it matters that you patch objects in the namespace where they
Michael Foord944e02d2012-03-25 23:12:55 +0100103 are looked up. This is normally straightforward, but for a quick guide
104 read :ref:`where to patch <where-to-patch>`.
105
Georg Brandl4433ff92014-10-31 07:59:37 +0100106As well as a decorator :func:`patch` can be used as a context manager in a with
Michael Foord944e02d2012-03-25 23:12:55 +0100107statement:
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
Georg Brandl4433ff92014-10-31 07:59:37 +0100138and they will be called appropriately. The :class:`MagicMock` class is just a Mock
Michael Foord944e02d2012-03-25 23:12:55 +0100139variant 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>`.
Georg Brandl4433ff92014-10-31 07:59:37 +0100152Auto-speccing can be done through the *autospec* argument to patch, or the
Michael Foord944e02d2012-03-25 23:12:55 +0100153: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
Georg Brandl4433ff92014-10-31 07:59:37 +0100174:func:`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.
Michael Foord944e02d2012-03-25 23:12:55 +0100177
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
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
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.
Georg Brandl4433ff92014-10-31 07:59:37 +0100299 The :attr:`mock_calls` list is checked for the calls.
Michael Foord944e02d2012-03-25 23:12:55 +0100300
Georg Brandl4433ff92014-10-31 07:59:37 +0100301 If *any_order* is false (the default) then the calls must be
Michael Foord944e02d2012-03-25 23:12:55 +0100302 sequential. There can be extra calls before or after the
303 specified calls.
304
Georg Brandl4433ff92014-10-31 07:59:37 +0100305 If *any_order* is true then the calls can be in any order, but
Michael Foord944e02d2012-03-25 23:12:55 +0100306 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
Georg Brandl4433ff92014-10-31 07:59:37 +0100332 reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the
Michael Foord944e02d2012-03-25 23:12:55 +0100333 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
Georg Brandl4433ff92014-10-31 07:59:37 +0100340 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
Michael Foord944e02d2012-03-25 23:12:55 +0100342 attributes from the mock.
343
Georg Brandl4433ff92014-10-31 07:59:37 +0100344 If *spec_set* is true then only attributes on the spec can be set.
Michael Foord944e02d2012-03-25 23:12:55 +0100345
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
Georg Brandl4433ff92014-10-31 07:59:37 +0100385 :meth:`configure_mock` exists to make it easier to do configuration
Michael Foord944e02d2012-03-25 23:12:55 +0100386 after the mock has been created.
387
388
389 .. method:: __dir__()
390
Georg Brandl4433ff92014-10-31 07:59:37 +0100391 :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results.
392 For mocks with a *spec* this includes all the permitted attributes
Michael Foord944e02d2012-03-25 23:12:55 +0100393 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
Georg Brandl4433ff92014-10-31 07:59:37 +0100452 :attr:`return_value` can also be set in the constructor:
Michael Foord944e02d2012-03-25 23:12:55 +0100453
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,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100464 an iterable or an exception (class or instance) to be raised.
Michael Foord944e02d2012-03-25 23:12:55 +0100465
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
Brett Cannon533f1ed2013-05-25 11:28:20 -0400470 value (from the :attr:`return_value`).
Michael Foord944e02d2012-03-25 23:12:55 +0100471
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100472 If you pass in an iterable, it is used to retrieve an iterator which
473 must yield a value on every call. This value can either be an exception
474 instance to be raised, or a value to be returned from the call to the
475 mock (:data:`DEFAULT` handling is identical to the function case).
476
Michael Foord944e02d2012-03-25 23:12:55 +0100477 An example of a mock that raises an exception (to test exception
478 handling of an API):
479
480 >>> mock = Mock()
481 >>> mock.side_effect = Exception('Boom!')
482 >>> mock()
483 Traceback (most recent call last):
484 ...
485 Exception: Boom!
486
Georg Brandl4433ff92014-10-31 07:59:37 +0100487 Using :attr:`side_effect` to return a sequence of values:
Michael Foord944e02d2012-03-25 23:12:55 +0100488
489 >>> mock = Mock()
490 >>> mock.side_effect = [3, 2, 1]
491 >>> mock(), mock(), mock()
492 (3, 2, 1)
493
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100494 Using a callable:
Michael Foord944e02d2012-03-25 23:12:55 +0100495
496 >>> mock = Mock(return_value=3)
497 >>> def side_effect(*args, **kwargs):
498 ... return DEFAULT
499 ...
500 >>> mock.side_effect = side_effect
501 >>> mock()
502 3
503
Georg Brandl4433ff92014-10-31 07:59:37 +0100504 :attr:`side_effect` can be set in the constructor. Here's an example that
Michael Foord944e02d2012-03-25 23:12:55 +0100505 adds one to the value the mock is called with and returns it:
506
507 >>> side_effect = lambda value: value + 1
508 >>> mock = Mock(side_effect=side_effect)
509 >>> mock(3)
510 4
511 >>> mock(-8)
512 -7
513
Georg Brandl4433ff92014-10-31 07:59:37 +0100514 Setting :attr:`side_effect` to ``None`` clears it:
Michael Foord944e02d2012-03-25 23:12:55 +0100515
516 >>> m = Mock(side_effect=KeyError, return_value=3)
517 >>> m()
518 Traceback (most recent call last):
519 ...
520 KeyError
521 >>> m.side_effect = None
522 >>> m()
523 3
524
525
526 .. attribute:: call_args
527
Georg Brandl4433ff92014-10-31 07:59:37 +0100528 This is either ``None`` (if the mock hasn't been called), or the
Michael Foord944e02d2012-03-25 23:12:55 +0100529 arguments that the mock was last called with. This will be in the
530 form of a tuple: the first member is any ordered arguments the mock
531 was called with (or an empty tuple) and the second member is any
532 keyword arguments (or an empty dictionary).
533
534 >>> mock = Mock(return_value=None)
535 >>> print mock.call_args
536 None
537 >>> mock()
538 >>> mock.call_args
539 call()
540 >>> mock.call_args == ()
541 True
542 >>> mock(3, 4)
543 >>> mock.call_args
544 call(3, 4)
545 >>> mock.call_args == ((3, 4),)
546 True
547 >>> mock(3, 4, 5, key='fish', next='w00t!')
548 >>> mock.call_args
549 call(3, 4, 5, key='fish', next='w00t!')
550
Georg Brandl4433ff92014-10-31 07:59:37 +0100551 :attr:`call_args`, along with members of the lists :attr:`call_args_list`,
Michael Foord944e02d2012-03-25 23:12:55 +0100552 :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
553 These are tuples, so they can be unpacked to get at the individual
554 arguments and make more complex assertions. See
555 :ref:`calls as tuples <calls-as-tuples>`.
556
557
558 .. attribute:: call_args_list
559
560 This is a list of all the calls made to the mock object in sequence
561 (so the length of the list is the number of times it has been
562 called). Before any calls have been made it is an empty list. The
563 :data:`call` object can be used for conveniently constructing lists of
Georg Brandl4433ff92014-10-31 07:59:37 +0100564 calls to compare with :attr:`call_args_list`.
Michael Foord944e02d2012-03-25 23:12:55 +0100565
566 >>> mock = Mock(return_value=None)
567 >>> mock()
568 >>> mock(3, 4)
569 >>> mock(key='fish', next='w00t!')
570 >>> mock.call_args_list
571 [call(), call(3, 4), call(key='fish', next='w00t!')]
572 >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
573 >>> mock.call_args_list == expected
574 True
575
Georg Brandl4433ff92014-10-31 07:59:37 +0100576 Members of :attr:`call_args_list` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100577 unpacked as tuples to get at the individual arguments. See
578 :ref:`calls as tuples <calls-as-tuples>`.
579
580
581 .. attribute:: method_calls
582
583 As well as tracking calls to themselves, mocks also track calls to
584 methods and attributes, and *their* methods and attributes:
585
586 >>> mock = Mock()
587 >>> mock.method()
588 <Mock name='mock.method()' id='...'>
589 >>> mock.property.method.attribute()
590 <Mock name='mock.property.method.attribute()' id='...'>
591 >>> mock.method_calls
592 [call.method(), call.property.method.attribute()]
593
Georg Brandl4433ff92014-10-31 07:59:37 +0100594 Members of :attr:`method_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100595 unpacked as tuples to get at the individual arguments. See
596 :ref:`calls as tuples <calls-as-tuples>`.
597
598
599 .. attribute:: mock_calls
600
Georg Brandl4433ff92014-10-31 07:59:37 +0100601 :attr:`mock_calls` records *all* calls to the mock object, its methods,
602 magic methods *and* return value mocks.
Michael Foord944e02d2012-03-25 23:12:55 +0100603
604 >>> mock = MagicMock()
605 >>> result = mock(1, 2, 3)
606 >>> mock.first(a=3)
607 <MagicMock name='mock.first()' id='...'>
608 >>> mock.second()
609 <MagicMock name='mock.second()' id='...'>
610 >>> int(mock)
611 1
612 >>> result(1)
613 <MagicMock name='mock()()' id='...'>
614 >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
615 ... call.__int__(), call()(1)]
616 >>> mock.mock_calls == expected
617 True
618
Georg Brandl4433ff92014-10-31 07:59:37 +0100619 Members of :attr:`mock_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100620 unpacked as tuples to get at the individual arguments. See
621 :ref:`calls as tuples <calls-as-tuples>`.
622
623
624 .. attribute:: __class__
625
Georg Brandl4433ff92014-10-31 07:59:37 +0100626 Normally the :attr:`__class__` attribute of an object will return its type.
627 For a mock object with a :attr:`spec`, ``__class__`` returns the spec class
628 instead. This allows mock objects to pass :func:`isinstance` tests for the
Michael Foord944e02d2012-03-25 23:12:55 +0100629 object they are replacing / masquerading as:
630
631 >>> mock = Mock(spec=3)
632 >>> isinstance(mock, int)
633 True
634
Georg Brandl4433ff92014-10-31 07:59:37 +0100635 :attr:`__class__` is assignable to, this allows a mock to pass an
636 :func:`isinstance` check without forcing you to use a spec:
Michael Foord944e02d2012-03-25 23:12:55 +0100637
638 >>> mock = Mock()
639 >>> mock.__class__ = dict
640 >>> isinstance(mock, dict)
641 True
642
643.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
644
Georg Brandl4433ff92014-10-31 07:59:37 +0100645 A non-callable version of :class:`Mock`. The constructor parameters have the same
646 meaning of :class:`Mock`, with the exception of *return_value* and *side_effect*
Michael Foord944e02d2012-03-25 23:12:55 +0100647 which have no meaning on a non-callable mock.
648
Georg Brandl4433ff92014-10-31 07:59:37 +0100649Mock objects that use a class or an instance as a :attr:`spec` or
650:attr:`spec_set` are able to pass :func:`isinstance` tests:
Michael Foord944e02d2012-03-25 23:12:55 +0100651
652 >>> mock = Mock(spec=SomeClass)
653 >>> isinstance(mock, SomeClass)
654 True
655 >>> mock = Mock(spec_set=SomeClass())
656 >>> isinstance(mock, SomeClass)
657 True
658
Georg Brandl4433ff92014-10-31 07:59:37 +0100659The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic
Michael Foord944e02d2012-03-25 23:12:55 +0100660methods <magic-methods>` for the full details.
661
662The mock classes and the :func:`patch` decorators all take arbitrary keyword
Georg Brandl4433ff92014-10-31 07:59:37 +0100663arguments for configuration. For the :func:`patch` decorators the keywords are
Michael Foord944e02d2012-03-25 23:12:55 +0100664passed to the constructor of the mock being created. The keyword arguments
665are for configuring attributes of the mock:
666
667 >>> m = MagicMock(attribute=3, other='fish')
668 >>> m.attribute
669 3
670 >>> m.other
671 'fish'
672
673The return value and side effect of child mocks can be set in the same way,
674using dotted notation. As you can't use dotted names directly in a call you
Georg Brandl4433ff92014-10-31 07:59:37 +0100675have to create a dictionary and unpack it using ``**``:
Michael Foord944e02d2012-03-25 23:12:55 +0100676
677 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
678 >>> mock = Mock(some_attribute='eggs', **attrs)
679 >>> mock.some_attribute
680 'eggs'
681 >>> mock.method()
682 3
683 >>> mock.other()
684 Traceback (most recent call last):
685 ...
686 KeyError
687
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100688A callable mock which was created with a *spec* (or a *spec_set*) will
689introspect the specification object's signature when matching calls to
690the mock. Therefore, it can match the actual call's arguments regardless
691of whether they were passed positionally or by name::
692
693 >>> def f(a, b, c): pass
694 ...
695 >>> mock = Mock(spec=f)
696 >>> mock(1, 2, c=3)
697 <Mock name='mock()' id='140161580456576'>
698 >>> mock.assert_called_with(1, 2, 3)
699 >>> mock.assert_called_with(a=1, b=2, c=3)
700
701This applies to :meth:`~Mock.assert_called_with`,
702:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and
703:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also
704apply to method calls on the mock object.
705
706 .. versionchanged:: 3.4
707 Added signature introspection on specced and autospecced mock objects.
708
Michael Foord944e02d2012-03-25 23:12:55 +0100709
710.. class:: PropertyMock(*args, **kwargs)
711
712 A mock intended to be used as a property, or other descriptor, on a class.
Georg Brandl4433ff92014-10-31 07:59:37 +0100713 :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods
714 so you can specify a return value when it is fetched.
Michael Foord944e02d2012-03-25 23:12:55 +0100715
Georg Brandl4433ff92014-10-31 07:59:37 +0100716 Fetching a :class:`PropertyMock` instance from an object calls the mock, with
Michael Foord944e02d2012-03-25 23:12:55 +0100717 no args. Setting it calls the mock with the value being set.
718
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200719 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100720 ... @property
721 ... def foo(self):
722 ... return 'something'
723 ... @foo.setter
724 ... def foo(self, value):
725 ... pass
726 ...
727 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
728 ... mock_foo.return_value = 'mockity-mock'
729 ... this_foo = Foo()
730 ... print this_foo.foo
731 ... this_foo.foo = 6
732 ...
733 mockity-mock
734 >>> mock_foo.mock_calls
735 [call(), call(6)]
736
Michael Foordc2870622012-04-13 16:57:22 +0100737Because of the way mock attributes are stored you can't directly attach a
Georg Brandl4433ff92014-10-31 07:59:37 +0100738:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type
Michael Foordc2870622012-04-13 16:57:22 +0100739object::
740
741 >>> m = MagicMock()
742 >>> p = PropertyMock(return_value=3)
743 >>> type(m).foo = p
744 >>> m.foo
745 3
746 >>> p.assert_called_once_with()
747
Michael Foord944e02d2012-03-25 23:12:55 +0100748
749Calling
750~~~~~~~
751
752Mock objects are callable. The call will return the value set as the
753:attr:`~Mock.return_value` attribute. The default return value is a new Mock
754object; it is created the first time the return value is accessed (either
755explicitly or by calling the Mock) - but it is stored and the same one
756returned each time.
757
758Calls made to the object will be recorded in the attributes
759like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
760
761If :attr:`~Mock.side_effect` is set then it will be called after the call has
Georg Brandl4433ff92014-10-31 07:59:37 +0100762been recorded, so if :attr:`side_effect` raises an exception the call is still
Michael Foord944e02d2012-03-25 23:12:55 +0100763recorded.
764
765The simplest way to make a mock raise an exception when called is to make
766:attr:`~Mock.side_effect` an exception class or instance:
767
768 >>> m = MagicMock(side_effect=IndexError)
769 >>> m(1, 2, 3)
770 Traceback (most recent call last):
771 ...
772 IndexError
773 >>> m.mock_calls
774 [call(1, 2, 3)]
775 >>> m.side_effect = KeyError('Bang!')
776 >>> m('two', 'three', 'four')
777 Traceback (most recent call last):
778 ...
779 KeyError: 'Bang!'
780 >>> m.mock_calls
781 [call(1, 2, 3), call('two', 'three', 'four')]
782
Georg Brandl4433ff92014-10-31 07:59:37 +0100783If :attr:`side_effect` is a function then whatever that function returns is what
784calls to the mock return. The :attr:`side_effect` function is called with the
Michael Foord944e02d2012-03-25 23:12:55 +0100785same arguments as the mock. This allows you to vary the return value of the
786call dynamically, based on the input:
787
788 >>> def side_effect(value):
789 ... return value + 1
790 ...
791 >>> m = MagicMock(side_effect=side_effect)
792 >>> m(1)
793 2
794 >>> m(2)
795 3
796 >>> m.mock_calls
797 [call(1), call(2)]
798
799If you want the mock to still return the default return value (a new mock), or
800any set return value, then there are two ways of doing this. Either return
Georg Brandl4433ff92014-10-31 07:59:37 +0100801:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`:
Michael Foord944e02d2012-03-25 23:12:55 +0100802
803 >>> m = MagicMock()
804 >>> def side_effect(*args, **kwargs):
805 ... return m.return_value
806 ...
807 >>> m.side_effect = side_effect
808 >>> m.return_value = 3
809 >>> m()
810 3
811 >>> def side_effect(*args, **kwargs):
812 ... return DEFAULT
813 ...
814 >>> m.side_effect = side_effect
815 >>> m()
816 3
817
Georg Brandl4433ff92014-10-31 07:59:37 +0100818To remove a :attr:`side_effect`, and return to the default behaviour, set the
819:attr:`side_effect` to ``None``:
Michael Foord944e02d2012-03-25 23:12:55 +0100820
821 >>> m = MagicMock(return_value=6)
822 >>> def side_effect(*args, **kwargs):
823 ... return 3
824 ...
825 >>> m.side_effect = side_effect
826 >>> m()
827 3
828 >>> m.side_effect = None
829 >>> m()
830 6
831
Georg Brandl4433ff92014-10-31 07:59:37 +0100832The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock
Michael Foord944e02d2012-03-25 23:12:55 +0100833will return values from the iterable (until the iterable is exhausted and
Georg Brandl4433ff92014-10-31 07:59:37 +0100834a :exc:`StopIteration` is raised):
Michael Foord944e02d2012-03-25 23:12:55 +0100835
836 >>> m = MagicMock(side_effect=[1, 2, 3])
837 >>> m()
838 1
839 >>> m()
840 2
841 >>> m()
842 3
843 >>> m()
844 Traceback (most recent call last):
845 ...
846 StopIteration
847
Michael Foord2cd48732012-04-21 15:52:11 +0100848If any members of the iterable are exceptions they will be raised instead of
849returned::
850
851 >>> iterable = (33, ValueError, 66)
852 >>> m = MagicMock(side_effect=iterable)
853 >>> m()
854 33
855 >>> m()
856 Traceback (most recent call last):
857 ...
858 ValueError
859 >>> m()
860 66
861
Michael Foord944e02d2012-03-25 23:12:55 +0100862
863.. _deleting-attributes:
864
865Deleting Attributes
866~~~~~~~~~~~~~~~~~~~
867
868Mock objects create attributes on demand. This allows them to pretend to be
869objects of any type.
870
Georg Brandl4433ff92014-10-31 07:59:37 +0100871You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an
872:exc:`AttributeError` when an attribute is fetched. You can do this by providing
873an object as a :attr:`spec` for a mock, but that isn't always convenient.
Michael Foord944e02d2012-03-25 23:12:55 +0100874
875You "block" attributes by deleting them. Once deleted, accessing an attribute
Georg Brandl4433ff92014-10-31 07:59:37 +0100876will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100877
878 >>> mock = MagicMock()
879 >>> hasattr(mock, 'm')
880 True
881 >>> del mock.m
882 >>> hasattr(mock, 'm')
883 False
884 >>> del mock.f
885 >>> mock.f
886 Traceback (most recent call last):
887 ...
888 AttributeError: f
889
890
Michael Foordf5752302013-03-18 15:04:03 -0700891Mock names and the name attribute
892~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
893
894Since "name" is an argument to the :class:`Mock` constructor, if you want your
895mock object to have a "name" attribute you can't just pass it in at creation
896time. There are two alternatives. One option is to use
897:meth:`~Mock.configure_mock`::
898
899 >>> mock = MagicMock()
900 >>> mock.configure_mock(name='my_name')
901 >>> mock.name
902 'my_name'
903
904A simpler option is to simply set the "name" attribute after mock creation::
905
906 >>> mock = MagicMock()
907 >>> mock.name = "foo"
908
909
Michael Foord944e02d2012-03-25 23:12:55 +0100910Attaching Mocks as Attributes
911~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
912
913When you attach a mock as an attribute of another mock (or as the return
914value) it becomes a "child" of that mock. Calls to the child are recorded in
915the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
916parent. This is useful for configuring child mocks and then attaching them to
917the parent, or for attaching mocks to a parent that records all calls to the
918children and allows you to make assertions about the order of calls between
919mocks:
920
921 >>> parent = MagicMock()
922 >>> child1 = MagicMock(return_value=None)
923 >>> child2 = MagicMock(return_value=None)
924 >>> parent.child1 = child1
925 >>> parent.child2 = child2
926 >>> child1(1)
927 >>> child2(2)
928 >>> parent.mock_calls
929 [call.child1(1), call.child2(2)]
930
931The exception to this is if the mock has a name. This allows you to prevent
932the "parenting" if for some reason you don't want it to happen.
933
934 >>> mock = MagicMock()
935 >>> not_a_child = MagicMock(name='not-a-child')
936 >>> mock.attribute = not_a_child
937 >>> mock.attribute()
938 <MagicMock name='not-a-child()' id='...'>
939 >>> mock.mock_calls
940 []
941
942Mocks created for you by :func:`patch` are automatically given names. To
943attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
944method:
945
946 >>> thing1 = object()
947 >>> thing2 = object()
948 >>> parent = MagicMock()
949 >>> with patch('__main__.thing1', return_value=None) as child1:
950 ... with patch('__main__.thing2', return_value=None) as child2:
951 ... parent.attach_mock(child1, 'child1')
952 ... parent.attach_mock(child2, 'child2')
953 ... child1('one')
954 ... child2('two')
955 ...
956 >>> parent.mock_calls
957 [call.child1('one'), call.child2('two')]
958
959
960.. [#] The only exceptions are magic methods and attributes (those that have
961 leading and trailing double underscores). Mock doesn't create these but
Georg Brandl4433ff92014-10-31 07:59:37 +0100962 instead raises an :exc:`AttributeError`. This is because the interpreter
Michael Foord944e02d2012-03-25 23:12:55 +0100963 will often implicitly request these methods, and gets *very* confused to
964 get a new Mock object when it expects a magic method. If you need magic
965 method support see :ref:`magic methods <magic-methods>`.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100966
967
968The patchers
Georg Brandlfb134382013-02-03 11:47:49 +0100969------------
Michael Foorda9e6fb22012-03-28 14:36:02 +0100970
971The patch decorators are used for patching objects only within the scope of
972the function they decorate. They automatically handle the unpatching for you,
973even if exceptions are raised. All of these functions can also be used in with
974statements or as class decorators.
975
976
977patch
Georg Brandlfb134382013-02-03 11:47:49 +0100978~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +0100979
980.. note::
981
Georg Brandl4433ff92014-10-31 07:59:37 +0100982 :func:`patch` is straightforward to use. The key is to do the patching in the
Michael Foorda9e6fb22012-03-28 14:36:02 +0100983 right namespace. See the section `where to patch`_.
984
985.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
986
Georg Brandl4433ff92014-10-31 07:59:37 +0100987 :func:`patch` acts as a function decorator, class decorator or a context
988 manager. Inside the body of the function or with statement, the *target*
989 is patched with a *new* object. When the function/with statement exits
Michael Foord54b3db82012-03-28 15:08:08 +0100990 the patch is undone.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100991
Georg Brandl4433ff92014-10-31 07:59:37 +0100992 If *new* is omitted, then the target is replaced with a
993 :class:`MagicMock`. If :func:`patch` is used as a decorator and *new* is
Michael Foord54b3db82012-03-28 15:08:08 +0100994 omitted, the created mock is passed in as an extra argument to the
Georg Brandl4433ff92014-10-31 07:59:37 +0100995 decorated function. If :func:`patch` is used as a context manager the created
Michael Foord54b3db82012-03-28 15:08:08 +0100996 mock is returned by the context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100997
Georg Brandl4433ff92014-10-31 07:59:37 +0100998 *target* should be a string in the form ``'package.module.ClassName'``. The
999 *target* is imported and the specified object replaced with the *new*
1000 object, so the *target* must be importable from the environment you are
1001 calling :func:`patch` from. The target is imported when the decorated function
Michael Foord54b3db82012-03-28 15:08:08 +01001002 is executed, not at decoration time.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001003
Georg Brandl4433ff92014-10-31 07:59:37 +01001004 The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001005 if patch is creating one for you.
1006
Georg Brandl4433ff92014-10-31 07:59:37 +01001007 In addition you can pass ``spec=True`` or ``spec_set=True``, which causes
Michael Foorda9e6fb22012-03-28 14:36:02 +01001008 patch to pass in the object being mocked as the spec/spec_set object.
1009
Georg Brandl4433ff92014-10-31 07:59:37 +01001010 *new_callable* allows you to specify a different class, or callable object,
1011 that will be called to create the *new* object. By default :class:`MagicMock` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001012 used.
1013
Georg Brandl4433ff92014-10-31 07:59:37 +01001014 A more powerful form of *spec* is *autospec*. If you set ``autospec=True``
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001015 then the mock will be created with a spec from the object being replaced.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001016 All attributes of the mock will also have the spec of the corresponding
1017 attribute of the object being replaced. Methods and functions being mocked
Georg Brandl4433ff92014-10-31 07:59:37 +01001018 will have their arguments checked and will raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001019 called with the wrong signature. For mocks
1020 replacing a class, their return value (the 'instance') will have the same
1021 spec as the class. See the :func:`create_autospec` function and
1022 :ref:`auto-speccing`.
1023
Georg Brandl4433ff92014-10-31 07:59:37 +01001024 Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001025 arbitrary object as the spec instead of the one being replaced.
1026
Georg Brandl4433ff92014-10-31 07:59:37 +01001027 By default :func:`patch` will fail to replace attributes that don't exist. If
1028 you pass in ``create=True``, and the attribute doesn't exist, patch will
Michael Foorda9e6fb22012-03-28 14:36:02 +01001029 create the attribute for you when the patched function is called, and
1030 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001031 attributes that your production code creates at runtime. It is off by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001032 default because it can be dangerous. With it switched on you can write
1033 passing tests against APIs that don't actually exist!
1034
1035 Patch can be used as a `TestCase` class decorator. It works by
1036 decorating each test method in the class. This reduces the boilerplate
1037 code when your test methods share a common patchings set. `patch` finds
1038 tests by looking for method names that start with `patch.TEST_PREFIX`.
1039 By default this is `test`, which matches the way `unittest` finds tests.
1040 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1041
1042 Patch can be used as a context manager, with the with statement. Here the
1043 patching applies to the indented block after the with statement. If you
1044 use "as" then the patched object will be bound to the name after the
1045 "as"; very useful if `patch` is creating a mock object for you.
1046
1047 `patch` takes arbitrary keyword arguments. These will be passed to
1048 the `Mock` (or `new_callable`) on construction.
1049
1050 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1051 available for alternate use-cases.
1052
Michael Foord90155362012-03-28 15:32:08 +01001053`patch` as function decorator, creating the mock for you and passing it into
1054the decorated function:
1055
1056 >>> @patch('__main__.SomeClass')
Michael Foord324b58b2012-03-28 15:49:08 +01001057 ... def function(normal_argument, mock_class):
Michael Foord90155362012-03-28 15:32:08 +01001058 ... print(mock_class is SomeClass)
1059 ...
Michael Foord324b58b2012-03-28 15:49:08 +01001060 >>> function(None)
Michael Foord90155362012-03-28 15:32:08 +01001061 True
Michael Foorda9e6fb22012-03-28 14:36:02 +01001062
Georg Brandl4433ff92014-10-31 07:59:37 +01001063Patching a class replaces the class with a :class:`MagicMock` *instance*. If the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001064class is instantiated in the code under test then it will be the
1065:attr:`~Mock.return_value` of the mock that will be used.
1066
1067If the class is instantiated multiple times you could use
1068:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
Georg Brandl4433ff92014-10-31 07:59:37 +01001069can set the *return_value* to be anything you want.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001070
1071To configure return values on methods of *instances* on the patched class
Georg Brandl4433ff92014-10-31 07:59:37 +01001072you must do this on the :attr:`return_value`. For example:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001073
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001074 >>> class Class:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001075 ... def method(self):
1076 ... pass
1077 ...
1078 >>> with patch('__main__.Class') as MockClass:
1079 ... instance = MockClass.return_value
1080 ... instance.method.return_value = 'foo'
1081 ... assert Class() is instance
1082 ... assert Class().method() == 'foo'
1083 ...
1084
Georg Brandl4433ff92014-10-31 07:59:37 +01001085If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001086return value of the created mock will have the same spec.
1087
1088 >>> Original = Class
1089 >>> patcher = patch('__main__.Class', spec=True)
1090 >>> MockClass = patcher.start()
1091 >>> instance = MockClass()
1092 >>> assert isinstance(instance, Original)
1093 >>> patcher.stop()
1094
Georg Brandl4433ff92014-10-31 07:59:37 +01001095The *new_callable* argument is useful where you want to use an alternative
Michael Foorda9e6fb22012-03-28 14:36:02 +01001096class to the default :class:`MagicMock` for the created mock. For example, if
1097you wanted a :class:`NonCallableMock` to be used:
1098
1099 >>> thing = object()
1100 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
1101 ... assert thing is mock_thing
1102 ... thing()
1103 ...
1104 Traceback (most recent call last):
1105 ...
1106 TypeError: 'NonCallableMock' object is not callable
1107
Georg Brandl4433ff92014-10-31 07:59:37 +01001108Another use case might be to replace an object with a :class:`io.StringIO` instance:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001109
Serhiy Storchakae79be872013-08-17 00:09:55 +03001110 >>> from io import StringIO
Michael Foorda9e6fb22012-03-28 14:36:02 +01001111 >>> def foo():
1112 ... print 'Something'
1113 ...
1114 >>> @patch('sys.stdout', new_callable=StringIO)
1115 ... def test(mock_stdout):
1116 ... foo()
1117 ... assert mock_stdout.getvalue() == 'Something\n'
1118 ...
1119 >>> test()
1120
Georg Brandl4433ff92014-10-31 07:59:37 +01001121When :func:`patch` is creating a mock for you, it is common that the first thing
Michael Foorda9e6fb22012-03-28 14:36:02 +01001122you need to do is to configure the mock. Some of that configuration can be done
1123in the call to patch. Any arbitrary keywords you pass into the call will be
1124used to set attributes on the created mock:
1125
1126 >>> patcher = patch('__main__.thing', first='one', second='two')
1127 >>> mock_thing = patcher.start()
1128 >>> mock_thing.first
1129 'one'
1130 >>> mock_thing.second
1131 'two'
1132
1133As well as attributes on the created mock attributes, like the
1134:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
1135also be configured. These aren't syntactically valid to pass in directly as
1136keyword arguments, but a dictionary with these as keys can still be expanded
Georg Brandl4433ff92014-10-31 07:59:37 +01001137into a :func:`patch` call using ``**``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001138
1139 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
1140 >>> patcher = patch('__main__.thing', **config)
1141 >>> mock_thing = patcher.start()
1142 >>> mock_thing.method()
1143 3
1144 >>> mock_thing.other()
1145 Traceback (most recent call last):
1146 ...
1147 KeyError
1148
1149
1150patch.object
Georg Brandlfb134382013-02-03 11:47:49 +01001151~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001152
1153.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1154
Georg Brandl4433ff92014-10-31 07:59:37 +01001155 patch the named member (*attribute*) on an object (*target*) with a mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001156 object.
1157
Georg Brandl4433ff92014-10-31 07:59:37 +01001158 :func:`patch.object` can be used as a decorator, class decorator or a context
1159 manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and
1160 *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`,
1161 :func:`patch.object` takes arbitrary keyword arguments for configuring the mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001162 object it creates.
1163
Georg Brandl4433ff92014-10-31 07:59:37 +01001164 When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001165 for choosing which methods to wrap.
1166
Georg Brandl4433ff92014-10-31 07:59:37 +01001167You can either call :func:`patch.object` with three arguments or two arguments. The
Michael Foorda9e6fb22012-03-28 14:36:02 +01001168three argument form takes the object to be patched, the attribute name and the
1169object to replace the attribute with.
1170
1171When calling with the two argument form you omit the replacement object, and a
1172mock is created for you and passed in as an extra argument to the decorated
1173function:
1174
1175 >>> @patch.object(SomeClass, 'class_method')
1176 ... def test(mock_method):
1177 ... SomeClass.class_method(3)
1178 ... mock_method.assert_called_with(3)
1179 ...
1180 >>> test()
1181
Georg Brandl4433ff92014-10-31 07:59:37 +01001182*spec*, *create* and the other arguments to :func:`patch.object` have the same
1183meaning as they do for :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001184
1185
1186patch.dict
Georg Brandlfb134382013-02-03 11:47:49 +01001187~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001188
1189.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
1190
1191 Patch a dictionary, or dictionary like object, and restore the dictionary
1192 to its original state after the test.
1193
Georg Brandl4433ff92014-10-31 07:59:37 +01001194 *in_dict* can be a dictionary or a mapping like container. If it is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01001195 mapping then it must at least support getting, setting and deleting items
1196 plus iterating over keys.
1197
Georg Brandl4433ff92014-10-31 07:59:37 +01001198 *in_dict* can also be a string specifying the name of the dictionary, which
Michael Foorda9e6fb22012-03-28 14:36:02 +01001199 will then be fetched by importing it.
1200
Georg Brandl4433ff92014-10-31 07:59:37 +01001201 *values* can be a dictionary of values to set in the dictionary. *values*
1202 can also be an iterable of ``(key, value)`` pairs.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001203
Georg Brandl4433ff92014-10-31 07:59:37 +01001204 If *clear* is true then the dictionary will be cleared before the new
Michael Foorda9e6fb22012-03-28 14:36:02 +01001205 values are set.
1206
Georg Brandl4433ff92014-10-31 07:59:37 +01001207 :func:`patch.dict` can also be called with arbitrary keyword arguments to set
Michael Foorda9e6fb22012-03-28 14:36:02 +01001208 values in the dictionary.
1209
Georg Brandl4433ff92014-10-31 07:59:37 +01001210 :func:`patch.dict` can be used as a context manager, decorator or class
1211 decorator. When used as a class decorator :func:`patch.dict` honours
1212 ``patch.TEST_PREFIX`` for choosing which methods to wrap.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001213
Georg Brandl4433ff92014-10-31 07:59:37 +01001214:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
Michael Foorda9e6fb22012-03-28 14:36:02 +01001215change a dictionary, and ensure the dictionary is restored when the test
1216ends.
1217
1218 >>> foo = {}
1219 >>> with patch.dict(foo, {'newkey': 'newvalue'}):
1220 ... assert foo == {'newkey': 'newvalue'}
1221 ...
1222 >>> assert foo == {}
1223
1224 >>> import os
1225 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
1226 ... print os.environ['newkey']
1227 ...
1228 newvalue
1229 >>> assert 'newkey' not in os.environ
1230
Georg Brandl4433ff92014-10-31 07:59:37 +01001231Keywords can be used in the :func:`patch.dict` call to set values in the dictionary:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001232
1233 >>> mymodule = MagicMock()
1234 >>> mymodule.function.return_value = 'fish'
1235 >>> with patch.dict('sys.modules', mymodule=mymodule):
1236 ... import mymodule
1237 ... mymodule.function('some', 'args')
1238 ...
1239 'fish'
1240
Georg Brandl4433ff92014-10-31 07:59:37 +01001241:func:`patch.dict` can be used with dictionary like objects that aren't actually
Michael Foorda9e6fb22012-03-28 14:36:02 +01001242dictionaries. At the very minimum they must support item getting, setting,
1243deleting and either iteration or membership test. This corresponds to the
Georg Brandl4433ff92014-10-31 07:59:37 +01001244magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either
1245:meth:`__iter__` or :meth:`__contains__`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001246
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001247 >>> class Container:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001248 ... def __init__(self):
1249 ... self.values = {}
1250 ... def __getitem__(self, name):
1251 ... return self.values[name]
1252 ... def __setitem__(self, name, value):
1253 ... self.values[name] = value
1254 ... def __delitem__(self, name):
1255 ... del self.values[name]
1256 ... def __iter__(self):
1257 ... return iter(self.values)
1258 ...
1259 >>> thing = Container()
1260 >>> thing['one'] = 1
1261 >>> with patch.dict(thing, one=2, two=3):
1262 ... assert thing['one'] == 2
1263 ... assert thing['two'] == 3
1264 ...
1265 >>> assert thing['one'] == 1
1266 >>> assert list(thing) == ['one']
1267
1268
1269patch.multiple
Georg Brandlfb134382013-02-03 11:47:49 +01001270~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001271
1272.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1273
1274 Perform multiple patches in a single call. It takes the object to be
1275 patched (either as an object or a string to fetch the object by importing)
1276 and keyword arguments for the patches::
1277
1278 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1279 ...
1280
Georg Brandl4433ff92014-10-31 07:59:37 +01001281 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create
Michael Foorda9e6fb22012-03-28 14:36:02 +01001282 mocks for you. In this case the created mocks are passed into a decorated
Georg Brandl4433ff92014-10-31 07:59:37 +01001283 function by keyword, and a dictionary is returned when :func:`patch.multiple` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001284 used as a context manager.
1285
Georg Brandl4433ff92014-10-31 07:59:37 +01001286 :func:`patch.multiple` can be used as a decorator, class decorator or a context
1287 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and
1288 *new_callable* have the same meaning as for :func:`patch`. These arguments will
1289 be applied to *all* patches done by :func:`patch.multiple`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001290
Georg Brandl4433ff92014-10-31 07:59:37 +01001291 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001292 for choosing which methods to wrap.
1293
Georg Brandl4433ff92014-10-31 07:59:37 +01001294If you want :func:`patch.multiple` to create mocks for you, then you can use
1295:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
Michael Foorda9e6fb22012-03-28 14:36:02 +01001296then the created mocks are passed into the decorated function by keyword.
1297
1298 >>> thing = object()
1299 >>> other = object()
1300
1301 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1302 ... def test_function(thing, other):
1303 ... assert isinstance(thing, MagicMock)
1304 ... assert isinstance(other, MagicMock)
1305 ...
1306 >>> test_function()
1307
Georg Brandl4433ff92014-10-31 07:59:37 +01001308:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
1309passed by keyword *after* any of the standard arguments created by :func:`patch`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001310
1311 >>> @patch('sys.exit')
1312 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1313 ... def test_function(mock_exit, other, thing):
1314 ... assert 'other' in repr(other)
1315 ... assert 'thing' in repr(thing)
1316 ... assert 'exit' in repr(mock_exit)
1317 ...
1318 >>> test_function()
1319
Georg Brandl4433ff92014-10-31 07:59:37 +01001320If :func:`patch.multiple` is used as a context manager, the value returned by the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001321context manger is a dictionary where created mocks are keyed by name:
1322
1323 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1324 ... assert 'other' in repr(values['other'])
1325 ... assert 'thing' in repr(values['thing'])
1326 ... assert values['thing'] is thing
1327 ... assert values['other'] is other
1328 ...
1329
1330
1331.. _start-and-stop:
1332
1333patch methods: start and stop
Georg Brandlfb134382013-02-03 11:47:49 +01001334~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001335
Georg Brandl4433ff92014-10-31 07:59:37 +01001336All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do
1337patching in ``setUp`` methods or where you want to do multiple patches without
Michael Foorda9e6fb22012-03-28 14:36:02 +01001338nesting decorators or with statements.
1339
Georg Brandl4433ff92014-10-31 07:59:37 +01001340To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as
1341normal and keep a reference to the returned ``patcher`` object. You can then
1342call :meth:`start` to put the patch in place and :meth:`stop` to undo it.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001343
Georg Brandl4433ff92014-10-31 07:59:37 +01001344If you are using :func:`patch` to create a mock for you then it will be returned by
1345the call to ``patcher.start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001346
1347 >>> patcher = patch('package.module.ClassName')
1348 >>> from package import module
1349 >>> original = module.ClassName
1350 >>> new_mock = patcher.start()
1351 >>> assert module.ClassName is not original
1352 >>> assert module.ClassName is new_mock
1353 >>> patcher.stop()
1354 >>> assert module.ClassName is original
1355 >>> assert module.ClassName is not new_mock
1356
1357
Georg Brandl4433ff92014-10-31 07:59:37 +01001358A typical use case for this might be for doing multiple patches in the ``setUp``
1359method of a :class:`TestCase`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001360
1361 >>> class MyTest(TestCase):
1362 ... def setUp(self):
1363 ... self.patcher1 = patch('package.module.Class1')
1364 ... self.patcher2 = patch('package.module.Class2')
1365 ... self.MockClass1 = self.patcher1.start()
1366 ... self.MockClass2 = self.patcher2.start()
1367 ...
1368 ... def tearDown(self):
1369 ... self.patcher1.stop()
1370 ... self.patcher2.stop()
1371 ...
1372 ... def test_something(self):
1373 ... assert package.module.Class1 is self.MockClass1
1374 ... assert package.module.Class2 is self.MockClass2
1375 ...
1376 >>> MyTest('test_something').run()
1377
1378.. caution::
1379
1380 If you use this technique you must ensure that the patching is "undone" by
Georg Brandl4433ff92014-10-31 07:59:37 +01001381 calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001382 exception is raised in the ``setUp`` then ``tearDown`` is not called.
1383 :meth:`unittest.TestCase.addCleanup` makes this easier:
1384
1385 >>> class MyTest(TestCase):
1386 ... def setUp(self):
1387 ... patcher = patch('package.module.Class')
1388 ... self.MockClass = patcher.start()
1389 ... self.addCleanup(patcher.stop)
1390 ...
1391 ... def test_something(self):
1392 ... assert package.module.Class is self.MockClass
1393 ...
1394
1395 As an added bonus you no longer need to keep a reference to the `patcher`
1396 object.
1397
Michael Foordf7c41582012-06-10 20:36:32 +01001398It is also possible to stop all patches which have been started by using
1399`patch.stopall`.
1400
1401.. function:: patch.stopall
1402
Michael Foord911fd322012-06-10 20:38:54 +01001403 Stop all active patches. Only stops patches started with `start`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001404
1405
1406TEST_PREFIX
Georg Brandlfb134382013-02-03 11:47:49 +01001407~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001408
1409All of the patchers can be used as class decorators. When used in this way
1410they wrap every test method on the class. The patchers recognise methods that
Georg Brandl4433ff92014-10-31 07:59:37 +01001411start with ``'test'`` as being test methods. This is the same way that the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001412:class:`unittest.TestLoader` finds test methods by default.
1413
1414It is possible that you want to use a different prefix for your tests. You can
Georg Brandl4433ff92014-10-31 07:59:37 +01001415inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001416
1417 >>> patch.TEST_PREFIX = 'foo'
1418 >>> value = 3
1419 >>>
1420 >>> @patch('__main__.value', 'not three')
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001421 ... class Thing:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001422 ... def foo_one(self):
1423 ... print value
1424 ... def foo_two(self):
1425 ... print value
1426 ...
1427 >>>
1428 >>> Thing().foo_one()
1429 not three
1430 >>> Thing().foo_two()
1431 not three
1432 >>> value
1433 3
1434
1435
1436Nesting Patch Decorators
Georg Brandlfb134382013-02-03 11:47:49 +01001437~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001438
1439If you want to perform multiple patches then you can simply stack up the
1440decorators.
1441
1442You can stack up multiple patch decorators using this pattern:
1443
1444 >>> @patch.object(SomeClass, 'class_method')
1445 ... @patch.object(SomeClass, 'static_method')
1446 ... def test(mock1, mock2):
1447 ... assert SomeClass.static_method is mock1
1448 ... assert SomeClass.class_method is mock2
1449 ... SomeClass.static_method('foo')
1450 ... SomeClass.class_method('bar')
1451 ... return mock1, mock2
1452 ...
1453 >>> mock1, mock2 = test()
1454 >>> mock1.assert_called_once_with('foo')
1455 >>> mock2.assert_called_once_with('bar')
1456
1457
1458Note that the decorators are applied from the bottom upwards. This is the
1459standard way that Python applies decorators. The order of the created mocks
1460passed into your test function matches this order.
1461
1462
1463.. _where-to-patch:
1464
1465Where to patch
Georg Brandlfb134382013-02-03 11:47:49 +01001466~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001467
Georg Brandl4433ff92014-10-31 07:59:37 +01001468:func:`patch` works by (temporarily) changing the object that a *name* points to with
Michael Foorda9e6fb22012-03-28 14:36:02 +01001469another one. There can be many names pointing to any individual object, so
1470for patching to work you must ensure that you patch the name used by the system
1471under test.
1472
1473The basic principle is that you patch where an object is *looked up*, which
1474is not necessarily the same place as where it is defined. A couple of
1475examples will help to clarify this.
1476
1477Imagine we have a project that we want to test with the following structure::
1478
1479 a.py
1480 -> Defines SomeClass
1481
1482 b.py
1483 -> from a import SomeClass
1484 -> some_function instantiates SomeClass
1485
Georg Brandl4433ff92014-10-31 07:59:37 +01001486Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
1487:func:`patch`. The problem is that when we import module b, which we will have to
1488do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
1489``a.SomeClass`` then it will have no effect on our test; module b already has a
1490reference to the *real* ``SomeClass`` and it looks like our patching had no
Michael Foorda9e6fb22012-03-28 14:36:02 +01001491effect.
1492
Georg Brandl4433ff92014-10-31 07:59:37 +01001493The key is to patch out ``SomeClass`` where it is used (or where it is looked up
1494). In this case ``some_function`` will actually look up ``SomeClass`` in module b,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001495where we have imported it. The patching should look like::
1496
1497 @patch('b.SomeClass')
1498
Georg Brandl4433ff92014-10-31 07:59:37 +01001499However, consider the alternative scenario where instead of ``from a import
1500SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both
Michael Foorda9e6fb22012-03-28 14:36:02 +01001501of these import forms are common. In this case the class we want to patch is
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001502being looked up in the module and so we have to patch ``a.SomeClass`` instead::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001503
1504 @patch('a.SomeClass')
1505
1506
1507Patching Descriptors and Proxy Objects
Georg Brandlfb134382013-02-03 11:47:49 +01001508~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001509
1510Both patch_ and patch.object_ correctly patch and restore descriptors: class
1511methods, static methods and properties. You should patch these on the *class*
1512rather than an instance. They also work with *some* objects
Larry Hastings3732ed22014-03-15 21:13:56 -07001513that proxy attribute access, like the `django settings object
Michael Foorda9e6fb22012-03-28 14:36:02 +01001514<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
1515
1516
Michael Foord2309ed82012-03-28 15:38:36 +01001517MagicMock and magic method support
Georg Brandlfb134382013-02-03 11:47:49 +01001518----------------------------------
Michael Foord2309ed82012-03-28 15:38:36 +01001519
1520.. _magic-methods:
1521
1522Mocking Magic Methods
Georg Brandlfb134382013-02-03 11:47:49 +01001523~~~~~~~~~~~~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001524
1525:class:`Mock` supports mocking the Python protocol methods, also known as
1526"magic methods". This allows mock objects to replace containers or other
1527objects that implement Python protocols.
1528
1529Because magic methods are looked up differently from normal methods [#]_, this
1530support has been specially implemented. This means that only specific magic
1531methods are supported. The supported list includes *almost* all of them. If
1532there are any missing that you need please let us know.
1533
1534You mock magic methods by setting the method you are interested in to a function
1535or a mock instance. If you are using a function then it *must* take ``self`` as
1536the first argument [#]_.
1537
1538 >>> def __str__(self):
1539 ... return 'fooble'
1540 ...
1541 >>> mock = Mock()
1542 >>> mock.__str__ = __str__
1543 >>> str(mock)
1544 'fooble'
1545
1546 >>> mock = Mock()
1547 >>> mock.__str__ = Mock()
1548 >>> mock.__str__.return_value = 'fooble'
1549 >>> str(mock)
1550 'fooble'
1551
1552 >>> mock = Mock()
1553 >>> mock.__iter__ = Mock(return_value=iter([]))
1554 >>> list(mock)
1555 []
1556
1557One use case for this is for mocking objects used as context managers in a
Georg Brandl4433ff92014-10-31 07:59:37 +01001558:keyword:`with` statement:
Michael Foord2309ed82012-03-28 15:38:36 +01001559
1560 >>> mock = Mock()
1561 >>> mock.__enter__ = Mock(return_value='foo')
1562 >>> mock.__exit__ = Mock(return_value=False)
1563 >>> with mock as m:
1564 ... assert m == 'foo'
1565 ...
1566 >>> mock.__enter__.assert_called_with()
1567 >>> mock.__exit__.assert_called_with(None, None, None)
1568
1569Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
1570are recorded in :attr:`~Mock.mock_calls`.
1571
1572.. note::
1573
Georg Brandl4433ff92014-10-31 07:59:37 +01001574 If you use the *spec* keyword argument to create a mock then attempting to
1575 set a magic method that isn't in the spec will raise an :exc:`AttributeError`.
Michael Foord2309ed82012-03-28 15:38:36 +01001576
1577The full list of supported magic methods is:
1578
1579* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
1580* ``__dir__``, ``__format__`` and ``__subclasses__``
1581* ``__floor__``, ``__trunc__`` and ``__ceil__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001582* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001583 ``__eq__`` and ``__ne__``
1584* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001585 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__``
1586 and ``__missing__``
Michael Foord2309ed82012-03-28 15:38:36 +01001587* Context manager: ``__enter__`` and ``__exit__``
1588* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
1589* The numeric methods (including right hand and in-place variants):
Zachary Ware5c676f62015-07-06 23:27:15 -05001590 ``__add__``, ``__sub__``, ``__mul__``, ``__div__``, ``__truediv__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001591 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
1592 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001593* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``
1594 and ``__index__``
Michael Foord2309ed82012-03-28 15:38:36 +01001595* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
1596* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
1597 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
1598
1599
1600The following methods exist but are *not* supported as they are either in use
1601by mock, can't be set dynamically, or can cause problems:
1602
1603* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
1604* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
1605
1606
1607
1608Magic Mock
Georg Brandlfb134382013-02-03 11:47:49 +01001609~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001610
Georg Brandl4433ff92014-10-31 07:59:37 +01001611There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001612
1613
1614.. class:: MagicMock(*args, **kw)
1615
1616 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
1617 of most of the magic methods. You can use ``MagicMock`` without having to
1618 configure the magic methods yourself.
1619
1620 The constructor parameters have the same meaning as for :class:`Mock`.
1621
Georg Brandl4433ff92014-10-31 07:59:37 +01001622 If you use the *spec* or *spec_set* arguments then *only* magic methods
Michael Foord2309ed82012-03-28 15:38:36 +01001623 that exist in the spec will be created.
1624
1625
1626.. class:: NonCallableMagicMock(*args, **kw)
1627
Georg Brandl4433ff92014-10-31 07:59:37 +01001628 A non-callable version of :class:`MagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001629
1630 The constructor parameters have the same meaning as for
Georg Brandl4433ff92014-10-31 07:59:37 +01001631 :class:`MagicMock`, with the exception of *return_value* and
1632 *side_effect* which have no meaning on a non-callable mock.
Michael Foord2309ed82012-03-28 15:38:36 +01001633
Georg Brandl4433ff92014-10-31 07:59:37 +01001634The magic methods are setup with :class:`MagicMock` objects, so you can configure them
Michael Foord2309ed82012-03-28 15:38:36 +01001635and use them in the usual way:
1636
1637 >>> mock = MagicMock()
1638 >>> mock[3] = 'fish'
1639 >>> mock.__setitem__.assert_called_with(3, 'fish')
1640 >>> mock.__getitem__.return_value = 'result'
1641 >>> mock[2]
1642 'result'
1643
1644By default many of the protocol methods are required to return objects of a
1645specific type. These methods are preconfigured with a default return value, so
1646that they can be used without you having to do anything if you aren't interested
1647in the return value. You can still *set* the return value manually if you want
1648to change the default.
1649
1650Methods and their defaults:
1651
1652* ``__lt__``: NotImplemented
1653* ``__gt__``: NotImplemented
1654* ``__le__``: NotImplemented
1655* ``__ge__``: NotImplemented
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001656* ``__int__``: 1
1657* ``__contains__``: False
1658* ``__len__``: 1
1659* ``__iter__``: iter([])
1660* ``__exit__``: False
1661* ``__complex__``: 1j
1662* ``__float__``: 1.0
1663* ``__bool__``: True
1664* ``__index__``: 1
1665* ``__hash__``: default hash for the mock
1666* ``__str__``: default str for the mock
Michael Foord2309ed82012-03-28 15:38:36 +01001667* ``__sizeof__``: default sizeof for the mock
1668
1669For example:
1670
1671 >>> mock = MagicMock()
1672 >>> int(mock)
1673 1
1674 >>> len(mock)
1675 0
1676 >>> list(mock)
1677 []
1678 >>> object() in mock
1679 False
1680
Berker Peksag283f1aa2015-01-07 21:15:02 +02001681The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special.
1682They do the default equality comparison on identity, using the
1683:attr:`~Mock.side_effect` attribute, unless you change their return value to
1684return something else::
Michael Foord2309ed82012-03-28 15:38:36 +01001685
1686 >>> MagicMock() == 3
1687 False
1688 >>> MagicMock() != 3
1689 True
1690 >>> mock = MagicMock()
1691 >>> mock.__eq__.return_value = True
1692 >>> mock == 3
1693 True
1694
Georg Brandl4433ff92014-10-31 07:59:37 +01001695The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
Michael Foord2309ed82012-03-28 15:38:36 +01001696required to be an iterator:
1697
1698 >>> mock = MagicMock()
1699 >>> mock.__iter__.return_value = ['a', 'b', 'c']
1700 >>> list(mock)
1701 ['a', 'b', 'c']
1702 >>> list(mock)
1703 ['a', 'b', 'c']
1704
1705If the return value *is* an iterator, then iterating over it once will consume
1706it and subsequent iterations will result in an empty list:
1707
1708 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
1709 >>> list(mock)
1710 ['a', 'b', 'c']
1711 >>> list(mock)
1712 []
1713
1714``MagicMock`` has all of the supported magic methods configured except for some
1715of the obscure and obsolete ones. You can still set these up if you want.
1716
1717Magic methods that are supported but not setup by default in ``MagicMock`` are:
1718
1719* ``__subclasses__``
1720* ``__dir__``
1721* ``__format__``
1722* ``__get__``, ``__set__`` and ``__delete__``
1723* ``__reversed__`` and ``__missing__``
1724* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
1725 ``__getstate__`` and ``__setstate__``
1726* ``__getformat__`` and ``__setformat__``
1727
1728
1729
1730.. [#] Magic methods *should* be looked up on the class rather than the
1731 instance. Different versions of Python are inconsistent about applying this
1732 rule. The supported protocol methods should work with all supported versions
1733 of Python.
1734.. [#] The function is basically hooked up to the class, but each ``Mock``
1735 instance is kept isolated from the others.
1736
1737
Michael Foorda9e6fb22012-03-28 14:36:02 +01001738Helpers
Georg Brandlfb134382013-02-03 11:47:49 +01001739-------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001740
1741sentinel
Georg Brandlfb134382013-02-03 11:47:49 +01001742~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001743
1744.. data:: sentinel
1745
1746 The ``sentinel`` object provides a convenient way of providing unique
1747 objects for your tests.
1748
1749 Attributes are created on demand when you access them by name. Accessing
1750 the same attribute will always return the same object. The objects
1751 returned have a sensible repr so that test failure messages are readable.
1752
1753Sometimes when testing you need to test that a specific object is passed as an
1754argument to another method, or returned. It can be common to create named
Georg Brandl4433ff92014-10-31 07:59:37 +01001755sentinel objects to test this. :data:`sentinel` provides a convenient way of
Michael Foorda9e6fb22012-03-28 14:36:02 +01001756creating and testing the identity of objects like this.
1757
Georg Brandl4433ff92014-10-31 07:59:37 +01001758In this example we monkey patch ``method`` to return ``sentinel.some_object``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001759
1760 >>> real = ProductionClass()
1761 >>> real.method = Mock(name="method")
1762 >>> real.method.return_value = sentinel.some_object
1763 >>> result = real.method()
1764 >>> assert result is sentinel.some_object
1765 >>> sentinel.some_object
1766 sentinel.some_object
1767
1768
1769DEFAULT
Georg Brandlfb134382013-02-03 11:47:49 +01001770~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001771
1772
1773.. data:: DEFAULT
1774
Georg Brandl4433ff92014-10-31 07:59:37 +01001775 The :data:`DEFAULT` object is a pre-created sentinel (actually
1776 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001777 functions to indicate that the normal return value should be used.
1778
1779
Michael Foorda9e6fb22012-03-28 14:36:02 +01001780call
Georg Brandlfb134382013-02-03 11:47:49 +01001781~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001782
1783.. function:: call(*args, **kwargs)
1784
Georg Brandl4433ff92014-10-31 07:59:37 +01001785 :func:`call` is a helper object for making simpler assertions, for comparing with
Georg Brandl24891672012-04-01 13:48:26 +02001786 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
Georg Brandl4433ff92014-10-31 07:59:37 +01001787 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be
Michael Foorda9e6fb22012-03-28 14:36:02 +01001788 used with :meth:`~Mock.assert_has_calls`.
1789
1790 >>> m = MagicMock(return_value=None)
1791 >>> m(1, 2, a='foo', b='bar')
1792 >>> m()
1793 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
1794 True
1795
1796.. method:: call.call_list()
1797
Georg Brandl4433ff92014-10-31 07:59:37 +01001798 For a call object that represents multiple calls, :meth:`call_list`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001799 returns a list of all the intermediate calls as well as the
1800 final call.
1801
Georg Brandl4433ff92014-10-31 07:59:37 +01001802``call_list`` is particularly useful for making assertions on "chained calls". A
Michael Foorda9e6fb22012-03-28 14:36:02 +01001803chained call is multiple calls on a single line of code. This results in
1804multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
1805the sequence of calls can be tedious.
1806
1807:meth:`~call.call_list` can construct the sequence of calls from the same
1808chained call:
1809
1810 >>> m = MagicMock()
1811 >>> m(1).method(arg='foo').other('bar')(2.0)
1812 <MagicMock name='mock().method().other()()' id='...'>
1813 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
1814 >>> kall.call_list()
1815 [call(1),
1816 call().method(arg='foo'),
1817 call().method().other('bar'),
1818 call().method().other()(2.0)]
1819 >>> m.mock_calls == kall.call_list()
1820 True
1821
1822.. _calls-as-tuples:
1823
Georg Brandl4433ff92014-10-31 07:59:37 +01001824A ``call`` object is either a tuple of (positional args, keyword args) or
Michael Foorda9e6fb22012-03-28 14:36:02 +01001825(name, positional args, keyword args) depending on how it was constructed. When
Georg Brandl4433ff92014-10-31 07:59:37 +01001826you construct them yourself this isn't particularly interesting, but the ``call``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001827objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
1828:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
1829arguments they contain.
1830
Georg Brandl4433ff92014-10-31 07:59:37 +01001831The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
1832are two-tuples of (positional args, keyword args) whereas the ``call`` objects
Michael Foorda9e6fb22012-03-28 14:36:02 +01001833in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
1834three-tuples of (name, positional args, keyword args).
1835
1836You can use their "tupleness" to pull out the individual arguments for more
1837complex introspection and assertions. The positional arguments are a tuple
1838(an empty tuple if there are no positional arguments) and the keyword
1839arguments are a dictionary:
1840
1841 >>> m = MagicMock(return_value=None)
1842 >>> m(1, 2, 3, arg='one', arg2='two')
1843 >>> kall = m.call_args
1844 >>> args, kwargs = kall
1845 >>> args
1846 (1, 2, 3)
1847 >>> kwargs
1848 {'arg2': 'two', 'arg': 'one'}
1849 >>> args is kall[0]
1850 True
1851 >>> kwargs is kall[1]
1852 True
1853
1854 >>> m = MagicMock()
1855 >>> m.foo(4, 5, 6, arg='two', arg2='three')
1856 <MagicMock name='mock.foo()' id='...'>
1857 >>> kall = m.mock_calls[0]
1858 >>> name, args, kwargs = kall
1859 >>> name
1860 'foo'
1861 >>> args
1862 (4, 5, 6)
1863 >>> kwargs
1864 {'arg2': 'three', 'arg': 'two'}
1865 >>> name is m.mock_calls[0][0]
1866 True
1867
1868
1869create_autospec
Georg Brandlfb134382013-02-03 11:47:49 +01001870~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001871
1872.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
1873
1874 Create a mock object using another object as a spec. Attributes on the
Georg Brandl4433ff92014-10-31 07:59:37 +01001875 mock will use the corresponding attribute on the *spec* object as their
Michael Foorda9e6fb22012-03-28 14:36:02 +01001876 spec.
1877
1878 Functions or methods being mocked will have their arguments checked to
1879 ensure that they are called with the correct signature.
1880
Georg Brandl4433ff92014-10-31 07:59:37 +01001881 If *spec_set* is ``True`` then attempting to set attributes that don't exist
1882 on the spec object will raise an :exc:`AttributeError`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001883
1884 If a class is used as a spec then the return value of the mock (the
1885 instance of the class) will have the same spec. You can use a class as the
Georg Brandl4433ff92014-10-31 07:59:37 +01001886 spec for an instance object by passing ``instance=True``. The returned mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001887 will only be callable if instances of the mock are callable.
1888
Georg Brandl4433ff92014-10-31 07:59:37 +01001889 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to
Michael Foorda9e6fb22012-03-28 14:36:02 +01001890 the constructor of the created mock.
1891
1892See :ref:`auto-speccing` for examples of how to use auto-speccing with
Georg Brandl4433ff92014-10-31 07:59:37 +01001893:func:`create_autospec` and the *autospec* argument to :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001894
1895
1896ANY
Georg Brandlfb134382013-02-03 11:47:49 +01001897~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001898
1899.. data:: ANY
1900
1901Sometimes you may need to make assertions about *some* of the arguments in a
1902call to mock, but either not care about some of the arguments or want to pull
1903them individually out of :attr:`~Mock.call_args` and make more complex
1904assertions on them.
1905
1906To ignore certain arguments you can pass in objects that compare equal to
1907*everything*. Calls to :meth:`~Mock.assert_called_with` and
1908:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
1909passed in.
1910
1911 >>> mock = Mock(return_value=None)
1912 >>> mock('foo', bar=object())
1913 >>> mock.assert_called_once_with('foo', bar=ANY)
1914
Georg Brandl4433ff92014-10-31 07:59:37 +01001915:data:`ANY` can also be used in comparisons with call lists like
Michael Foorda9e6fb22012-03-28 14:36:02 +01001916:attr:`~Mock.mock_calls`:
1917
1918 >>> m = MagicMock(return_value=None)
1919 >>> m(1)
1920 >>> m(1, 2)
1921 >>> m(object())
1922 >>> m.mock_calls == [call(1), call(1, 2), ANY]
1923 True
1924
1925
1926
1927FILTER_DIR
Georg Brandlfb134382013-02-03 11:47:49 +01001928~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001929
1930.. data:: FILTER_DIR
1931
Georg Brandl4433ff92014-10-31 07:59:37 +01001932:data:`FILTER_DIR` is a module level variable that controls the way mock objects
1933respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001934which uses the filtering described below, to only show useful members. If you
1935dislike this filtering, or need to switch it off for diagnostic purposes, then
Georg Brandl4433ff92014-10-31 07:59:37 +01001936set ``mock.FILTER_DIR = False``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001937
Georg Brandl4433ff92014-10-31 07:59:37 +01001938With filtering on, ``dir(some_mock)`` shows only useful attributes and will
Michael Foorda9e6fb22012-03-28 14:36:02 +01001939include any dynamically created attributes that wouldn't normally be shown.
Georg Brandl4433ff92014-10-31 07:59:37 +01001940If the mock was created with a *spec* (or *autospec* of course) then all the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001941attributes from the original are shown, even if they haven't been accessed
1942yet:
1943
1944 >>> dir(Mock())
1945 ['assert_any_call',
1946 'assert_called_once_with',
1947 'assert_called_with',
1948 'assert_has_calls',
1949 'attach_mock',
1950 ...
1951 >>> from urllib import request
1952 >>> dir(Mock(spec=request))
1953 ['AbstractBasicAuthHandler',
1954 'AbstractDigestAuthHandler',
1955 'AbstractHTTPHandler',
1956 'BaseHandler',
1957 ...
1958
Georg Brandl4433ff92014-10-31 07:59:37 +01001959Many of the not-very-useful (private to :class:`Mock` rather than the thing being
Michael Foorda9e6fb22012-03-28 14:36:02 +01001960mocked) underscore and double underscore prefixed attributes have been
Georg Brandl4433ff92014-10-31 07:59:37 +01001961filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this
Michael Foorda9e6fb22012-03-28 14:36:02 +01001962behaviour you can switch it off by setting the module level switch
Georg Brandl4433ff92014-10-31 07:59:37 +01001963:data:`FILTER_DIR`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001964
1965 >>> from unittest import mock
1966 >>> mock.FILTER_DIR = False
1967 >>> dir(mock.Mock())
1968 ['_NonCallableMock__get_return_value',
1969 '_NonCallableMock__get_side_effect',
1970 '_NonCallableMock__return_value_doc',
1971 '_NonCallableMock__set_return_value',
1972 '_NonCallableMock__set_side_effect',
1973 '__call__',
1974 '__class__',
1975 ...
1976
Georg Brandl4433ff92014-10-31 07:59:37 +01001977Alternatively you can just use ``vars(my_mock)`` (instance members) and
1978``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of
1979:data:`mock.FILTER_DIR`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001980
1981
1982mock_open
Georg Brandlfb134382013-02-03 11:47:49 +01001983~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001984
1985.. function:: mock_open(mock=None, read_data=None)
1986
Georg Brandl4433ff92014-10-31 07:59:37 +01001987 A helper function to create a mock to replace the use of :func:`open`. It works
1988 for :func:`open` called directly or used as a context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001989
Georg Brandl4433ff92014-10-31 07:59:37 +01001990 The *mock* argument is the mock object to configure. If ``None`` (the
1991 default) then a :class:`MagicMock` will be created for you, with the API limited
Michael Foorda9e6fb22012-03-28 14:36:02 +01001992 to methods or attributes available on standard file handles.
1993
Georg Brandl4433ff92014-10-31 07:59:37 +01001994 *read_data* is a string for the :meth:`~io.IOBase.read`,
Serhiy Storchaka98b28fd2013-10-13 23:12:09 +03001995 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
Michael Foord04cbe0c2013-03-19 17:22:51 -07001996 of the file handle to return. Calls to those methods will take data from
Georg Brandl4433ff92014-10-31 07:59:37 +01001997 *read_data* until it is depleted. The mock of these methods is pretty
Michael Foord04cbe0c2013-03-19 17:22:51 -07001998 simplistic. If you need more control over the data that you are feeding to
1999 the tested code you will need to customize this mock for yourself.
Georg Brandl4433ff92014-10-31 07:59:37 +01002000 *read_data* is an empty string by default.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002001
Georg Brandl4433ff92014-10-31 07:59:37 +01002002Using :func:`open` as a context manager is a great way to ensure your file handles
Michael Foorda9e6fb22012-03-28 14:36:02 +01002003are closed properly and is becoming common::
2004
2005 with open('/some/path', 'w') as f:
2006 f.write('something')
2007
Georg Brandl4433ff92014-10-31 07:59:37 +01002008The issue is that even if you mock out the call to :func:`open` it is the
2009*returned object* that is used as a context manager (and has :meth:`__enter__` and
2010:meth:`__exit__` called).
Michael Foorda9e6fb22012-03-28 14:36:02 +01002011
2012Mocking context managers with a :class:`MagicMock` is common enough and fiddly
2013enough that a helper function is useful.
2014
2015 >>> m = mock_open()
2016 >>> with patch('__main__.open', m, create=True):
2017 ... with open('foo', 'w') as h:
2018 ... h.write('some stuff')
2019 ...
2020 >>> m.mock_calls
2021 [call('foo', 'w'),
2022 call().__enter__(),
2023 call().write('some stuff'),
2024 call().__exit__(None, None, None)]
2025 >>> m.assert_called_once_with('foo', 'w')
2026 >>> handle = m()
2027 >>> handle.write.assert_called_once_with('some stuff')
2028
2029And for reading files:
2030
2031 >>> with patch('__main__.open', mock_open(read_data='bibble'), create=True) as m:
2032 ... with open('foo') as h:
2033 ... result = h.read()
2034 ...
2035 >>> m.assert_called_once_with('foo')
2036 >>> assert result == 'bibble'
2037
2038
2039.. _auto-speccing:
2040
2041Autospeccing
Georg Brandlfb134382013-02-03 11:47:49 +01002042~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002043
Georg Brandl4433ff92014-10-31 07:59:37 +01002044Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002045api of mocks to the api of an original object (the spec), but it is recursive
2046(implemented lazily) so that attributes of mocks only have the same api as
2047the attributes of the spec. In addition mocked functions / methods have the
Georg Brandl4433ff92014-10-31 07:59:37 +01002048same call signature as the original so they raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002049called incorrectly.
2050
2051Before I explain how auto-speccing works, here's why it is needed.
2052
Georg Brandl4433ff92014-10-31 07:59:37 +01002053:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws
Michael Foorda9e6fb22012-03-28 14:36:02 +01002054when used to mock out objects from a system under test. One of these flaws is
Georg Brandl4433ff92014-10-31 07:59:37 +01002055specific to the :class:`Mock` api and the other is a more general problem with using
Michael Foorda9e6fb22012-03-28 14:36:02 +01002056mock objects.
2057
Georg Brandl4433ff92014-10-31 07:59:37 +01002058First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002059extremely handy: :meth:`~Mock.assert_called_with` and
2060:meth:`~Mock.assert_called_once_with`.
2061
2062 >>> mock = Mock(name='Thing', return_value=None)
2063 >>> mock(1, 2, 3)
2064 >>> mock.assert_called_once_with(1, 2, 3)
2065 >>> mock(1, 2, 3)
2066 >>> mock.assert_called_once_with(1, 2, 3)
2067 Traceback (most recent call last):
2068 ...
Michael Foord28d591c2012-09-28 16:15:22 +01002069 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002070
2071Because mocks auto-create attributes on demand, and allow you to call them
2072with arbitrary arguments, if you misspell one of these assert methods then
2073your assertion is gone:
2074
2075.. code-block:: pycon
2076
2077 >>> mock = Mock(name='Thing', return_value=None)
2078 >>> mock(1, 2, 3)
2079 >>> mock.assret_called_once_with(4, 5, 6)
2080
2081Your tests can pass silently and incorrectly because of the typo.
2082
2083The second issue is more general to mocking. If you refactor some of your
2084code, rename members and so on, any tests for code that is still using the
2085*old api* but uses mocks instead of the real objects will still pass. This
2086means your tests can all pass even though your code is broken.
2087
2088Note that this is another reason why you need integration tests as well as
2089unit tests. Testing everything in isolation is all fine and dandy, but if you
2090don't test how your units are "wired together" there is still lots of room
2091for bugs that tests might have caught.
2092
Georg Brandl4433ff92014-10-31 07:59:37 +01002093:mod:`mock` already provides a feature to help with this, called speccing. If you
2094use a class or instance as the :attr:`spec` for a mock then you can only access
Michael Foorda9e6fb22012-03-28 14:36:02 +01002095attributes on the mock that exist on the real class:
2096
2097 >>> from urllib import request
2098 >>> mock = Mock(spec=request.Request)
2099 >>> mock.assret_called_with
2100 Traceback (most recent call last):
2101 ...
2102 AttributeError: Mock object has no attribute 'assret_called_with'
2103
2104The spec only applies to the mock itself, so we still have the same issue
2105with any methods on the mock:
2106
2107.. code-block:: pycon
2108
2109 >>> mock.has_data()
2110 <mock.Mock object at 0x...>
2111 >>> mock.has_data.assret_called_with()
2112
Georg Brandl4433ff92014-10-31 07:59:37 +01002113Auto-speccing solves this problem. You can either pass ``autospec=True`` to
2114:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a
2115mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002116object that is being replaced will be used as the spec object. Because the
2117speccing is done "lazily" (the spec is created as attributes on the mock are
2118accessed) you can use it with very complex or deeply nested objects (like
2119modules that import modules that import modules) without a big performance
2120hit.
2121
2122Here's an example of it in use:
2123
2124 >>> from urllib import request
2125 >>> patcher = patch('__main__.request', autospec=True)
2126 >>> mock_request = patcher.start()
2127 >>> request is mock_request
2128 True
2129 >>> mock_request.Request
2130 <MagicMock name='request.Request' spec='Request' id='...'>
2131
Georg Brandl4433ff92014-10-31 07:59:37 +01002132You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two
2133arguments in the constructor (one of which is *self*). Here's what happens if
Michael Foorda9e6fb22012-03-28 14:36:02 +01002134we try to call it incorrectly:
2135
2136 >>> req = request.Request()
2137 Traceback (most recent call last):
2138 ...
2139 TypeError: <lambda>() takes at least 2 arguments (1 given)
2140
2141The spec also applies to instantiated classes (i.e. the return value of
2142specced mocks):
2143
2144 >>> req = request.Request('foo')
2145 >>> req
2146 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2147
Georg Brandl4433ff92014-10-31 07:59:37 +01002148:class:`Request` objects are not callable, so the return value of instantiating our
2149mocked out :class:`request.Request` is a non-callable mock. With the spec in place
Michael Foorda9e6fb22012-03-28 14:36:02 +01002150any typos in our asserts will raise the correct error:
2151
2152 >>> req.add_header('spam', 'eggs')
2153 <MagicMock name='request.Request().add_header()' id='...'>
2154 >>> req.add_header.assret_called_with
2155 Traceback (most recent call last):
2156 ...
2157 AttributeError: Mock object has no attribute 'assret_called_with'
2158 >>> req.add_header.assert_called_with('spam', 'eggs')
2159
Georg Brandl4433ff92014-10-31 07:59:37 +01002160In many cases you will just be able to add ``autospec=True`` to your existing
2161:func:`patch` calls and then be protected against bugs due to typos and api
Michael Foorda9e6fb22012-03-28 14:36:02 +01002162changes.
2163
Georg Brandl4433ff92014-10-31 07:59:37 +01002164As well as using *autospec* through :func:`patch` there is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002165:func:`create_autospec` for creating autospecced mocks directly:
2166
2167 >>> from urllib import request
2168 >>> mock_request = create_autospec(request)
2169 >>> mock_request.Request('foo', 'bar')
2170 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2171
2172This isn't without caveats and limitations however, which is why it is not
2173the default behaviour. In order to know what attributes are available on the
2174spec object, autospec has to introspect (access attributes) the spec. As you
2175traverse attributes on the mock a corresponding traversal of the original
2176object is happening under the hood. If any of your specced objects have
2177properties or descriptors that can trigger code execution then you may not be
2178able to use autospec. On the other hand it is much better to design your
2179objects so that introspection is safe [#]_.
2180
2181A more serious problem is that it is common for instance attributes to be
Georg Brandl4433ff92014-10-31 07:59:37 +01002182created in the :meth:`__init__` method and not to exist on the class at all.
2183*autospec* can't know about any dynamically created attributes and restricts
Michael Foorda9e6fb22012-03-28 14:36:02 +01002184the api to visible attributes.
2185
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002186 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002187 ... def __init__(self):
2188 ... self.a = 33
2189 ...
2190 >>> with patch('__main__.Something', autospec=True):
2191 ... thing = Something()
2192 ... thing.a
2193 ...
2194 Traceback (most recent call last):
2195 ...
2196 AttributeError: Mock object has no attribute 'a'
2197
2198There are a few different ways of resolving this problem. The easiest, but
2199not necessarily the least annoying, way is to simply set the required
Georg Brandl4433ff92014-10-31 07:59:37 +01002200attributes on the mock after creation. Just because *autospec* doesn't allow
Michael Foorda9e6fb22012-03-28 14:36:02 +01002201you to fetch attributes that don't exist on the spec it doesn't prevent you
2202setting them:
2203
2204 >>> with patch('__main__.Something', autospec=True):
2205 ... thing = Something()
2206 ... thing.a = 33
2207 ...
2208
Georg Brandl4433ff92014-10-31 07:59:37 +01002209There is a more aggressive version of both *spec* and *autospec* that *does*
Michael Foorda9e6fb22012-03-28 14:36:02 +01002210prevent you setting non-existent attributes. This is useful if you want to
2211ensure your code only *sets* valid attributes too, but obviously it prevents
2212this particular scenario:
2213
2214 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2215 ... thing = Something()
2216 ... thing.a = 33
2217 ...
2218 Traceback (most recent call last):
2219 ...
2220 AttributeError: Mock object has no attribute 'a'
2221
2222Probably the best way of solving the problem is to add class attributes as
Georg Brandl4433ff92014-10-31 07:59:37 +01002223default values for instance members initialised in :meth:`__init__`. Note that if
2224you are only setting default attributes in :meth:`__init__` then providing them via
Michael Foorda9e6fb22012-03-28 14:36:02 +01002225class attributes (shared between instances of course) is faster too. e.g.
2226
2227.. code-block:: python
2228
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002229 class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002230 a = 33
2231
2232This brings up another issue. It is relatively common to provide a default
Georg Brandl4433ff92014-10-31 07:59:37 +01002233value of ``None`` for members that will later be an object of a different type.
2234``None`` would be useless as a spec because it wouldn't let you access *any*
2235attributes or methods on it. As ``None`` is *never* going to be useful as a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002236spec, and probably indicates a member that will normally of some other type,
Georg Brandl4433ff92014-10-31 07:59:37 +01002237autospec doesn't use a spec for members that are set to ``None``. These will
2238just be ordinary mocks (well - MagicMocks):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002239
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002240 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002241 ... member = None
2242 ...
2243 >>> mock = create_autospec(Something)
2244 >>> mock.member.foo.bar.baz()
2245 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2246
2247If modifying your production classes to add defaults isn't to your liking
2248then there are more options. One of these is simply to use an instance as the
2249spec rather than the class. The other is to create a subclass of the
2250production class and add the defaults to the subclass without affecting the
2251production class. Both of these require you to use an alternative object as
Georg Brandl4433ff92014-10-31 07:59:37 +01002252the spec. Thankfully :func:`patch` supports this - you can simply pass the
2253alternative object as the *autospec* argument:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002254
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002255 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002256 ... def __init__(self):
2257 ... self.a = 33
2258 ...
2259 >>> class SomethingForTest(Something):
2260 ... a = 33
2261 ...
2262 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2263 >>> mock = p.start()
2264 >>> mock.a
2265 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2266
2267
2268.. [#] This only applies to classes or already instantiated objects. Calling
2269 a mocked class to create a mock instance *does not* create a real instance.
Georg Brandl4433ff92014-10-31 07:59:37 +01002270 It is only attribute lookups - along with calls to :func:`dir` - that are done.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002271