blob: f2ebf1131127d5cde16acc28603f7159337f22b6 [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 Brandl7ad3df62014-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 Brandl7ad3df62014-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 Brandl7ad3df62014-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 Brandl7ad3df62014-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 Brandl7ad3df62014-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 Brandl7ad3df62014-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 Brandl7ad3df62014-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 Brandl7ad3df62014-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 Brandl7ad3df62014-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 Brandl7ad3df62014-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 Brandl7ad3df62014-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
Georg Brandl7ad3df62014-10-31 07:59:37 +0100184:class:`Mock` is a flexible mock object intended to replace the use of stubs and
Michael Foord944e02d2012-03-25 23:12:55 +0100185test 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
Georg Brandl7ad3df62014-10-31 07:59:37 +0100190:class:`MagicMock` is a subclass of :class:`Mock` with all the magic methods
Michael Foord944e02d2012-03-25 23:12:55 +0100191pre-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
Georg Brandl7ad3df62014-10-31 07:59:37 +0100196in a particular module with a :class:`Mock` object. By default :func:`patch` will create
197a :class:`MagicMock` for you. You can specify an alternative class of :class:`Mock` using
198the *new_callable* argument to :func:`patch`.
Michael Foord944e02d2012-03-25 23:12:55 +0100199
200
Kushal Das8c145342014-04-16 23:32:21 +0530201.. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)
Michael Foord944e02d2012-03-25 23:12:55 +0100202
Georg Brandl7ad3df62014-10-31 07:59:37 +0100203 Create a new :class:`Mock` object. :class:`Mock` takes several optional arguments
Michael Foord944e02d2012-03-25 23:12:55 +0100204 that specify the behaviour of the Mock object:
205
Georg Brandl7ad3df62014-10-31 07:59:37 +0100206 * *spec*: This can be either a list of strings or an existing object (a
Michael Foord944e02d2012-03-25 23:12:55 +0100207 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).
Georg Brandl7ad3df62014-10-31 07:59:37 +0100210 Accessing any attribute not in this list will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100211
Georg Brandl7ad3df62014-10-31 07:59:37 +0100212 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
Georg Brandl7ad3df62014-10-31 07:59:37 +0100214 allows mocks to pass :func:`isinstance` tests.
Michael Foord944e02d2012-03-25 23:12:55 +0100215
Georg Brandl7ad3df62014-10-31 07:59:37 +0100216 * *spec_set*: A stricter variant of *spec*. If used, attempting to *set*
Michael Foord944e02d2012-03-25 23:12:55 +0100217 or get an attribute on the mock that isn't on the object passed as
Georg Brandl7ad3df62014-10-31 07:59:37 +0100218 *spec_set* will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100219
Georg Brandl7ad3df62014-10-31 07:59:37 +0100220 * *side_effect*: A function to be called whenever the Mock is called. See
Michael Foord944e02d2012-03-25 23:12:55 +0100221 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
Georg Brandl7ad3df62014-10-31 07:59:37 +0100226 Alternatively *side_effect* can be an exception class or instance. In
Michael Foord944e02d2012-03-25 23:12:55 +0100227 this case the exception will be raised when the mock is called.
228
Georg Brandl7ad3df62014-10-31 07:59:37 +0100229 If *side_effect* is an iterable then each call to the mock will return
Michael Foord944e02d2012-03-25 23:12:55 +0100230 the next value from the iterable.
231
Georg Brandl7ad3df62014-10-31 07:59:37 +0100232 A *side_effect* can be cleared by setting it to ``None``.
Michael Foord944e02d2012-03-25 23:12:55 +0100233
Georg Brandl7ad3df62014-10-31 07:59:37 +0100234 * *return_value*: The value returned when the mock is called. By default
Michael Foord944e02d2012-03-25 23:12:55 +0100235 this is a new Mock (created on first access). See the
236 :attr:`return_value` attribute.
237
Georg Brandl7ad3df62014-10-31 07:59:37 +0100238 * *unsafe*: By default if any attribute starts with *assert* or
239 *assret* will raise an :exc:`AttributeError`. Passing ``unsafe=True``
240 will allow access to these attributes.
Kushal Das8c145342014-04-16 23:32:21 +0530241
242 .. versionadded:: 3.5
243
Georg Brandl7ad3df62014-10-31 07:59:37 +0100244 * *wraps*: Item for the mock object to wrap. If *wraps* is not None then
Michael Foord944e02d2012-03-25 23:12:55 +0100245 calling the Mock will pass the call through to the wrapped object
Michael Foord0682a0c2012-04-13 20:51:20 +0100246 (returning the real result). Attribute access on the mock will return a
247 Mock object that wraps the corresponding attribute of the wrapped
248 object (so attempting to access an attribute that doesn't exist will
Georg Brandl7ad3df62014-10-31 07:59:37 +0100249 raise an :exc:`AttributeError`).
Michael Foord944e02d2012-03-25 23:12:55 +0100250
Georg Brandl7ad3df62014-10-31 07:59:37 +0100251 If the mock has an explicit *return_value* set then calls are not passed
252 to the wrapped object and the *return_value* is returned instead.
Michael Foord944e02d2012-03-25 23:12:55 +0100253
Georg Brandl7ad3df62014-10-31 07:59:37 +0100254 * *name*: If the mock has a name then it will be used in the repr of the
Michael Foord944e02d2012-03-25 23:12:55 +0100255 mock. This can be useful for debugging. The name is propagated to child
256 mocks.
257
258 Mocks can also be called with arbitrary keyword arguments. These will be
259 used to set attributes on the mock after it is created. See the
260 :meth:`configure_mock` method for details.
261
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100262 .. method:: assert_called(*args, **kwargs)
263
264 Assert that the mock was called at least once.
265
266 >>> mock = Mock()
267 >>> mock.method()
268 <Mock name='mock.method()' id='...'>
269 >>> mock.method.assert_called()
270
271 .. versionadded:: 3.6
272
273 .. method:: assert_called_once(*args, **kwargs)
274
275 Assert that the mock was called exactly once.
276
277 >>> mock = Mock()
278 >>> mock.method()
279 <Mock name='mock.method()' id='...'>
280 >>> mock.method.assert_called_once()
281 >>> mock.method()
282 <Mock name='mock.method()' id='...'>
283 >>> mock.method.assert_called_once()
284 Traceback (most recent call last):
285 ...
286 AssertionError: Expected 'method' to have been called once. Called 2 times.
287
288 .. versionadded:: 3.6
289
Michael Foord944e02d2012-03-25 23:12:55 +0100290
291 .. method:: assert_called_with(*args, **kwargs)
292
293 This method is a convenient way of asserting that calls are made in a
294 particular way:
295
296 >>> mock = Mock()
297 >>> mock.method(1, 2, 3, test='wow')
298 <Mock name='mock.method()' id='...'>
299 >>> mock.method.assert_called_with(1, 2, 3, test='wow')
300
Michael Foord944e02d2012-03-25 23:12:55 +0100301 .. method:: assert_called_once_with(*args, **kwargs)
302
303 Assert that the mock was called exactly once and with the specified
304 arguments.
305
306 >>> mock = Mock(return_value=None)
307 >>> mock('foo', bar='baz')
308 >>> mock.assert_called_once_with('foo', bar='baz')
309 >>> mock('foo', bar='baz')
310 >>> mock.assert_called_once_with('foo', bar='baz')
311 Traceback (most recent call last):
312 ...
Michael Foord28d591c2012-09-28 16:15:22 +0100313 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foord944e02d2012-03-25 23:12:55 +0100314
315
316 .. method:: assert_any_call(*args, **kwargs)
317
318 assert the mock has been called with the specified arguments.
319
320 The assert passes if the mock has *ever* been called, unlike
321 :meth:`assert_called_with` and :meth:`assert_called_once_with` that
322 only pass if the call is the most recent one.
323
324 >>> mock = Mock(return_value=None)
325 >>> mock(1, 2, arg='thing')
326 >>> mock('some', 'thing', 'else')
327 >>> mock.assert_any_call(1, 2, arg='thing')
328
329
330 .. method:: assert_has_calls(calls, any_order=False)
331
332 assert the mock has been called with the specified calls.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100333 The :attr:`mock_calls` list is checked for the calls.
Michael Foord944e02d2012-03-25 23:12:55 +0100334
Georg Brandl7ad3df62014-10-31 07:59:37 +0100335 If *any_order* is false (the default) then the calls must be
Michael Foord944e02d2012-03-25 23:12:55 +0100336 sequential. There can be extra calls before or after the
337 specified calls.
338
Georg Brandl7ad3df62014-10-31 07:59:37 +0100339 If *any_order* is true then the calls can be in any order, but
Michael Foord944e02d2012-03-25 23:12:55 +0100340 they must all appear in :attr:`mock_calls`.
341
342 >>> mock = Mock(return_value=None)
343 >>> mock(1)
344 >>> mock(2)
345 >>> mock(3)
346 >>> mock(4)
347 >>> calls = [call(2), call(3)]
348 >>> mock.assert_has_calls(calls)
349 >>> calls = [call(4), call(2), call(3)]
350 >>> mock.assert_has_calls(calls, any_order=True)
351
Kushal Das8af9db32014-04-17 01:36:14 +0530352 .. method:: assert_not_called(*args, **kwargs)
353
354 Assert the mock was never called.
355
356 >>> m = Mock()
357 >>> m.hello.assert_not_called()
358 >>> obj = m.hello()
359 >>> m.hello.assert_not_called()
360 Traceback (most recent call last):
361 ...
362 AssertionError: Expected 'hello' to not have been called. Called 1 times.
363
364 .. versionadded:: 3.5
365
Michael Foord944e02d2012-03-25 23:12:55 +0100366
Kushal Das9cd39a12016-06-02 10:20:16 -0700367 .. method:: reset_mock(*, return_value=False, side_effect=False)
Michael Foord944e02d2012-03-25 23:12:55 +0100368
369 The reset_mock method resets all the call attributes on a mock object:
370
371 >>> mock = Mock(return_value=None)
372 >>> mock('hello')
373 >>> mock.called
374 True
375 >>> mock.reset_mock()
376 >>> mock.called
377 False
378
Kushal Das9cd39a12016-06-02 10:20:16 -0700379 .. versionchanged:: 3.6
380 Added two keyword only argument to the reset_mock function.
381
Michael Foord944e02d2012-03-25 23:12:55 +0100382 This can be useful where you want to make a series of assertions that
Georg Brandl7ad3df62014-10-31 07:59:37 +0100383 reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the
Michael Foord944e02d2012-03-25 23:12:55 +0100384 return value, :attr:`side_effect` or any child attributes you have
Kushal Das9cd39a12016-06-02 10:20:16 -0700385 set using normal assignment by default. In case you want to reset
386 *return_value* or :attr:`side_effect`, then pass the corresponding
387 parameter as ``True``. Child mocks and the return value mock
Michael Foord944e02d2012-03-25 23:12:55 +0100388 (if any) are reset as well.
389
Kushal Das9cd39a12016-06-02 10:20:16 -0700390 .. note:: *return_value*, and :attr:`side_effect` are keyword only
391 argument.
392
Michael Foord944e02d2012-03-25 23:12:55 +0100393
394 .. method:: mock_add_spec(spec, spec_set=False)
395
Georg Brandl7ad3df62014-10-31 07:59:37 +0100396 Add a spec to a mock. *spec* can either be an object or a
397 list of strings. Only attributes on the *spec* can be fetched as
Michael Foord944e02d2012-03-25 23:12:55 +0100398 attributes from the mock.
399
Georg Brandl7ad3df62014-10-31 07:59:37 +0100400 If *spec_set* is true then only attributes on the spec can be set.
Michael Foord944e02d2012-03-25 23:12:55 +0100401
402
403 .. method:: attach_mock(mock, attribute)
404
405 Attach a mock as an attribute of this one, replacing its name and
406 parent. Calls to the attached mock will be recorded in the
407 :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
408
409
410 .. method:: configure_mock(**kwargs)
411
412 Set attributes on the mock through keyword arguments.
413
414 Attributes plus return values and side effects can be set on child
415 mocks using standard dot notation and unpacking a dictionary in the
416 method call:
417
418 >>> mock = Mock()
419 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
420 >>> mock.configure_mock(**attrs)
421 >>> mock.method()
422 3
423 >>> mock.other()
424 Traceback (most recent call last):
425 ...
426 KeyError
427
428 The same thing can be achieved in the constructor call to mocks:
429
430 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
431 >>> mock = Mock(some_attribute='eggs', **attrs)
432 >>> mock.some_attribute
433 'eggs'
434 >>> mock.method()
435 3
436 >>> mock.other()
437 Traceback (most recent call last):
438 ...
439 KeyError
440
Georg Brandl7ad3df62014-10-31 07:59:37 +0100441 :meth:`configure_mock` exists to make it easier to do configuration
Michael Foord944e02d2012-03-25 23:12:55 +0100442 after the mock has been created.
443
444
445 .. method:: __dir__()
446
Georg Brandl7ad3df62014-10-31 07:59:37 +0100447 :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results.
448 For mocks with a *spec* this includes all the permitted attributes
Michael Foord944e02d2012-03-25 23:12:55 +0100449 for the mock.
450
451 See :data:`FILTER_DIR` for what this filtering does, and how to
452 switch it off.
453
454
455 .. method:: _get_child_mock(**kw)
456
457 Create the child mocks for attributes and return value.
458 By default child mocks will be the same type as the parent.
459 Subclasses of Mock may want to override this to customize the way
460 child mocks are made.
461
462 For non-callable mocks the callable variant will be used (rather than
463 any custom subclass).
464
465
466 .. attribute:: called
467
468 A boolean representing whether or not the mock object has been called:
469
470 >>> mock = Mock(return_value=None)
471 >>> mock.called
472 False
473 >>> mock()
474 >>> mock.called
475 True
476
477 .. attribute:: call_count
478
479 An integer telling you how many times the mock object has been called:
480
481 >>> mock = Mock(return_value=None)
482 >>> mock.call_count
483 0
484 >>> mock()
485 >>> mock()
486 >>> mock.call_count
487 2
488
489
490 .. attribute:: return_value
491
492 Set this to configure the value returned by calling the mock:
493
494 >>> mock = Mock()
495 >>> mock.return_value = 'fish'
496 >>> mock()
497 'fish'
498
499 The default return value is a mock object and you can configure it in
500 the normal way:
501
502 >>> mock = Mock()
503 >>> mock.return_value.attribute = sentinel.Attribute
504 >>> mock.return_value()
505 <Mock name='mock()()' id='...'>
506 >>> mock.return_value.assert_called_with()
507
Georg Brandl7ad3df62014-10-31 07:59:37 +0100508 :attr:`return_value` can also be set in the constructor:
Michael Foord944e02d2012-03-25 23:12:55 +0100509
510 >>> mock = Mock(return_value=3)
511 >>> mock.return_value
512 3
513 >>> mock()
514 3
515
516
517 .. attribute:: side_effect
518
519 This can either be a function to be called when the mock is called,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100520 an iterable or an exception (class or instance) to be raised.
Michael Foord944e02d2012-03-25 23:12:55 +0100521
522 If you pass in a function it will be called with same arguments as the
523 mock and unless the function returns the :data:`DEFAULT` singleton the
524 call to the mock will then return whatever the function returns. If the
525 function returns :data:`DEFAULT` then the mock will return its normal
Brett Cannon533f1ed2013-05-25 11:28:20 -0400526 value (from the :attr:`return_value`).
Michael Foord944e02d2012-03-25 23:12:55 +0100527
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100528 If you pass in an iterable, it is used to retrieve an iterator which
529 must yield a value on every call. This value can either be an exception
530 instance to be raised, or a value to be returned from the call to the
531 mock (:data:`DEFAULT` handling is identical to the function case).
532
Michael Foord944e02d2012-03-25 23:12:55 +0100533 An example of a mock that raises an exception (to test exception
534 handling of an API):
535
536 >>> mock = Mock()
537 >>> mock.side_effect = Exception('Boom!')
538 >>> mock()
539 Traceback (most recent call last):
540 ...
541 Exception: Boom!
542
Georg Brandl7ad3df62014-10-31 07:59:37 +0100543 Using :attr:`side_effect` to return a sequence of values:
Michael Foord944e02d2012-03-25 23:12:55 +0100544
545 >>> mock = Mock()
546 >>> mock.side_effect = [3, 2, 1]
547 >>> mock(), mock(), mock()
548 (3, 2, 1)
549
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100550 Using a callable:
Michael Foord944e02d2012-03-25 23:12:55 +0100551
552 >>> mock = Mock(return_value=3)
553 >>> def side_effect(*args, **kwargs):
554 ... return DEFAULT
555 ...
556 >>> mock.side_effect = side_effect
557 >>> mock()
558 3
559
Georg Brandl7ad3df62014-10-31 07:59:37 +0100560 :attr:`side_effect` can be set in the constructor. Here's an example that
Michael Foord944e02d2012-03-25 23:12:55 +0100561 adds one to the value the mock is called with and returns it:
562
563 >>> side_effect = lambda value: value + 1
564 >>> mock = Mock(side_effect=side_effect)
565 >>> mock(3)
566 4
567 >>> mock(-8)
568 -7
569
Georg Brandl7ad3df62014-10-31 07:59:37 +0100570 Setting :attr:`side_effect` to ``None`` clears it:
Michael Foord944e02d2012-03-25 23:12:55 +0100571
572 >>> m = Mock(side_effect=KeyError, return_value=3)
573 >>> m()
574 Traceback (most recent call last):
575 ...
576 KeyError
577 >>> m.side_effect = None
578 >>> m()
579 3
580
581
582 .. attribute:: call_args
583
Georg Brandl7ad3df62014-10-31 07:59:37 +0100584 This is either ``None`` (if the mock hasn't been called), or the
Michael Foord944e02d2012-03-25 23:12:55 +0100585 arguments that the mock was last called with. This will be in the
586 form of a tuple: the first member is any ordered arguments the mock
587 was called with (or an empty tuple) and the second member is any
588 keyword arguments (or an empty dictionary).
589
590 >>> mock = Mock(return_value=None)
Berker Peksag920f6db2015-09-10 21:41:15 +0300591 >>> print(mock.call_args)
Michael Foord944e02d2012-03-25 23:12:55 +0100592 None
593 >>> mock()
594 >>> mock.call_args
595 call()
596 >>> mock.call_args == ()
597 True
598 >>> mock(3, 4)
599 >>> mock.call_args
600 call(3, 4)
601 >>> mock.call_args == ((3, 4),)
602 True
603 >>> mock(3, 4, 5, key='fish', next='w00t!')
604 >>> mock.call_args
605 call(3, 4, 5, key='fish', next='w00t!')
606
Georg Brandl7ad3df62014-10-31 07:59:37 +0100607 :attr:`call_args`, along with members of the lists :attr:`call_args_list`,
Michael Foord944e02d2012-03-25 23:12:55 +0100608 :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
609 These are tuples, so they can be unpacked to get at the individual
610 arguments and make more complex assertions. See
611 :ref:`calls as tuples <calls-as-tuples>`.
612
613
614 .. attribute:: call_args_list
615
616 This is a list of all the calls made to the mock object in sequence
617 (so the length of the list is the number of times it has been
618 called). Before any calls have been made it is an empty list. The
619 :data:`call` object can be used for conveniently constructing lists of
Georg Brandl7ad3df62014-10-31 07:59:37 +0100620 calls to compare with :attr:`call_args_list`.
Michael Foord944e02d2012-03-25 23:12:55 +0100621
622 >>> mock = Mock(return_value=None)
623 >>> mock()
624 >>> mock(3, 4)
625 >>> mock(key='fish', next='w00t!')
626 >>> mock.call_args_list
627 [call(), call(3, 4), call(key='fish', next='w00t!')]
628 >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
629 >>> mock.call_args_list == expected
630 True
631
Georg Brandl7ad3df62014-10-31 07:59:37 +0100632 Members of :attr:`call_args_list` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100633 unpacked as tuples to get at the individual arguments. See
634 :ref:`calls as tuples <calls-as-tuples>`.
635
636
637 .. attribute:: method_calls
638
639 As well as tracking calls to themselves, mocks also track calls to
640 methods and attributes, and *their* methods and attributes:
641
642 >>> mock = Mock()
643 >>> mock.method()
644 <Mock name='mock.method()' id='...'>
645 >>> mock.property.method.attribute()
646 <Mock name='mock.property.method.attribute()' id='...'>
647 >>> mock.method_calls
648 [call.method(), call.property.method.attribute()]
649
Georg Brandl7ad3df62014-10-31 07:59:37 +0100650 Members of :attr:`method_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100651 unpacked as tuples to get at the individual arguments. See
652 :ref:`calls as tuples <calls-as-tuples>`.
653
654
655 .. attribute:: mock_calls
656
Georg Brandl7ad3df62014-10-31 07:59:37 +0100657 :attr:`mock_calls` records *all* calls to the mock object, its methods,
658 magic methods *and* return value mocks.
Michael Foord944e02d2012-03-25 23:12:55 +0100659
660 >>> mock = MagicMock()
661 >>> result = mock(1, 2, 3)
662 >>> mock.first(a=3)
663 <MagicMock name='mock.first()' id='...'>
664 >>> mock.second()
665 <MagicMock name='mock.second()' id='...'>
666 >>> int(mock)
667 1
668 >>> result(1)
669 <MagicMock name='mock()()' id='...'>
670 >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
671 ... call.__int__(), call()(1)]
672 >>> mock.mock_calls == expected
673 True
674
Georg Brandl7ad3df62014-10-31 07:59:37 +0100675 Members of :attr:`mock_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100676 unpacked as tuples to get at the individual arguments. See
677 :ref:`calls as tuples <calls-as-tuples>`.
678
679
680 .. attribute:: __class__
681
Georg Brandl7ad3df62014-10-31 07:59:37 +0100682 Normally the :attr:`__class__` attribute of an object will return its type.
683 For a mock object with a :attr:`spec`, ``__class__`` returns the spec class
684 instead. This allows mock objects to pass :func:`isinstance` tests for the
Michael Foord944e02d2012-03-25 23:12:55 +0100685 object they are replacing / masquerading as:
686
687 >>> mock = Mock(spec=3)
688 >>> isinstance(mock, int)
689 True
690
Georg Brandl7ad3df62014-10-31 07:59:37 +0100691 :attr:`__class__` is assignable to, this allows a mock to pass an
692 :func:`isinstance` check without forcing you to use a spec:
Michael Foord944e02d2012-03-25 23:12:55 +0100693
694 >>> mock = Mock()
695 >>> mock.__class__ = dict
696 >>> isinstance(mock, dict)
697 True
698
699.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
700
Georg Brandl7ad3df62014-10-31 07:59:37 +0100701 A non-callable version of :class:`Mock`. The constructor parameters have the same
702 meaning of :class:`Mock`, with the exception of *return_value* and *side_effect*
Michael Foord944e02d2012-03-25 23:12:55 +0100703 which have no meaning on a non-callable mock.
704
Georg Brandl7ad3df62014-10-31 07:59:37 +0100705Mock objects that use a class or an instance as a :attr:`spec` or
706:attr:`spec_set` are able to pass :func:`isinstance` tests:
Michael Foord944e02d2012-03-25 23:12:55 +0100707
708 >>> mock = Mock(spec=SomeClass)
709 >>> isinstance(mock, SomeClass)
710 True
711 >>> mock = Mock(spec_set=SomeClass())
712 >>> isinstance(mock, SomeClass)
713 True
714
Georg Brandl7ad3df62014-10-31 07:59:37 +0100715The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic
Michael Foord944e02d2012-03-25 23:12:55 +0100716methods <magic-methods>` for the full details.
717
718The mock classes and the :func:`patch` decorators all take arbitrary keyword
Georg Brandl7ad3df62014-10-31 07:59:37 +0100719arguments for configuration. For the :func:`patch` decorators the keywords are
Michael Foord944e02d2012-03-25 23:12:55 +0100720passed to the constructor of the mock being created. The keyword arguments
721are for configuring attributes of the mock:
722
723 >>> m = MagicMock(attribute=3, other='fish')
724 >>> m.attribute
725 3
726 >>> m.other
727 'fish'
728
729The return value and side effect of child mocks can be set in the same way,
730using dotted notation. As you can't use dotted names directly in a call you
Georg Brandl7ad3df62014-10-31 07:59:37 +0100731have to create a dictionary and unpack it using ``**``:
Michael Foord944e02d2012-03-25 23:12:55 +0100732
733 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
734 >>> mock = Mock(some_attribute='eggs', **attrs)
735 >>> mock.some_attribute
736 'eggs'
737 >>> mock.method()
738 3
739 >>> mock.other()
740 Traceback (most recent call last):
741 ...
742 KeyError
743
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100744A callable mock which was created with a *spec* (or a *spec_set*) will
745introspect the specification object's signature when matching calls to
746the mock. Therefore, it can match the actual call's arguments regardless
747of whether they were passed positionally or by name::
748
749 >>> def f(a, b, c): pass
750 ...
751 >>> mock = Mock(spec=f)
752 >>> mock(1, 2, c=3)
753 <Mock name='mock()' id='140161580456576'>
754 >>> mock.assert_called_with(1, 2, 3)
755 >>> mock.assert_called_with(a=1, b=2, c=3)
756
757This applies to :meth:`~Mock.assert_called_with`,
758:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and
759:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also
760apply to method calls on the mock object.
761
762 .. versionchanged:: 3.4
763 Added signature introspection on specced and autospecced mock objects.
764
Michael Foord944e02d2012-03-25 23:12:55 +0100765
766.. class:: PropertyMock(*args, **kwargs)
767
768 A mock intended to be used as a property, or other descriptor, on a class.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100769 :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods
770 so you can specify a return value when it is fetched.
Michael Foord944e02d2012-03-25 23:12:55 +0100771
Georg Brandl7ad3df62014-10-31 07:59:37 +0100772 Fetching a :class:`PropertyMock` instance from an object calls the mock, with
Michael Foord944e02d2012-03-25 23:12:55 +0100773 no args. Setting it calls the mock with the value being set.
774
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200775 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100776 ... @property
777 ... def foo(self):
778 ... return 'something'
779 ... @foo.setter
780 ... def foo(self, value):
781 ... pass
782 ...
783 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
784 ... mock_foo.return_value = 'mockity-mock'
785 ... this_foo = Foo()
Berker Peksag920f6db2015-09-10 21:41:15 +0300786 ... print(this_foo.foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100787 ... this_foo.foo = 6
788 ...
789 mockity-mock
790 >>> mock_foo.mock_calls
791 [call(), call(6)]
792
Michael Foordc2870622012-04-13 16:57:22 +0100793Because of the way mock attributes are stored you can't directly attach a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100794:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type
Michael Foordc2870622012-04-13 16:57:22 +0100795object::
796
797 >>> m = MagicMock()
798 >>> p = PropertyMock(return_value=3)
799 >>> type(m).foo = p
800 >>> m.foo
801 3
802 >>> p.assert_called_once_with()
803
Michael Foord944e02d2012-03-25 23:12:55 +0100804
805Calling
806~~~~~~~
807
808Mock objects are callable. The call will return the value set as the
809:attr:`~Mock.return_value` attribute. The default return value is a new Mock
810object; it is created the first time the return value is accessed (either
811explicitly or by calling the Mock) - but it is stored and the same one
812returned each time.
813
814Calls made to the object will be recorded in the attributes
815like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
816
817If :attr:`~Mock.side_effect` is set then it will be called after the call has
Georg Brandl7ad3df62014-10-31 07:59:37 +0100818been recorded, so if :attr:`side_effect` raises an exception the call is still
Michael Foord944e02d2012-03-25 23:12:55 +0100819recorded.
820
821The simplest way to make a mock raise an exception when called is to make
822:attr:`~Mock.side_effect` an exception class or instance:
823
824 >>> m = MagicMock(side_effect=IndexError)
825 >>> m(1, 2, 3)
826 Traceback (most recent call last):
827 ...
828 IndexError
829 >>> m.mock_calls
830 [call(1, 2, 3)]
831 >>> m.side_effect = KeyError('Bang!')
832 >>> m('two', 'three', 'four')
833 Traceback (most recent call last):
834 ...
835 KeyError: 'Bang!'
836 >>> m.mock_calls
837 [call(1, 2, 3), call('two', 'three', 'four')]
838
Georg Brandl7ad3df62014-10-31 07:59:37 +0100839If :attr:`side_effect` is a function then whatever that function returns is what
840calls to the mock return. The :attr:`side_effect` function is called with the
Michael Foord944e02d2012-03-25 23:12:55 +0100841same arguments as the mock. This allows you to vary the return value of the
842call dynamically, based on the input:
843
844 >>> def side_effect(value):
845 ... return value + 1
846 ...
847 >>> m = MagicMock(side_effect=side_effect)
848 >>> m(1)
849 2
850 >>> m(2)
851 3
852 >>> m.mock_calls
853 [call(1), call(2)]
854
855If you want the mock to still return the default return value (a new mock), or
856any set return value, then there are two ways of doing this. Either return
Georg Brandl7ad3df62014-10-31 07:59:37 +0100857:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`:
Michael Foord944e02d2012-03-25 23:12:55 +0100858
859 >>> m = MagicMock()
860 >>> def side_effect(*args, **kwargs):
861 ... return m.return_value
862 ...
863 >>> m.side_effect = side_effect
864 >>> m.return_value = 3
865 >>> m()
866 3
867 >>> def side_effect(*args, **kwargs):
868 ... return DEFAULT
869 ...
870 >>> m.side_effect = side_effect
871 >>> m()
872 3
873
Georg Brandl7ad3df62014-10-31 07:59:37 +0100874To remove a :attr:`side_effect`, and return to the default behaviour, set the
875:attr:`side_effect` to ``None``:
Michael Foord944e02d2012-03-25 23:12:55 +0100876
877 >>> m = MagicMock(return_value=6)
878 >>> def side_effect(*args, **kwargs):
879 ... return 3
880 ...
881 >>> m.side_effect = side_effect
882 >>> m()
883 3
884 >>> m.side_effect = None
885 >>> m()
886 6
887
Georg Brandl7ad3df62014-10-31 07:59:37 +0100888The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock
Michael Foord944e02d2012-03-25 23:12:55 +0100889will return values from the iterable (until the iterable is exhausted and
Georg Brandl7ad3df62014-10-31 07:59:37 +0100890a :exc:`StopIteration` is raised):
Michael Foord944e02d2012-03-25 23:12:55 +0100891
892 >>> m = MagicMock(side_effect=[1, 2, 3])
893 >>> m()
894 1
895 >>> m()
896 2
897 >>> m()
898 3
899 >>> m()
900 Traceback (most recent call last):
901 ...
902 StopIteration
903
Michael Foord2cd48732012-04-21 15:52:11 +0100904If any members of the iterable are exceptions they will be raised instead of
905returned::
906
907 >>> iterable = (33, ValueError, 66)
908 >>> m = MagicMock(side_effect=iterable)
909 >>> m()
910 33
911 >>> m()
912 Traceback (most recent call last):
913 ...
914 ValueError
915 >>> m()
916 66
917
Michael Foord944e02d2012-03-25 23:12:55 +0100918
919.. _deleting-attributes:
920
921Deleting Attributes
922~~~~~~~~~~~~~~~~~~~
923
924Mock objects create attributes on demand. This allows them to pretend to be
925objects of any type.
926
Georg Brandl7ad3df62014-10-31 07:59:37 +0100927You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an
928:exc:`AttributeError` when an attribute is fetched. You can do this by providing
929an object as a :attr:`spec` for a mock, but that isn't always convenient.
Michael Foord944e02d2012-03-25 23:12:55 +0100930
931You "block" attributes by deleting them. Once deleted, accessing an attribute
Georg Brandl7ad3df62014-10-31 07:59:37 +0100932will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100933
934 >>> mock = MagicMock()
935 >>> hasattr(mock, 'm')
936 True
937 >>> del mock.m
938 >>> hasattr(mock, 'm')
939 False
940 >>> del mock.f
941 >>> mock.f
942 Traceback (most recent call last):
943 ...
944 AttributeError: f
945
946
Michael Foordf5752302013-03-18 15:04:03 -0700947Mock names and the name attribute
948~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
949
950Since "name" is an argument to the :class:`Mock` constructor, if you want your
951mock object to have a "name" attribute you can't just pass it in at creation
952time. There are two alternatives. One option is to use
953:meth:`~Mock.configure_mock`::
954
955 >>> mock = MagicMock()
956 >>> mock.configure_mock(name='my_name')
957 >>> mock.name
958 'my_name'
959
960A simpler option is to simply set the "name" attribute after mock creation::
961
962 >>> mock = MagicMock()
963 >>> mock.name = "foo"
964
965
Michael Foord944e02d2012-03-25 23:12:55 +0100966Attaching Mocks as Attributes
967~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
968
969When you attach a mock as an attribute of another mock (or as the return
970value) it becomes a "child" of that mock. Calls to the child are recorded in
971the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
972parent. This is useful for configuring child mocks and then attaching them to
973the parent, or for attaching mocks to a parent that records all calls to the
974children and allows you to make assertions about the order of calls between
975mocks:
976
977 >>> parent = MagicMock()
978 >>> child1 = MagicMock(return_value=None)
979 >>> child2 = MagicMock(return_value=None)
980 >>> parent.child1 = child1
981 >>> parent.child2 = child2
982 >>> child1(1)
983 >>> child2(2)
984 >>> parent.mock_calls
985 [call.child1(1), call.child2(2)]
986
987The exception to this is if the mock has a name. This allows you to prevent
988the "parenting" if for some reason you don't want it to happen.
989
990 >>> mock = MagicMock()
991 >>> not_a_child = MagicMock(name='not-a-child')
992 >>> mock.attribute = not_a_child
993 >>> mock.attribute()
994 <MagicMock name='not-a-child()' id='...'>
995 >>> mock.mock_calls
996 []
997
998Mocks created for you by :func:`patch` are automatically given names. To
999attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
1000method:
1001
1002 >>> thing1 = object()
1003 >>> thing2 = object()
1004 >>> parent = MagicMock()
1005 >>> with patch('__main__.thing1', return_value=None) as child1:
1006 ... with patch('__main__.thing2', return_value=None) as child2:
1007 ... parent.attach_mock(child1, 'child1')
1008 ... parent.attach_mock(child2, 'child2')
1009 ... child1('one')
1010 ... child2('two')
1011 ...
1012 >>> parent.mock_calls
1013 [call.child1('one'), call.child2('two')]
1014
1015
1016.. [#] The only exceptions are magic methods and attributes (those that have
1017 leading and trailing double underscores). Mock doesn't create these but
Georg Brandl7ad3df62014-10-31 07:59:37 +01001018 instead raises an :exc:`AttributeError`. This is because the interpreter
Michael Foord944e02d2012-03-25 23:12:55 +01001019 will often implicitly request these methods, and gets *very* confused to
1020 get a new Mock object when it expects a magic method. If you need magic
1021 method support see :ref:`magic methods <magic-methods>`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001022
1023
1024The patchers
Georg Brandlfb134382013-02-03 11:47:49 +01001025------------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001026
1027The patch decorators are used for patching objects only within the scope of
1028the function they decorate. They automatically handle the unpatching for you,
1029even if exceptions are raised. All of these functions can also be used in with
1030statements or as class decorators.
1031
1032
1033patch
Georg Brandlfb134382013-02-03 11:47:49 +01001034~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001035
1036.. note::
1037
Georg Brandl7ad3df62014-10-31 07:59:37 +01001038 :func:`patch` is straightforward to use. The key is to do the patching in the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001039 right namespace. See the section `where to patch`_.
1040
1041.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1042
Georg Brandl7ad3df62014-10-31 07:59:37 +01001043 :func:`patch` acts as a function decorator, class decorator or a context
1044 manager. Inside the body of the function or with statement, the *target*
1045 is patched with a *new* object. When the function/with statement exits
Michael Foord54b3db82012-03-28 15:08:08 +01001046 the patch is undone.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001047
Georg Brandl7ad3df62014-10-31 07:59:37 +01001048 If *new* is omitted, then the target is replaced with a
1049 :class:`MagicMock`. If :func:`patch` is used as a decorator and *new* is
Michael Foord54b3db82012-03-28 15:08:08 +01001050 omitted, the created mock is passed in as an extra argument to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001051 decorated function. If :func:`patch` is used as a context manager the created
Michael Foord54b3db82012-03-28 15:08:08 +01001052 mock is returned by the context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001053
Georg Brandl7ad3df62014-10-31 07:59:37 +01001054 *target* should be a string in the form ``'package.module.ClassName'``. The
1055 *target* is imported and the specified object replaced with the *new*
1056 object, so the *target* must be importable from the environment you are
1057 calling :func:`patch` from. The target is imported when the decorated function
Michael Foord54b3db82012-03-28 15:08:08 +01001058 is executed, not at decoration time.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001059
Georg Brandl7ad3df62014-10-31 07:59:37 +01001060 The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001061 if patch is creating one for you.
1062
Georg Brandl7ad3df62014-10-31 07:59:37 +01001063 In addition you can pass ``spec=True`` or ``spec_set=True``, which causes
Michael Foorda9e6fb22012-03-28 14:36:02 +01001064 patch to pass in the object being mocked as the spec/spec_set object.
1065
Georg Brandl7ad3df62014-10-31 07:59:37 +01001066 *new_callable* allows you to specify a different class, or callable object,
1067 that will be called to create the *new* object. By default :class:`MagicMock` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001068 used.
1069
Georg Brandl7ad3df62014-10-31 07:59:37 +01001070 A more powerful form of *spec* is *autospec*. If you set ``autospec=True``
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001071 then the mock will be created with a spec from the object being replaced.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001072 All attributes of the mock will also have the spec of the corresponding
1073 attribute of the object being replaced. Methods and functions being mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +01001074 will have their arguments checked and will raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001075 called with the wrong signature. For mocks
1076 replacing a class, their return value (the 'instance') will have the same
1077 spec as the class. See the :func:`create_autospec` function and
1078 :ref:`auto-speccing`.
1079
Georg Brandl7ad3df62014-10-31 07:59:37 +01001080 Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001081 arbitrary object as the spec instead of the one being replaced.
1082
Georg Brandl7ad3df62014-10-31 07:59:37 +01001083 By default :func:`patch` will fail to replace attributes that don't exist. If
1084 you pass in ``create=True``, and the attribute doesn't exist, patch will
Michael Foorda9e6fb22012-03-28 14:36:02 +01001085 create the attribute for you when the patched function is called, and
1086 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001087 attributes that your production code creates at runtime. It is off by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001088 default because it can be dangerous. With it switched on you can write
1089 passing tests against APIs that don't actually exist!
1090
Michael Foordfddcfa22014-04-14 16:25:20 -04001091 .. note::
1092
1093 .. versionchanged:: 3.5
1094 If you are patching builtins in a module then you don't
Georg Brandl7ad3df62014-10-31 07:59:37 +01001095 need to pass ``create=True``, it will be added by default.
Michael Foordfddcfa22014-04-14 16:25:20 -04001096
Georg Brandl7ad3df62014-10-31 07:59:37 +01001097 Patch can be used as a :class:`TestCase` class decorator. It works by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001098 decorating each test method in the class. This reduces the boilerplate
Georg Brandl7ad3df62014-10-31 07:59:37 +01001099 code when your test methods share a common patchings set. :func:`patch` finds
1100 tests by looking for method names that start with ``patch.TEST_PREFIX``.
1101 By default this is ``'test'``, which matches the way :mod:`unittest` finds tests.
1102 You can specify an alternative prefix by setting ``patch.TEST_PREFIX``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001103
1104 Patch can be used as a context manager, with the with statement. Here the
1105 patching applies to the indented block after the with statement. If you
1106 use "as" then the patched object will be bound to the name after the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001107 "as"; very useful if :func:`patch` is creating a mock object for you.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001108
Georg Brandl7ad3df62014-10-31 07:59:37 +01001109 :func:`patch` takes arbitrary keyword arguments. These will be passed to
1110 the :class:`Mock` (or *new_callable*) on construction.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001111
Georg Brandl7ad3df62014-10-31 07:59:37 +01001112 ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001113 available for alternate use-cases.
1114
Georg Brandl7ad3df62014-10-31 07:59:37 +01001115:func:`patch` as function decorator, creating the mock for you and passing it into
Michael Foord90155362012-03-28 15:32:08 +01001116the decorated function:
1117
1118 >>> @patch('__main__.SomeClass')
Michael Foord324b58b2012-03-28 15:49:08 +01001119 ... def function(normal_argument, mock_class):
Michael Foord90155362012-03-28 15:32:08 +01001120 ... print(mock_class is SomeClass)
1121 ...
Michael Foord324b58b2012-03-28 15:49:08 +01001122 >>> function(None)
Michael Foord90155362012-03-28 15:32:08 +01001123 True
Michael Foorda9e6fb22012-03-28 14:36:02 +01001124
Georg Brandl7ad3df62014-10-31 07:59:37 +01001125Patching a class replaces the class with a :class:`MagicMock` *instance*. If the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001126class is instantiated in the code under test then it will be the
1127:attr:`~Mock.return_value` of the mock that will be used.
1128
1129If the class is instantiated multiple times you could use
1130:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
Georg Brandl7ad3df62014-10-31 07:59:37 +01001131can set the *return_value* to be anything you want.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001132
1133To configure return values on methods of *instances* on the patched class
Georg Brandl7ad3df62014-10-31 07:59:37 +01001134you must do this on the :attr:`return_value`. For example:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001135
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001136 >>> class Class:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001137 ... def method(self):
1138 ... pass
1139 ...
1140 >>> with patch('__main__.Class') as MockClass:
1141 ... instance = MockClass.return_value
1142 ... instance.method.return_value = 'foo'
1143 ... assert Class() is instance
1144 ... assert Class().method() == 'foo'
1145 ...
1146
Georg Brandl7ad3df62014-10-31 07:59:37 +01001147If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001148return value of the created mock will have the same spec.
1149
1150 >>> Original = Class
1151 >>> patcher = patch('__main__.Class', spec=True)
1152 >>> MockClass = patcher.start()
1153 >>> instance = MockClass()
1154 >>> assert isinstance(instance, Original)
1155 >>> patcher.stop()
1156
Georg Brandl7ad3df62014-10-31 07:59:37 +01001157The *new_callable* argument is useful where you want to use an alternative
Michael Foorda9e6fb22012-03-28 14:36:02 +01001158class to the default :class:`MagicMock` for the created mock. For example, if
1159you wanted a :class:`NonCallableMock` to be used:
1160
1161 >>> thing = object()
1162 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
1163 ... assert thing is mock_thing
1164 ... thing()
1165 ...
1166 Traceback (most recent call last):
1167 ...
1168 TypeError: 'NonCallableMock' object is not callable
1169
Martin Panter7462b6492015-11-02 03:37:02 +00001170Another use case might be to replace an object with an :class:`io.StringIO` instance:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001171
Serhiy Storchakae79be872013-08-17 00:09:55 +03001172 >>> from io import StringIO
Michael Foorda9e6fb22012-03-28 14:36:02 +01001173 >>> def foo():
Berker Peksag920f6db2015-09-10 21:41:15 +03001174 ... print('Something')
Michael Foorda9e6fb22012-03-28 14:36:02 +01001175 ...
1176 >>> @patch('sys.stdout', new_callable=StringIO)
1177 ... def test(mock_stdout):
1178 ... foo()
1179 ... assert mock_stdout.getvalue() == 'Something\n'
1180 ...
1181 >>> test()
1182
Georg Brandl7ad3df62014-10-31 07:59:37 +01001183When :func:`patch` is creating a mock for you, it is common that the first thing
Michael Foorda9e6fb22012-03-28 14:36:02 +01001184you need to do is to configure the mock. Some of that configuration can be done
1185in the call to patch. Any arbitrary keywords you pass into the call will be
1186used to set attributes on the created mock:
1187
1188 >>> patcher = patch('__main__.thing', first='one', second='two')
1189 >>> mock_thing = patcher.start()
1190 >>> mock_thing.first
1191 'one'
1192 >>> mock_thing.second
1193 'two'
1194
1195As well as attributes on the created mock attributes, like the
1196:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
1197also be configured. These aren't syntactically valid to pass in directly as
1198keyword arguments, but a dictionary with these as keys can still be expanded
Georg Brandl7ad3df62014-10-31 07:59:37 +01001199into a :func:`patch` call using ``**``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001200
1201 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
1202 >>> patcher = patch('__main__.thing', **config)
1203 >>> mock_thing = patcher.start()
1204 >>> mock_thing.method()
1205 3
1206 >>> mock_thing.other()
1207 Traceback (most recent call last):
1208 ...
1209 KeyError
1210
1211
1212patch.object
Georg Brandlfb134382013-02-03 11:47:49 +01001213~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001214
1215.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1216
Georg Brandl7ad3df62014-10-31 07:59:37 +01001217 patch the named member (*attribute*) on an object (*target*) with a mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001218 object.
1219
Georg Brandl7ad3df62014-10-31 07:59:37 +01001220 :func:`patch.object` can be used as a decorator, class decorator or a context
1221 manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and
1222 *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`,
1223 :func:`patch.object` takes arbitrary keyword arguments for configuring the mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001224 object it creates.
1225
Georg Brandl7ad3df62014-10-31 07:59:37 +01001226 When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001227 for choosing which methods to wrap.
1228
Georg Brandl7ad3df62014-10-31 07:59:37 +01001229You can either call :func:`patch.object` with three arguments or two arguments. The
Michael Foorda9e6fb22012-03-28 14:36:02 +01001230three argument form takes the object to be patched, the attribute name and the
1231object to replace the attribute with.
1232
1233When calling with the two argument form you omit the replacement object, and a
1234mock is created for you and passed in as an extra argument to the decorated
1235function:
1236
1237 >>> @patch.object(SomeClass, 'class_method')
1238 ... def test(mock_method):
1239 ... SomeClass.class_method(3)
1240 ... mock_method.assert_called_with(3)
1241 ...
1242 >>> test()
1243
Georg Brandl7ad3df62014-10-31 07:59:37 +01001244*spec*, *create* and the other arguments to :func:`patch.object` have the same
1245meaning as they do for :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001246
1247
1248patch.dict
Georg Brandlfb134382013-02-03 11:47:49 +01001249~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001250
1251.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
1252
1253 Patch a dictionary, or dictionary like object, and restore the dictionary
1254 to its original state after the test.
1255
Georg Brandl7ad3df62014-10-31 07:59:37 +01001256 *in_dict* can be a dictionary or a mapping like container. If it is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01001257 mapping then it must at least support getting, setting and deleting items
1258 plus iterating over keys.
1259
Georg Brandl7ad3df62014-10-31 07:59:37 +01001260 *in_dict* can also be a string specifying the name of the dictionary, which
Michael Foorda9e6fb22012-03-28 14:36:02 +01001261 will then be fetched by importing it.
1262
Georg Brandl7ad3df62014-10-31 07:59:37 +01001263 *values* can be a dictionary of values to set in the dictionary. *values*
1264 can also be an iterable of ``(key, value)`` pairs.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001265
Georg Brandl7ad3df62014-10-31 07:59:37 +01001266 If *clear* is true then the dictionary will be cleared before the new
Michael Foorda9e6fb22012-03-28 14:36:02 +01001267 values are set.
1268
Georg Brandl7ad3df62014-10-31 07:59:37 +01001269 :func:`patch.dict` can also be called with arbitrary keyword arguments to set
Michael Foorda9e6fb22012-03-28 14:36:02 +01001270 values in the dictionary.
1271
Georg Brandl7ad3df62014-10-31 07:59:37 +01001272 :func:`patch.dict` can be used as a context manager, decorator or class
1273 decorator. When used as a class decorator :func:`patch.dict` honours
1274 ``patch.TEST_PREFIX`` for choosing which methods to wrap.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001275
Georg Brandl7ad3df62014-10-31 07:59:37 +01001276:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
Michael Foorda9e6fb22012-03-28 14:36:02 +01001277change a dictionary, and ensure the dictionary is restored when the test
1278ends.
1279
1280 >>> foo = {}
1281 >>> with patch.dict(foo, {'newkey': 'newvalue'}):
1282 ... assert foo == {'newkey': 'newvalue'}
1283 ...
1284 >>> assert foo == {}
1285
1286 >>> import os
1287 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
Berker Peksag920f6db2015-09-10 21:41:15 +03001288 ... print(os.environ['newkey'])
Michael Foorda9e6fb22012-03-28 14:36:02 +01001289 ...
1290 newvalue
1291 >>> assert 'newkey' not in os.environ
1292
Georg Brandl7ad3df62014-10-31 07:59:37 +01001293Keywords can be used in the :func:`patch.dict` call to set values in the dictionary:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001294
1295 >>> mymodule = MagicMock()
1296 >>> mymodule.function.return_value = 'fish'
1297 >>> with patch.dict('sys.modules', mymodule=mymodule):
1298 ... import mymodule
1299 ... mymodule.function('some', 'args')
1300 ...
1301 'fish'
1302
Georg Brandl7ad3df62014-10-31 07:59:37 +01001303:func:`patch.dict` can be used with dictionary like objects that aren't actually
Michael Foorda9e6fb22012-03-28 14:36:02 +01001304dictionaries. At the very minimum they must support item getting, setting,
1305deleting and either iteration or membership test. This corresponds to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001306magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either
1307:meth:`__iter__` or :meth:`__contains__`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001308
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001309 >>> class Container:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001310 ... def __init__(self):
1311 ... self.values = {}
1312 ... def __getitem__(self, name):
1313 ... return self.values[name]
1314 ... def __setitem__(self, name, value):
1315 ... self.values[name] = value
1316 ... def __delitem__(self, name):
1317 ... del self.values[name]
1318 ... def __iter__(self):
1319 ... return iter(self.values)
1320 ...
1321 >>> thing = Container()
1322 >>> thing['one'] = 1
1323 >>> with patch.dict(thing, one=2, two=3):
1324 ... assert thing['one'] == 2
1325 ... assert thing['two'] == 3
1326 ...
1327 >>> assert thing['one'] == 1
1328 >>> assert list(thing) == ['one']
1329
1330
1331patch.multiple
Georg Brandlfb134382013-02-03 11:47:49 +01001332~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001333
1334.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1335
1336 Perform multiple patches in a single call. It takes the object to be
1337 patched (either as an object or a string to fetch the object by importing)
1338 and keyword arguments for the patches::
1339
1340 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1341 ...
1342
Georg Brandl7ad3df62014-10-31 07:59:37 +01001343 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create
Michael Foorda9e6fb22012-03-28 14:36:02 +01001344 mocks for you. In this case the created mocks are passed into a decorated
Georg Brandl7ad3df62014-10-31 07:59:37 +01001345 function by keyword, and a dictionary is returned when :func:`patch.multiple` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001346 used as a context manager.
1347
Georg Brandl7ad3df62014-10-31 07:59:37 +01001348 :func:`patch.multiple` can be used as a decorator, class decorator or a context
1349 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and
1350 *new_callable* have the same meaning as for :func:`patch`. These arguments will
1351 be applied to *all* patches done by :func:`patch.multiple`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001352
Georg Brandl7ad3df62014-10-31 07:59:37 +01001353 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001354 for choosing which methods to wrap.
1355
Georg Brandl7ad3df62014-10-31 07:59:37 +01001356If you want :func:`patch.multiple` to create mocks for you, then you can use
1357:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
Michael Foorda9e6fb22012-03-28 14:36:02 +01001358then the created mocks are passed into the decorated function by keyword.
1359
1360 >>> thing = object()
1361 >>> other = object()
1362
1363 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1364 ... def test_function(thing, other):
1365 ... assert isinstance(thing, MagicMock)
1366 ... assert isinstance(other, MagicMock)
1367 ...
1368 >>> test_function()
1369
Georg Brandl7ad3df62014-10-31 07:59:37 +01001370:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
1371passed by keyword *after* any of the standard arguments created by :func:`patch`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001372
1373 >>> @patch('sys.exit')
1374 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1375 ... def test_function(mock_exit, other, thing):
1376 ... assert 'other' in repr(other)
1377 ... assert 'thing' in repr(thing)
1378 ... assert 'exit' in repr(mock_exit)
1379 ...
1380 >>> test_function()
1381
Georg Brandl7ad3df62014-10-31 07:59:37 +01001382If :func:`patch.multiple` is used as a context manager, the value returned by the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001383context manger is a dictionary where created mocks are keyed by name:
1384
1385 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1386 ... assert 'other' in repr(values['other'])
1387 ... assert 'thing' in repr(values['thing'])
1388 ... assert values['thing'] is thing
1389 ... assert values['other'] is other
1390 ...
1391
1392
1393.. _start-and-stop:
1394
1395patch methods: start and stop
Georg Brandlfb134382013-02-03 11:47:49 +01001396~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001397
Georg Brandl7ad3df62014-10-31 07:59:37 +01001398All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do
1399patching in ``setUp`` methods or where you want to do multiple patches without
Michael Foorda9e6fb22012-03-28 14:36:02 +01001400nesting decorators or with statements.
1401
Georg Brandl7ad3df62014-10-31 07:59:37 +01001402To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as
1403normal and keep a reference to the returned ``patcher`` object. You can then
1404call :meth:`start` to put the patch in place and :meth:`stop` to undo it.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001405
Georg Brandl7ad3df62014-10-31 07:59:37 +01001406If you are using :func:`patch` to create a mock for you then it will be returned by
1407the call to ``patcher.start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001408
1409 >>> patcher = patch('package.module.ClassName')
1410 >>> from package import module
1411 >>> original = module.ClassName
1412 >>> new_mock = patcher.start()
1413 >>> assert module.ClassName is not original
1414 >>> assert module.ClassName is new_mock
1415 >>> patcher.stop()
1416 >>> assert module.ClassName is original
1417 >>> assert module.ClassName is not new_mock
1418
1419
Georg Brandl7ad3df62014-10-31 07:59:37 +01001420A typical use case for this might be for doing multiple patches in the ``setUp``
1421method of a :class:`TestCase`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001422
1423 >>> class MyTest(TestCase):
1424 ... def setUp(self):
1425 ... self.patcher1 = patch('package.module.Class1')
1426 ... self.patcher2 = patch('package.module.Class2')
1427 ... self.MockClass1 = self.patcher1.start()
1428 ... self.MockClass2 = self.patcher2.start()
1429 ...
1430 ... def tearDown(self):
1431 ... self.patcher1.stop()
1432 ... self.patcher2.stop()
1433 ...
1434 ... def test_something(self):
1435 ... assert package.module.Class1 is self.MockClass1
1436 ... assert package.module.Class2 is self.MockClass2
1437 ...
1438 >>> MyTest('test_something').run()
1439
1440.. caution::
1441
1442 If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +01001443 calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001444 exception is raised in the ``setUp`` then ``tearDown`` is not called.
1445 :meth:`unittest.TestCase.addCleanup` makes this easier:
1446
1447 >>> class MyTest(TestCase):
1448 ... def setUp(self):
1449 ... patcher = patch('package.module.Class')
1450 ... self.MockClass = patcher.start()
1451 ... self.addCleanup(patcher.stop)
1452 ...
1453 ... def test_something(self):
1454 ... assert package.module.Class is self.MockClass
1455 ...
1456
Georg Brandl7ad3df62014-10-31 07:59:37 +01001457 As an added bonus you no longer need to keep a reference to the ``patcher``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001458 object.
1459
Michael Foordf7c41582012-06-10 20:36:32 +01001460It is also possible to stop all patches which have been started by using
Georg Brandl7ad3df62014-10-31 07:59:37 +01001461:func:`patch.stopall`.
Michael Foordf7c41582012-06-10 20:36:32 +01001462
1463.. function:: patch.stopall
1464
Georg Brandl7ad3df62014-10-31 07:59:37 +01001465 Stop all active patches. Only stops patches started with ``start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001466
Georg Brandl7ad3df62014-10-31 07:59:37 +01001467
1468.. _patch-builtins:
Michael Foordfddcfa22014-04-14 16:25:20 -04001469
1470patch builtins
Georg Brandl7ad3df62014-10-31 07:59:37 +01001471~~~~~~~~~~~~~~
Michael Foordfddcfa22014-04-14 16:25:20 -04001472You can patch any builtins within a module. The following example patches
Georg Brandl7ad3df62014-10-31 07:59:37 +01001473builtin :func:`ord`:
Michael Foordfddcfa22014-04-14 16:25:20 -04001474
1475 >>> @patch('__main__.ord')
1476 ... def test(mock_ord):
1477 ... mock_ord.return_value = 101
1478 ... print(ord('c'))
1479 ...
1480 >>> test()
1481 101
1482
Michael Foorda9e6fb22012-03-28 14:36:02 +01001483
1484TEST_PREFIX
Georg Brandlfb134382013-02-03 11:47:49 +01001485~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001486
1487All of the patchers can be used as class decorators. When used in this way
1488they wrap every test method on the class. The patchers recognise methods that
Georg Brandl7ad3df62014-10-31 07:59:37 +01001489start with ``'test'`` as being test methods. This is the same way that the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001490:class:`unittest.TestLoader` finds test methods by default.
1491
1492It is possible that you want to use a different prefix for your tests. You can
Georg Brandl7ad3df62014-10-31 07:59:37 +01001493inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001494
1495 >>> patch.TEST_PREFIX = 'foo'
1496 >>> value = 3
1497 >>>
1498 >>> @patch('__main__.value', 'not three')
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001499 ... class Thing:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001500 ... def foo_one(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001501 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001502 ... def foo_two(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001503 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001504 ...
1505 >>>
1506 >>> Thing().foo_one()
1507 not three
1508 >>> Thing().foo_two()
1509 not three
1510 >>> value
1511 3
1512
1513
1514Nesting Patch Decorators
Georg Brandlfb134382013-02-03 11:47:49 +01001515~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001516
1517If you want to perform multiple patches then you can simply stack up the
1518decorators.
1519
1520You can stack up multiple patch decorators using this pattern:
1521
1522 >>> @patch.object(SomeClass, 'class_method')
1523 ... @patch.object(SomeClass, 'static_method')
1524 ... def test(mock1, mock2):
1525 ... assert SomeClass.static_method is mock1
1526 ... assert SomeClass.class_method is mock2
1527 ... SomeClass.static_method('foo')
1528 ... SomeClass.class_method('bar')
1529 ... return mock1, mock2
1530 ...
1531 >>> mock1, mock2 = test()
1532 >>> mock1.assert_called_once_with('foo')
1533 >>> mock2.assert_called_once_with('bar')
1534
1535
1536Note that the decorators are applied from the bottom upwards. This is the
1537standard way that Python applies decorators. The order of the created mocks
1538passed into your test function matches this order.
1539
1540
1541.. _where-to-patch:
1542
1543Where to patch
Georg Brandlfb134382013-02-03 11:47:49 +01001544~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001545
Georg Brandl7ad3df62014-10-31 07:59:37 +01001546:func:`patch` works by (temporarily) changing the object that a *name* points to with
Michael Foorda9e6fb22012-03-28 14:36:02 +01001547another one. There can be many names pointing to any individual object, so
1548for patching to work you must ensure that you patch the name used by the system
1549under test.
1550
1551The basic principle is that you patch where an object is *looked up*, which
1552is not necessarily the same place as where it is defined. A couple of
1553examples will help to clarify this.
1554
1555Imagine we have a project that we want to test with the following structure::
1556
1557 a.py
1558 -> Defines SomeClass
1559
1560 b.py
1561 -> from a import SomeClass
1562 -> some_function instantiates SomeClass
1563
Georg Brandl7ad3df62014-10-31 07:59:37 +01001564Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
1565:func:`patch`. The problem is that when we import module b, which we will have to
1566do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
1567``a.SomeClass`` then it will have no effect on our test; module b already has a
1568reference to the *real* ``SomeClass`` and it looks like our patching had no
Michael Foorda9e6fb22012-03-28 14:36:02 +01001569effect.
1570
Georg Brandl7ad3df62014-10-31 07:59:37 +01001571The key is to patch out ``SomeClass`` where it is used (or where it is looked up
1572). In this case ``some_function`` will actually look up ``SomeClass`` in module b,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001573where we have imported it. The patching should look like::
1574
1575 @patch('b.SomeClass')
1576
Georg Brandl7ad3df62014-10-31 07:59:37 +01001577However, consider the alternative scenario where instead of ``from a import
1578SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both
Michael Foorda9e6fb22012-03-28 14:36:02 +01001579of these import forms are common. In this case the class we want to patch is
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001580being looked up in the module and so we have to patch ``a.SomeClass`` instead::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001581
1582 @patch('a.SomeClass')
1583
1584
1585Patching Descriptors and Proxy Objects
Georg Brandlfb134382013-02-03 11:47:49 +01001586~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001587
1588Both patch_ and patch.object_ correctly patch and restore descriptors: class
1589methods, static methods and properties. You should patch these on the *class*
1590rather than an instance. They also work with *some* objects
Zachary Ware5ea5d2c2014-02-26 09:34:43 -06001591that proxy attribute access, like the `django settings object
Michael Foorda9e6fb22012-03-28 14:36:02 +01001592<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
1593
1594
Michael Foord2309ed82012-03-28 15:38:36 +01001595MagicMock and magic method support
Georg Brandlfb134382013-02-03 11:47:49 +01001596----------------------------------
Michael Foord2309ed82012-03-28 15:38:36 +01001597
1598.. _magic-methods:
1599
1600Mocking Magic Methods
Georg Brandlfb134382013-02-03 11:47:49 +01001601~~~~~~~~~~~~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001602
1603:class:`Mock` supports mocking the Python protocol methods, also known as
1604"magic methods". This allows mock objects to replace containers or other
1605objects that implement Python protocols.
1606
1607Because magic methods are looked up differently from normal methods [#]_, this
1608support has been specially implemented. This means that only specific magic
1609methods are supported. The supported list includes *almost* all of them. If
1610there are any missing that you need please let us know.
1611
1612You mock magic methods by setting the method you are interested in to a function
1613or a mock instance. If you are using a function then it *must* take ``self`` as
1614the first argument [#]_.
1615
1616 >>> def __str__(self):
1617 ... return 'fooble'
1618 ...
1619 >>> mock = Mock()
1620 >>> mock.__str__ = __str__
1621 >>> str(mock)
1622 'fooble'
1623
1624 >>> mock = Mock()
1625 >>> mock.__str__ = Mock()
1626 >>> mock.__str__.return_value = 'fooble'
1627 >>> str(mock)
1628 'fooble'
1629
1630 >>> mock = Mock()
1631 >>> mock.__iter__ = Mock(return_value=iter([]))
1632 >>> list(mock)
1633 []
1634
1635One use case for this is for mocking objects used as context managers in a
Georg Brandl7ad3df62014-10-31 07:59:37 +01001636:keyword:`with` statement:
Michael Foord2309ed82012-03-28 15:38:36 +01001637
1638 >>> mock = Mock()
1639 >>> mock.__enter__ = Mock(return_value='foo')
1640 >>> mock.__exit__ = Mock(return_value=False)
1641 >>> with mock as m:
1642 ... assert m == 'foo'
1643 ...
1644 >>> mock.__enter__.assert_called_with()
1645 >>> mock.__exit__.assert_called_with(None, None, None)
1646
1647Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
1648are recorded in :attr:`~Mock.mock_calls`.
1649
1650.. note::
1651
Georg Brandl7ad3df62014-10-31 07:59:37 +01001652 If you use the *spec* keyword argument to create a mock then attempting to
1653 set a magic method that isn't in the spec will raise an :exc:`AttributeError`.
Michael Foord2309ed82012-03-28 15:38:36 +01001654
1655The full list of supported magic methods is:
1656
1657* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
1658* ``__dir__``, ``__format__`` and ``__subclasses__``
1659* ``__floor__``, ``__trunc__`` and ``__ceil__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001660* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001661 ``__eq__`` and ``__ne__``
1662* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001663 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__``
1664 and ``__missing__``
Michael Foord2309ed82012-03-28 15:38:36 +01001665* Context manager: ``__enter__`` and ``__exit__``
1666* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
1667* The numeric methods (including right hand and in-place variants):
Serhiy Storchakac2ccce72015-03-12 22:01:30 +02001668 ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001669 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
1670 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001671* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``
1672 and ``__index__``
Michael Foord2309ed82012-03-28 15:38:36 +01001673* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
1674* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
1675 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
1676
1677
1678The following methods exist but are *not* supported as they are either in use
1679by mock, can't be set dynamically, or can cause problems:
1680
1681* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
1682* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
1683
1684
1685
1686Magic Mock
Georg Brandlfb134382013-02-03 11:47:49 +01001687~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001688
Georg Brandl7ad3df62014-10-31 07:59:37 +01001689There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001690
1691
1692.. class:: MagicMock(*args, **kw)
1693
1694 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
1695 of most of the magic methods. You can use ``MagicMock`` without having to
1696 configure the magic methods yourself.
1697
1698 The constructor parameters have the same meaning as for :class:`Mock`.
1699
Georg Brandl7ad3df62014-10-31 07:59:37 +01001700 If you use the *spec* or *spec_set* arguments then *only* magic methods
Michael Foord2309ed82012-03-28 15:38:36 +01001701 that exist in the spec will be created.
1702
1703
1704.. class:: NonCallableMagicMock(*args, **kw)
1705
Georg Brandl7ad3df62014-10-31 07:59:37 +01001706 A non-callable version of :class:`MagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001707
1708 The constructor parameters have the same meaning as for
Georg Brandl7ad3df62014-10-31 07:59:37 +01001709 :class:`MagicMock`, with the exception of *return_value* and
1710 *side_effect* which have no meaning on a non-callable mock.
Michael Foord2309ed82012-03-28 15:38:36 +01001711
Georg Brandl7ad3df62014-10-31 07:59:37 +01001712The magic methods are setup with :class:`MagicMock` objects, so you can configure them
Michael Foord2309ed82012-03-28 15:38:36 +01001713and use them in the usual way:
1714
1715 >>> mock = MagicMock()
1716 >>> mock[3] = 'fish'
1717 >>> mock.__setitem__.assert_called_with(3, 'fish')
1718 >>> mock.__getitem__.return_value = 'result'
1719 >>> mock[2]
1720 'result'
1721
1722By default many of the protocol methods are required to return objects of a
1723specific type. These methods are preconfigured with a default return value, so
1724that they can be used without you having to do anything if you aren't interested
1725in the return value. You can still *set* the return value manually if you want
1726to change the default.
1727
1728Methods and their defaults:
1729
1730* ``__lt__``: NotImplemented
1731* ``__gt__``: NotImplemented
1732* ``__le__``: NotImplemented
1733* ``__ge__``: NotImplemented
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001734* ``__int__``: 1
1735* ``__contains__``: False
Berker Peksag8fafc742016-04-11 12:23:04 +03001736* ``__len__``: 0
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001737* ``__iter__``: iter([])
1738* ``__exit__``: False
1739* ``__complex__``: 1j
1740* ``__float__``: 1.0
1741* ``__bool__``: True
1742* ``__index__``: 1
1743* ``__hash__``: default hash for the mock
1744* ``__str__``: default str for the mock
Michael Foord2309ed82012-03-28 15:38:36 +01001745* ``__sizeof__``: default sizeof for the mock
1746
1747For example:
1748
1749 >>> mock = MagicMock()
1750 >>> int(mock)
1751 1
1752 >>> len(mock)
1753 0
1754 >>> list(mock)
1755 []
1756 >>> object() in mock
1757 False
1758
Berker Peksag283f1aa2015-01-07 21:15:02 +02001759The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special.
1760They do the default equality comparison on identity, using the
1761:attr:`~Mock.side_effect` attribute, unless you change their return value to
1762return something else::
Michael Foord2309ed82012-03-28 15:38:36 +01001763
1764 >>> MagicMock() == 3
1765 False
1766 >>> MagicMock() != 3
1767 True
1768 >>> mock = MagicMock()
1769 >>> mock.__eq__.return_value = True
1770 >>> mock == 3
1771 True
1772
Georg Brandl7ad3df62014-10-31 07:59:37 +01001773The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
Michael Foord2309ed82012-03-28 15:38:36 +01001774required to be an iterator:
1775
1776 >>> mock = MagicMock()
1777 >>> mock.__iter__.return_value = ['a', 'b', 'c']
1778 >>> list(mock)
1779 ['a', 'b', 'c']
1780 >>> list(mock)
1781 ['a', 'b', 'c']
1782
1783If the return value *is* an iterator, then iterating over it once will consume
1784it and subsequent iterations will result in an empty list:
1785
1786 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
1787 >>> list(mock)
1788 ['a', 'b', 'c']
1789 >>> list(mock)
1790 []
1791
1792``MagicMock`` has all of the supported magic methods configured except for some
1793of the obscure and obsolete ones. You can still set these up if you want.
1794
1795Magic methods that are supported but not setup by default in ``MagicMock`` are:
1796
1797* ``__subclasses__``
1798* ``__dir__``
1799* ``__format__``
1800* ``__get__``, ``__set__`` and ``__delete__``
1801* ``__reversed__`` and ``__missing__``
1802* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
1803 ``__getstate__`` and ``__setstate__``
1804* ``__getformat__`` and ``__setformat__``
1805
1806
1807
1808.. [#] Magic methods *should* be looked up on the class rather than the
1809 instance. Different versions of Python are inconsistent about applying this
1810 rule. The supported protocol methods should work with all supported versions
1811 of Python.
1812.. [#] The function is basically hooked up to the class, but each ``Mock``
1813 instance is kept isolated from the others.
1814
1815
Michael Foorda9e6fb22012-03-28 14:36:02 +01001816Helpers
Georg Brandlfb134382013-02-03 11:47:49 +01001817-------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001818
1819sentinel
Georg Brandlfb134382013-02-03 11:47:49 +01001820~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001821
1822.. data:: sentinel
1823
1824 The ``sentinel`` object provides a convenient way of providing unique
1825 objects for your tests.
1826
1827 Attributes are created on demand when you access them by name. Accessing
1828 the same attribute will always return the same object. The objects
1829 returned have a sensible repr so that test failure messages are readable.
1830
1831Sometimes when testing you need to test that a specific object is passed as an
1832argument to another method, or returned. It can be common to create named
Georg Brandl7ad3df62014-10-31 07:59:37 +01001833sentinel objects to test this. :data:`sentinel` provides a convenient way of
Michael Foorda9e6fb22012-03-28 14:36:02 +01001834creating and testing the identity of objects like this.
1835
Georg Brandl7ad3df62014-10-31 07:59:37 +01001836In this example we monkey patch ``method`` to return ``sentinel.some_object``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001837
1838 >>> real = ProductionClass()
1839 >>> real.method = Mock(name="method")
1840 >>> real.method.return_value = sentinel.some_object
1841 >>> result = real.method()
1842 >>> assert result is sentinel.some_object
1843 >>> sentinel.some_object
1844 sentinel.some_object
1845
1846
1847DEFAULT
Georg Brandlfb134382013-02-03 11:47:49 +01001848~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001849
1850
1851.. data:: DEFAULT
1852
Georg Brandl7ad3df62014-10-31 07:59:37 +01001853 The :data:`DEFAULT` object is a pre-created sentinel (actually
1854 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001855 functions to indicate that the normal return value should be used.
1856
1857
Michael Foorda9e6fb22012-03-28 14:36:02 +01001858call
Georg Brandlfb134382013-02-03 11:47:49 +01001859~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001860
1861.. function:: call(*args, **kwargs)
1862
Georg Brandl7ad3df62014-10-31 07:59:37 +01001863 :func:`call` is a helper object for making simpler assertions, for comparing with
Georg Brandl24891672012-04-01 13:48:26 +02001864 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
Georg Brandl7ad3df62014-10-31 07:59:37 +01001865 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be
Michael Foorda9e6fb22012-03-28 14:36:02 +01001866 used with :meth:`~Mock.assert_has_calls`.
1867
1868 >>> m = MagicMock(return_value=None)
1869 >>> m(1, 2, a='foo', b='bar')
1870 >>> m()
1871 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
1872 True
1873
1874.. method:: call.call_list()
1875
Georg Brandl7ad3df62014-10-31 07:59:37 +01001876 For a call object that represents multiple calls, :meth:`call_list`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001877 returns a list of all the intermediate calls as well as the
1878 final call.
1879
Georg Brandl7ad3df62014-10-31 07:59:37 +01001880``call_list`` is particularly useful for making assertions on "chained calls". A
Michael Foorda9e6fb22012-03-28 14:36:02 +01001881chained call is multiple calls on a single line of code. This results in
1882multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
1883the sequence of calls can be tedious.
1884
1885:meth:`~call.call_list` can construct the sequence of calls from the same
1886chained call:
1887
1888 >>> m = MagicMock()
1889 >>> m(1).method(arg='foo').other('bar')(2.0)
1890 <MagicMock name='mock().method().other()()' id='...'>
1891 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
1892 >>> kall.call_list()
1893 [call(1),
1894 call().method(arg='foo'),
1895 call().method().other('bar'),
1896 call().method().other()(2.0)]
1897 >>> m.mock_calls == kall.call_list()
1898 True
1899
1900.. _calls-as-tuples:
1901
Georg Brandl7ad3df62014-10-31 07:59:37 +01001902A ``call`` object is either a tuple of (positional args, keyword args) or
Michael Foorda9e6fb22012-03-28 14:36:02 +01001903(name, positional args, keyword args) depending on how it was constructed. When
Georg Brandl7ad3df62014-10-31 07:59:37 +01001904you construct them yourself this isn't particularly interesting, but the ``call``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001905objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
1906:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
1907arguments they contain.
1908
Georg Brandl7ad3df62014-10-31 07:59:37 +01001909The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
1910are two-tuples of (positional args, keyword args) whereas the ``call`` objects
Michael Foorda9e6fb22012-03-28 14:36:02 +01001911in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
1912three-tuples of (name, positional args, keyword args).
1913
1914You can use their "tupleness" to pull out the individual arguments for more
1915complex introspection and assertions. The positional arguments are a tuple
1916(an empty tuple if there are no positional arguments) and the keyword
1917arguments are a dictionary:
1918
1919 >>> m = MagicMock(return_value=None)
1920 >>> m(1, 2, 3, arg='one', arg2='two')
1921 >>> kall = m.call_args
1922 >>> args, kwargs = kall
1923 >>> args
1924 (1, 2, 3)
1925 >>> kwargs
1926 {'arg2': 'two', 'arg': 'one'}
1927 >>> args is kall[0]
1928 True
1929 >>> kwargs is kall[1]
1930 True
1931
1932 >>> m = MagicMock()
1933 >>> m.foo(4, 5, 6, arg='two', arg2='three')
1934 <MagicMock name='mock.foo()' id='...'>
1935 >>> kall = m.mock_calls[0]
1936 >>> name, args, kwargs = kall
1937 >>> name
1938 'foo'
1939 >>> args
1940 (4, 5, 6)
1941 >>> kwargs
1942 {'arg2': 'three', 'arg': 'two'}
1943 >>> name is m.mock_calls[0][0]
1944 True
1945
1946
1947create_autospec
Georg Brandlfb134382013-02-03 11:47:49 +01001948~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001949
1950.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
1951
1952 Create a mock object using another object as a spec. Attributes on the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001953 mock will use the corresponding attribute on the *spec* object as their
Michael Foorda9e6fb22012-03-28 14:36:02 +01001954 spec.
1955
1956 Functions or methods being mocked will have their arguments checked to
1957 ensure that they are called with the correct signature.
1958
Georg Brandl7ad3df62014-10-31 07:59:37 +01001959 If *spec_set* is ``True`` then attempting to set attributes that don't exist
1960 on the spec object will raise an :exc:`AttributeError`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001961
1962 If a class is used as a spec then the return value of the mock (the
1963 instance of the class) will have the same spec. You can use a class as the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001964 spec for an instance object by passing ``instance=True``. The returned mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001965 will only be callable if instances of the mock are callable.
1966
Georg Brandl7ad3df62014-10-31 07:59:37 +01001967 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to
Michael Foorda9e6fb22012-03-28 14:36:02 +01001968 the constructor of the created mock.
1969
1970See :ref:`auto-speccing` for examples of how to use auto-speccing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01001971:func:`create_autospec` and the *autospec* argument to :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001972
1973
1974ANY
Georg Brandlfb134382013-02-03 11:47:49 +01001975~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001976
1977.. data:: ANY
1978
1979Sometimes you may need to make assertions about *some* of the arguments in a
1980call to mock, but either not care about some of the arguments or want to pull
1981them individually out of :attr:`~Mock.call_args` and make more complex
1982assertions on them.
1983
1984To ignore certain arguments you can pass in objects that compare equal to
1985*everything*. Calls to :meth:`~Mock.assert_called_with` and
1986:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
1987passed in.
1988
1989 >>> mock = Mock(return_value=None)
1990 >>> mock('foo', bar=object())
1991 >>> mock.assert_called_once_with('foo', bar=ANY)
1992
Georg Brandl7ad3df62014-10-31 07:59:37 +01001993:data:`ANY` can also be used in comparisons with call lists like
Michael Foorda9e6fb22012-03-28 14:36:02 +01001994:attr:`~Mock.mock_calls`:
1995
1996 >>> m = MagicMock(return_value=None)
1997 >>> m(1)
1998 >>> m(1, 2)
1999 >>> m(object())
2000 >>> m.mock_calls == [call(1), call(1, 2), ANY]
2001 True
2002
2003
2004
2005FILTER_DIR
Georg Brandlfb134382013-02-03 11:47:49 +01002006~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002007
2008.. data:: FILTER_DIR
2009
Georg Brandl7ad3df62014-10-31 07:59:37 +01002010:data:`FILTER_DIR` is a module level variable that controls the way mock objects
2011respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``,
Michael Foorda9e6fb22012-03-28 14:36:02 +01002012which uses the filtering described below, to only show useful members. If you
2013dislike this filtering, or need to switch it off for diagnostic purposes, then
Georg Brandl7ad3df62014-10-31 07:59:37 +01002014set ``mock.FILTER_DIR = False``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002015
Georg Brandl7ad3df62014-10-31 07:59:37 +01002016With filtering on, ``dir(some_mock)`` shows only useful attributes and will
Michael Foorda9e6fb22012-03-28 14:36:02 +01002017include any dynamically created attributes that wouldn't normally be shown.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002018If the mock was created with a *spec* (or *autospec* of course) then all the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002019attributes from the original are shown, even if they haven't been accessed
2020yet:
2021
2022 >>> dir(Mock())
2023 ['assert_any_call',
2024 'assert_called_once_with',
2025 'assert_called_with',
2026 'assert_has_calls',
2027 'attach_mock',
2028 ...
2029 >>> from urllib import request
2030 >>> dir(Mock(spec=request))
2031 ['AbstractBasicAuthHandler',
2032 'AbstractDigestAuthHandler',
2033 'AbstractHTTPHandler',
2034 'BaseHandler',
2035 ...
2036
Georg Brandl7ad3df62014-10-31 07:59:37 +01002037Many of the not-very-useful (private to :class:`Mock` rather than the thing being
Michael Foorda9e6fb22012-03-28 14:36:02 +01002038mocked) underscore and double underscore prefixed attributes have been
Georg Brandl7ad3df62014-10-31 07:59:37 +01002039filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this
Michael Foorda9e6fb22012-03-28 14:36:02 +01002040behaviour you can switch it off by setting the module level switch
Georg Brandl7ad3df62014-10-31 07:59:37 +01002041:data:`FILTER_DIR`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002042
2043 >>> from unittest import mock
2044 >>> mock.FILTER_DIR = False
2045 >>> dir(mock.Mock())
2046 ['_NonCallableMock__get_return_value',
2047 '_NonCallableMock__get_side_effect',
2048 '_NonCallableMock__return_value_doc',
2049 '_NonCallableMock__set_return_value',
2050 '_NonCallableMock__set_side_effect',
2051 '__call__',
2052 '__class__',
2053 ...
2054
Georg Brandl7ad3df62014-10-31 07:59:37 +01002055Alternatively you can just use ``vars(my_mock)`` (instance members) and
2056``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of
2057:data:`mock.FILTER_DIR`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002058
2059
2060mock_open
Georg Brandlfb134382013-02-03 11:47:49 +01002061~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002062
2063.. function:: mock_open(mock=None, read_data=None)
2064
Georg Brandl7ad3df62014-10-31 07:59:37 +01002065 A helper function to create a mock to replace the use of :func:`open`. It works
2066 for :func:`open` called directly or used as a context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002067
Georg Brandl7ad3df62014-10-31 07:59:37 +01002068 The *mock* argument is the mock object to configure. If ``None`` (the
2069 default) then a :class:`MagicMock` will be created for you, with the API limited
Michael Foorda9e6fb22012-03-28 14:36:02 +01002070 to methods or attributes available on standard file handles.
2071
Georg Brandl7ad3df62014-10-31 07:59:37 +01002072 *read_data* is a string for the :meth:`~io.IOBase.read`,
Serhiy Storchaka98b28fd2013-10-13 23:12:09 +03002073 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
Michael Foord04cbe0c2013-03-19 17:22:51 -07002074 of the file handle to return. Calls to those methods will take data from
Georg Brandl7ad3df62014-10-31 07:59:37 +01002075 *read_data* until it is depleted. The mock of these methods is pretty
Robert Collinsca647ef2015-07-24 03:48:20 +12002076 simplistic: every time the *mock* is called, the *read_data* is rewound to
2077 the start. If you need more control over the data that you are feeding to
2078 the tested code you will need to customize this mock for yourself. When that
2079 is insufficient, one of the in-memory filesystem packages on `PyPI
2080 <https://pypi.python.org/pypi>`_ can offer a realistic filesystem for testing.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002081
Robert Collinsf79dfe32015-07-24 04:09:59 +12002082 .. versionchanged:: 3.4
2083 Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support.
2084 The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather
2085 than returning it on each call.
2086
Robert Collins70398392015-07-24 04:10:27 +12002087 .. versionchanged:: 3.5
Robert Collinsf79dfe32015-07-24 04:09:59 +12002088 *read_data* is now reset on each call to the *mock*.
2089
Georg Brandl7ad3df62014-10-31 07:59:37 +01002090Using :func:`open` as a context manager is a great way to ensure your file handles
Michael Foorda9e6fb22012-03-28 14:36:02 +01002091are closed properly and is becoming common::
2092
2093 with open('/some/path', 'w') as f:
2094 f.write('something')
2095
Georg Brandl7ad3df62014-10-31 07:59:37 +01002096The issue is that even if you mock out the call to :func:`open` it is the
2097*returned object* that is used as a context manager (and has :meth:`__enter__` and
2098:meth:`__exit__` called).
Michael Foorda9e6fb22012-03-28 14:36:02 +01002099
2100Mocking context managers with a :class:`MagicMock` is common enough and fiddly
2101enough that a helper function is useful.
2102
2103 >>> m = mock_open()
Michael Foordfddcfa22014-04-14 16:25:20 -04002104 >>> with patch('__main__.open', m):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002105 ... with open('foo', 'w') as h:
2106 ... h.write('some stuff')
2107 ...
2108 >>> m.mock_calls
2109 [call('foo', 'w'),
2110 call().__enter__(),
2111 call().write('some stuff'),
2112 call().__exit__(None, None, None)]
2113 >>> m.assert_called_once_with('foo', 'w')
2114 >>> handle = m()
2115 >>> handle.write.assert_called_once_with('some stuff')
2116
2117And for reading files:
2118
Michael Foordfddcfa22014-04-14 16:25:20 -04002119 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002120 ... with open('foo') as h:
2121 ... result = h.read()
2122 ...
2123 >>> m.assert_called_once_with('foo')
2124 >>> assert result == 'bibble'
2125
2126
2127.. _auto-speccing:
2128
2129Autospeccing
Georg Brandlfb134382013-02-03 11:47:49 +01002130~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002131
Georg Brandl7ad3df62014-10-31 07:59:37 +01002132Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002133api of mocks to the api of an original object (the spec), but it is recursive
2134(implemented lazily) so that attributes of mocks only have the same api as
2135the attributes of the spec. In addition mocked functions / methods have the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002136same call signature as the original so they raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002137called incorrectly.
2138
2139Before I explain how auto-speccing works, here's why it is needed.
2140
Georg Brandl7ad3df62014-10-31 07:59:37 +01002141:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws
Michael Foorda9e6fb22012-03-28 14:36:02 +01002142when used to mock out objects from a system under test. One of these flaws is
Georg Brandl7ad3df62014-10-31 07:59:37 +01002143specific to the :class:`Mock` api and the other is a more general problem with using
Michael Foorda9e6fb22012-03-28 14:36:02 +01002144mock objects.
2145
Georg Brandl7ad3df62014-10-31 07:59:37 +01002146First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002147extremely handy: :meth:`~Mock.assert_called_with` and
2148:meth:`~Mock.assert_called_once_with`.
2149
2150 >>> mock = Mock(name='Thing', return_value=None)
2151 >>> mock(1, 2, 3)
2152 >>> mock.assert_called_once_with(1, 2, 3)
2153 >>> mock(1, 2, 3)
2154 >>> mock.assert_called_once_with(1, 2, 3)
2155 Traceback (most recent call last):
2156 ...
Michael Foord28d591c2012-09-28 16:15:22 +01002157 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002158
2159Because mocks auto-create attributes on demand, and allow you to call them
2160with arbitrary arguments, if you misspell one of these assert methods then
2161your assertion is gone:
2162
2163.. code-block:: pycon
2164
2165 >>> mock = Mock(name='Thing', return_value=None)
2166 >>> mock(1, 2, 3)
2167 >>> mock.assret_called_once_with(4, 5, 6)
2168
2169Your tests can pass silently and incorrectly because of the typo.
2170
2171The second issue is more general to mocking. If you refactor some of your
2172code, rename members and so on, any tests for code that is still using the
2173*old api* but uses mocks instead of the real objects will still pass. This
2174means your tests can all pass even though your code is broken.
2175
2176Note that this is another reason why you need integration tests as well as
2177unit tests. Testing everything in isolation is all fine and dandy, but if you
2178don't test how your units are "wired together" there is still lots of room
2179for bugs that tests might have caught.
2180
Georg Brandl7ad3df62014-10-31 07:59:37 +01002181:mod:`mock` already provides a feature to help with this, called speccing. If you
2182use a class or instance as the :attr:`spec` for a mock then you can only access
Michael Foorda9e6fb22012-03-28 14:36:02 +01002183attributes on the mock that exist on the real class:
2184
2185 >>> from urllib import request
2186 >>> mock = Mock(spec=request.Request)
2187 >>> mock.assret_called_with
2188 Traceback (most recent call last):
2189 ...
2190 AttributeError: Mock object has no attribute 'assret_called_with'
2191
2192The spec only applies to the mock itself, so we still have the same issue
2193with any methods on the mock:
2194
2195.. code-block:: pycon
2196
2197 >>> mock.has_data()
2198 <mock.Mock object at 0x...>
2199 >>> mock.has_data.assret_called_with()
2200
Georg Brandl7ad3df62014-10-31 07:59:37 +01002201Auto-speccing solves this problem. You can either pass ``autospec=True`` to
2202:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a
2203mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002204object that is being replaced will be used as the spec object. Because the
2205speccing is done "lazily" (the spec is created as attributes on the mock are
2206accessed) you can use it with very complex or deeply nested objects (like
2207modules that import modules that import modules) without a big performance
2208hit.
2209
2210Here's an example of it in use:
2211
2212 >>> from urllib import request
2213 >>> patcher = patch('__main__.request', autospec=True)
2214 >>> mock_request = patcher.start()
2215 >>> request is mock_request
2216 True
2217 >>> mock_request.Request
2218 <MagicMock name='request.Request' spec='Request' id='...'>
2219
Georg Brandl7ad3df62014-10-31 07:59:37 +01002220You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two
2221arguments in the constructor (one of which is *self*). Here's what happens if
Michael Foorda9e6fb22012-03-28 14:36:02 +01002222we try to call it incorrectly:
2223
2224 >>> req = request.Request()
2225 Traceback (most recent call last):
2226 ...
2227 TypeError: <lambda>() takes at least 2 arguments (1 given)
2228
2229The spec also applies to instantiated classes (i.e. the return value of
2230specced mocks):
2231
2232 >>> req = request.Request('foo')
2233 >>> req
2234 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2235
Georg Brandl7ad3df62014-10-31 07:59:37 +01002236:class:`Request` objects are not callable, so the return value of instantiating our
2237mocked out :class:`request.Request` is a non-callable mock. With the spec in place
Michael Foorda9e6fb22012-03-28 14:36:02 +01002238any typos in our asserts will raise the correct error:
2239
2240 >>> req.add_header('spam', 'eggs')
2241 <MagicMock name='request.Request().add_header()' id='...'>
2242 >>> req.add_header.assret_called_with
2243 Traceback (most recent call last):
2244 ...
2245 AttributeError: Mock object has no attribute 'assret_called_with'
2246 >>> req.add_header.assert_called_with('spam', 'eggs')
2247
Georg Brandl7ad3df62014-10-31 07:59:37 +01002248In many cases you will just be able to add ``autospec=True`` to your existing
2249:func:`patch` calls and then be protected against bugs due to typos and api
Michael Foorda9e6fb22012-03-28 14:36:02 +01002250changes.
2251
Georg Brandl7ad3df62014-10-31 07:59:37 +01002252As well as using *autospec* through :func:`patch` there is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002253:func:`create_autospec` for creating autospecced mocks directly:
2254
2255 >>> from urllib import request
2256 >>> mock_request = create_autospec(request)
2257 >>> mock_request.Request('foo', 'bar')
2258 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2259
2260This isn't without caveats and limitations however, which is why it is not
2261the default behaviour. In order to know what attributes are available on the
2262spec object, autospec has to introspect (access attributes) the spec. As you
2263traverse attributes on the mock a corresponding traversal of the original
2264object is happening under the hood. If any of your specced objects have
2265properties or descriptors that can trigger code execution then you may not be
2266able to use autospec. On the other hand it is much better to design your
2267objects so that introspection is safe [#]_.
2268
2269A more serious problem is that it is common for instance attributes to be
Georg Brandl7ad3df62014-10-31 07:59:37 +01002270created in the :meth:`__init__` method and not to exist on the class at all.
2271*autospec* can't know about any dynamically created attributes and restricts
Michael Foorda9e6fb22012-03-28 14:36:02 +01002272the api to visible attributes.
2273
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002274 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002275 ... def __init__(self):
2276 ... self.a = 33
2277 ...
2278 >>> with patch('__main__.Something', autospec=True):
2279 ... thing = Something()
2280 ... thing.a
2281 ...
2282 Traceback (most recent call last):
2283 ...
2284 AttributeError: Mock object has no attribute 'a'
2285
2286There are a few different ways of resolving this problem. The easiest, but
2287not necessarily the least annoying, way is to simply set the required
Georg Brandl7ad3df62014-10-31 07:59:37 +01002288attributes on the mock after creation. Just because *autospec* doesn't allow
Michael Foorda9e6fb22012-03-28 14:36:02 +01002289you to fetch attributes that don't exist on the spec it doesn't prevent you
2290setting them:
2291
2292 >>> with patch('__main__.Something', autospec=True):
2293 ... thing = Something()
2294 ... thing.a = 33
2295 ...
2296
Georg Brandl7ad3df62014-10-31 07:59:37 +01002297There is a more aggressive version of both *spec* and *autospec* that *does*
Michael Foorda9e6fb22012-03-28 14:36:02 +01002298prevent you setting non-existent attributes. This is useful if you want to
2299ensure your code only *sets* valid attributes too, but obviously it prevents
2300this particular scenario:
2301
2302 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2303 ... thing = Something()
2304 ... thing.a = 33
2305 ...
2306 Traceback (most recent call last):
2307 ...
2308 AttributeError: Mock object has no attribute 'a'
2309
2310Probably the best way of solving the problem is to add class attributes as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002311default values for instance members initialised in :meth:`__init__`. Note that if
2312you are only setting default attributes in :meth:`__init__` then providing them via
Michael Foorda9e6fb22012-03-28 14:36:02 +01002313class attributes (shared between instances of course) is faster too. e.g.
2314
2315.. code-block:: python
2316
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002317 class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002318 a = 33
2319
2320This brings up another issue. It is relatively common to provide a default
Georg Brandl7ad3df62014-10-31 07:59:37 +01002321value of ``None`` for members that will later be an object of a different type.
2322``None`` would be useless as a spec because it wouldn't let you access *any*
2323attributes or methods on it. As ``None`` is *never* going to be useful as a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002324spec, and probably indicates a member that will normally of some other type,
Georg Brandl7ad3df62014-10-31 07:59:37 +01002325autospec doesn't use a spec for members that are set to ``None``. These will
2326just be ordinary mocks (well - MagicMocks):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002327
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002328 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002329 ... member = None
2330 ...
2331 >>> mock = create_autospec(Something)
2332 >>> mock.member.foo.bar.baz()
2333 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2334
2335If modifying your production classes to add defaults isn't to your liking
2336then there are more options. One of these is simply to use an instance as the
2337spec rather than the class. The other is to create a subclass of the
2338production class and add the defaults to the subclass without affecting the
2339production class. Both of these require you to use an alternative object as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002340the spec. Thankfully :func:`patch` supports this - you can simply pass the
2341alternative object as the *autospec* argument:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002342
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002343 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002344 ... def __init__(self):
2345 ... self.a = 33
2346 ...
2347 >>> class SomethingForTest(Something):
2348 ... a = 33
2349 ...
2350 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2351 >>> mock = p.start()
2352 >>> mock.a
2353 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2354
2355
2356.. [#] This only applies to classes or already instantiated objects. Calling
2357 a mocked class to create a mock instance *does not* create a real instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002358 It is only attribute lookups - along with calls to :func:`dir` - that are done.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002359