blob: 6c68a4844d277442e53eccaf9c3c076645845fec [file] [log] [blame]
Michael Foord944e02d2012-03-25 23:12:55 +01001:mod:`unittest.mock` --- helpers
2================================
3
4.. module:: unittest.mock
5 :synopsis: Mock object library.
6.. moduleauthor:: Michael Foord <michael@python.org>
7.. currentmodule:: unittest.mock
8
9.. versionadded:: 3.3
10
11
12sentinel
13--------
14
15.. data:: sentinel
16
17 The ``sentinel`` object provides a convenient way of providing unique
18 objects for your tests.
19
20 Attributes are created on demand when you access them by name. Accessing
21 the same attribute will always return the same object. The objects
22 returned have a sensible repr so that test failure messages are readable.
23
24Sometimes when testing you need to test that a specific object is passed as an
25argument to another method, or returned. It can be common to create named
26sentinel objects to test this. `sentinel` provides a convenient way of
27creating and testing the identity of objects like this.
28
29In this example we monkey patch `method` to return `sentinel.some_object`:
30
31 >>> real = ProductionClass()
32 >>> real.method = Mock(name="method")
33 >>> real.method.return_value = sentinel.some_object
34 >>> result = real.method()
35 >>> assert result is sentinel.some_object
36 >>> sentinel.some_object
37 sentinel.some_object
38
39
40DEFAULT
41-------
42
43
44.. data:: DEFAULT
45
46 The `DEFAULT` object is a pre-created sentinel (actually
47 `sentinel.DEFAULT`). It can be used by :attr:`~Mock.side_effect`
48 functions to indicate that the normal return value should be used.
49
50
51
52call
53----
54
55.. function:: call(*args, **kwargs)
56
57 `call` is a helper object for making simpler assertions, for comparing
58 with :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
59 :attr:`~Mock.mock_calls` and:attr: `~Mock.method_calls`. `call` can also be
60 used with :meth:`~Mock.assert_has_calls`.
61
62 >>> m = MagicMock(return_value=None)
63 >>> m(1, 2, a='foo', b='bar')
64 >>> m()
65 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
66 True
67
68.. method:: call.call_list()
69
70 For a call object that represents multiple calls, `call_list`
71 returns a list of all the intermediate calls as well as the
72 final call.
73
74`call_list` is particularly useful for making assertions on "chained calls". A
75chained call is multiple calls on a single line of code. This results in
76multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
77the sequence of calls can be tedious.
78
79:meth:`~call.call_list` can construct the sequence of calls from the same
80chained call:
81
82 >>> m = MagicMock()
83 >>> m(1).method(arg='foo').other('bar')(2.0)
84 <MagicMock name='mock().method().other()()' id='...'>
85 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
86 >>> kall.call_list()
87 [call(1),
88 call().method(arg='foo'),
89 call().method().other('bar'),
90 call().method().other()(2.0)]
91 >>> m.mock_calls == kall.call_list()
92 True
93
94.. _calls-as-tuples:
95
96A `call` object is either a tuple of (positional args, keyword args) or
97(name, positional args, keyword args) depending on how it was constructed. When
98you construct them yourself this isn't particularly interesting, but the `call`
99objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
100:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
101arguments they contain.
102
103The `call` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
104are two-tuples of (positional args, keyword args) whereas the `call` objects
105in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
106three-tuples of (name, positional args, keyword args).
107
108You can use their "tupleness" to pull out the individual arguments for more
109complex introspection and assertions. The positional arguments are a tuple
110(an empty tuple if there are no positional arguments) and the keyword
111arguments are a dictionary:
112
113 >>> m = MagicMock(return_value=None)
114 >>> m(1, 2, 3, arg='one', arg2='two')
115 >>> kall = m.call_args
116 >>> args, kwargs = kall
117 >>> args
118 (1, 2, 3)
119 >>> kwargs
120 {'arg2': 'two', 'arg': 'one'}
121 >>> args is kall[0]
122 True
123 >>> kwargs is kall[1]
124 True
125
126 >>> m = MagicMock()
127 >>> m.foo(4, 5, 6, arg='two', arg2='three')
128 <MagicMock name='mock.foo()' id='...'>
129 >>> kall = m.mock_calls[0]
130 >>> name, args, kwargs = kall
131 >>> name
132 'foo'
133 >>> args
134 (4, 5, 6)
135 >>> kwargs
136 {'arg2': 'three', 'arg': 'two'}
137 >>> name is m.mock_calls[0][0]
138 True
139
140
141create_autospec
142---------------
143
144.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
145
146 Create a mock object using another object as a spec. Attributes on the
147 mock will use the corresponding attribute on the `spec` object as their
148 spec.
149
150 Functions or methods being mocked will have their arguments checked to
151 ensure that they are called with the correct signature.
152
153 If `spec_set` is `True` then attempting to set attributes that don't exist
154 on the spec object will raise an `AttributeError`.
155
156 If a class is used as a spec then the return value of the mock (the
157 instance of the class) will have the same spec. You can use a class as the
158 spec for an instance object by passing `instance=True`. The returned mock
159 will only be callable if instances of the mock are callable.
160
161 `create_autospec` also takes arbitrary keyword arguments that are passed to
162 the constructor of the created mock.
163
164See :ref:`auto-speccing` for examples of how to use auto-speccing with
165`create_autospec` and the `autospec` argument to :func:`patch`.
166
167
168ANY
169---
170
171.. data:: ANY
172
173Sometimes you may need to make assertions about *some* of the arguments in a
174call to mock, but either not care about some of the arguments or want to pull
175them individually out of :attr:`~Mock.call_args` and make more complex
176assertions on them.
177
178To ignore certain arguments you can pass in objects that compare equal to
179*everything*. Calls to :meth:`~Mock.assert_called_with` and
180:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
181passed in.
182
183 >>> mock = Mock(return_value=None)
184 >>> mock('foo', bar=object())
185 >>> mock.assert_called_once_with('foo', bar=ANY)
186
187`ANY` can also be used in comparisons with call lists like
188:attr:`~Mock.mock_calls`:
189
190 >>> m = MagicMock(return_value=None)
191 >>> m(1)
192 >>> m(1, 2)
193 >>> m(object())
194 >>> m.mock_calls == [call(1), call(1, 2), ANY]
195 True
196
197
198
199FILTER_DIR
200----------
201
202.. data:: FILTER_DIR
203
204`FILTER_DIR` is a module level variable that controls the way mock objects
205respond to `dir` (only for Python 2.6 or more recent). The default is `True`,
206which uses the filtering described below, to only show useful members. If you
207dislike this filtering, or need to switch it off for diagnostic purposes, then
208set `mock.FILTER_DIR = False`.
209
210With filtering on, `dir(some_mock)` shows only useful attributes and will
211include any dynamically created attributes that wouldn't normally be shown.
212If the mock was created with a `spec` (or `autospec` of course) then all the
213attributes from the original are shown, even if they haven't been accessed
214yet:
215
216 >>> dir(Mock())
217 ['assert_any_call',
218 'assert_called_once_with',
219 'assert_called_with',
220 'assert_has_calls',
221 'attach_mock',
222 ...
223 >>> from urllib import request
224 >>> dir(Mock(spec=request))
225 ['AbstractBasicAuthHandler',
226 'AbstractDigestAuthHandler',
227 'AbstractHTTPHandler',
228 'BaseHandler',
229 ...
230
231Many of the not-very-useful (private to `Mock` rather than the thing being
232mocked) underscore and double underscore prefixed attributes have been
233filtered from the result of calling `dir` on a `Mock`. If you dislike this
234behaviour you can switch it off by setting the module level switch
235`FILTER_DIR`:
236
237 >>> from unittest import mock
238 >>> mock.FILTER_DIR = False
239 >>> dir(mock.Mock())
240 ['_NonCallableMock__get_return_value',
241 '_NonCallableMock__get_side_effect',
242 '_NonCallableMock__return_value_doc',
243 '_NonCallableMock__set_return_value',
244 '_NonCallableMock__set_side_effect',
245 '__call__',
246 '__class__',
247 ...
248
249Alternatively you can just use `vars(my_mock)` (instance members) and
250`dir(type(my_mock))` (type members) to bypass the filtering irrespective of
251`mock.FILTER_DIR`.
252
253
254mock_open
255---------
256
257.. function:: mock_open(mock=None, read_data=None)
258
259 A helper function to create a mock to replace the use of `open`. It works
260 for `open` called directly or used as a context manager.
261
262 The `mock` argument is the mock object to configure. If `None` (the
263 default) then a `MagicMock` will be created for you, with the API limited
264 to methods or attributes available on standard file handles.
265
266 `read_data` is a string for the `read` method of the file handle to return.
267 This is an empty string by default.
268
269Using `open` as a context manager is a great way to ensure your file handles
270are closed properly and is becoming common::
271
272 with open('/some/path', 'w') as f:
273 f.write('something')
274
275The issue is that even if you mock out the call to `open` it is the
276*returned object* that is used as a context manager (and has `__enter__` and
277`__exit__` called).
278
279Mocking context managers with a :class:`MagicMock` is common enough and fiddly
280enough that a helper function is useful.
281
282 >>> m = mock_open()
283 >>> with patch('__main__.open', m, create=True):
284 ... with open('foo', 'w') as h:
285 ... h.write('some stuff')
286 ...
287 >>> m.mock_calls
288 [call('foo', 'w'),
289 call().__enter__(),
290 call().write('some stuff'),
291 call().__exit__(None, None, None)]
292 >>> m.assert_called_once_with('foo', 'w')
293 >>> handle = m()
294 >>> handle.write.assert_called_once_with('some stuff')
295
296And for reading files:
297
298 >>> with patch('__main__.open', mock_open(read_data='bibble'), create=True) as m:
299 ... with open('foo') as h:
300 ... result = h.read()
301 ...
302 >>> m.assert_called_once_with('foo')
303 >>> assert result == 'bibble'
304
305
306.. _auto-speccing:
307
308Autospeccing
309------------
310
311Autospeccing is based on the existing `spec` feature of mock. It limits the
312api of mocks to the api of an original object (the spec), but it is recursive
313(implemented lazily) so that attributes of mocks only have the same api as
314the attributes of the spec. In addition mocked functions / methods have the
315same call signature as the original so they raise a `TypeError` if they are
316called incorrectly.
317
318Before I explain how auto-speccing works, here's why it is needed.
319
320`Mock` is a very powerful and flexible object, but it suffers from two flaws
321when used to mock out objects from a system under test. One of these flaws is
322specific to the `Mock` api and the other is a more general problem with using
323mock objects.
324
325First the problem specific to `Mock`. `Mock` has two assert methods that are
326extremely handy: :meth:`~Mock.assert_called_with` and
327:meth:`~Mock.assert_called_once_with`.
328
329 >>> mock = Mock(name='Thing', return_value=None)
330 >>> mock(1, 2, 3)
331 >>> mock.assert_called_once_with(1, 2, 3)
332 >>> mock(1, 2, 3)
333 >>> mock.assert_called_once_with(1, 2, 3)
334 Traceback (most recent call last):
335 ...
336 AssertionError: Expected to be called once. Called 2 times.
337
338Because mocks auto-create attributes on demand, and allow you to call them
339with arbitrary arguments, if you misspell one of these assert methods then
340your assertion is gone:
341
342.. code-block:: pycon
343
344 >>> mock = Mock(name='Thing', return_value=None)
345 >>> mock(1, 2, 3)
346 >>> mock.assret_called_once_with(4, 5, 6)
347
348Your tests can pass silently and incorrectly because of the typo.
349
350The second issue is more general to mocking. If you refactor some of your
351code, rename members and so on, any tests for code that is still using the
352*old api* but uses mocks instead of the real objects will still pass. This
353means your tests can all pass even though your code is broken.
354
355Note that this is another reason why you need integration tests as well as
356unit tests. Testing everything in isolation is all fine and dandy, but if you
357don't test how your units are "wired together" there is still lots of room
358for bugs that tests might have caught.
359
360`mock` already provides a feature to help with this, called speccing. If you
361use a class or instance as the `spec` for a mock then you can only access
362attributes on the mock that exist on the real class:
363
364 >>> from urllib import request
365 >>> mock = Mock(spec=request.Request)
366 >>> mock.assret_called_with
367 Traceback (most recent call last):
368 ...
369 AttributeError: Mock object has no attribute 'assret_called_with'
370
371The spec only applies to the mock itself, so we still have the same issue
372with any methods on the mock:
373
374.. code-block:: pycon
375
376 >>> mock.has_data()
377 <mock.Mock object at 0x...>
378 >>> mock.has_data.assret_called_with()
379
380Auto-speccing solves this problem. You can either pass `autospec=True` to
381`patch` / `patch.object` or use the `create_autospec` function to create a
382mock with a spec. If you use the `autospec=True` argument to `patch` then the
383object that is being replaced will be used as the spec object. Because the
384speccing is done "lazily" (the spec is created as attributes on the mock are
385accessed) you can use it with very complex or deeply nested objects (like
386modules that import modules that import modules) without a big performance
387hit.
388
389Here's an example of it in use:
390
391 >>> from urllib import request
392 >>> patcher = patch('__main__.request', autospec=True)
393 >>> mock_request = patcher.start()
394 >>> request is mock_request
395 True
396 >>> mock_request.Request
397 <MagicMock name='request.Request' spec='Request' id='...'>
398
399You can see that `request.Request` has a spec. `request.Request` takes two
400arguments in the constructor (one of which is `self`). Here's what happens if
401we try to call it incorrectly:
402
403 >>> req = request.Request()
404 Traceback (most recent call last):
405 ...
406 TypeError: <lambda>() takes at least 2 arguments (1 given)
407
408The spec also applies to instantiated classes (i.e. the return value of
409specced mocks):
410
411 >>> req = request.Request('foo')
412 >>> req
413 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
414
415`Request` objects are not callable, so the return value of instantiating our
416mocked out `request.Request` is a non-callable mock. With the spec in place
417any typos in our asserts will raise the correct error:
418
419 >>> req.add_header('spam', 'eggs')
420 <MagicMock name='request.Request().add_header()' id='...'>
421 >>> req.add_header.assret_called_with
422 Traceback (most recent call last):
423 ...
424 AttributeError: Mock object has no attribute 'assret_called_with'
425 >>> req.add_header.assert_called_with('spam', 'eggs')
426
427In many cases you will just be able to add `autospec=True` to your existing
428`patch` calls and then be protected against bugs due to typos and api
429changes.
430
431As well as using `autospec` through `patch` there is a
432:func:`create_autospec` for creating autospecced mocks directly:
433
434 >>> from urllib import request
435 >>> mock_request = create_autospec(request)
436 >>> mock_request.Request('foo', 'bar')
437 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
438
439This isn't without caveats and limitations however, which is why it is not
440the default behaviour. In order to know what attributes are available on the
441spec object, autospec has to introspect (access attributes) the spec. As you
442traverse attributes on the mock a corresponding traversal of the original
443object is happening under the hood. If any of your specced objects have
444properties or descriptors that can trigger code execution then you may not be
445able to use autospec. On the other hand it is much better to design your
446objects so that introspection is safe [#]_.
447
448A more serious problem is that it is common for instance attributes to be
449created in the `__init__` method and not to exist on the class at all.
450`autospec` can't know about any dynamically created attributes and restricts
451the api to visible attributes.
452
453 >>> class Something(object):
454 ... def __init__(self):
455 ... self.a = 33
456 ...
457 >>> with patch('__main__.Something', autospec=True):
458 ... thing = Something()
459 ... thing.a
460 ...
461 Traceback (most recent call last):
462 ...
463 AttributeError: Mock object has no attribute 'a'
464
465There are a few different ways of resolving this problem. The easiest, but
466not necessarily the least annoying, way is to simply set the required
467attributes on the mock after creation. Just because `autospec` doesn't allow
468you to fetch attributes that don't exist on the spec it doesn't prevent you
469setting them:
470
471 >>> with patch('__main__.Something', autospec=True):
472 ... thing = Something()
473 ... thing.a = 33
474 ...
475
476There is a more aggressive version of both `spec` and `autospec` that *does*
477prevent you setting non-existent attributes. This is useful if you want to
478ensure your code only *sets* valid attributes too, but obviously it prevents
479this particular scenario:
480
481 >>> with patch('__main__.Something', autospec=True, spec_set=True):
482 ... thing = Something()
483 ... thing.a = 33
484 ...
485 Traceback (most recent call last):
486 ...
487 AttributeError: Mock object has no attribute 'a'
488
489Probably the best way of solving the problem is to add class attributes as
490default values for instance members initialised in `__init__`. Note that if
491you are only setting default attributes in `__init__` then providing them via
492class attributes (shared between instances of course) is faster too. e.g.
493
494.. code-block:: python
495
496 class Something(object):
497 a = 33
498
499This brings up another issue. It is relatively common to provide a default
500value of `None` for members that will later be an object of a different type.
501`None` would be useless as a spec because it wouldn't let you access *any*
502attributes or methods on it. As `None` is *never* going to be useful as a
503spec, and probably indicates a member that will normally of some other type,
504`autospec` doesn't use a spec for members that are set to `None`. These will
505just be ordinary mocks (well - `MagicMocks`):
506
507 >>> class Something(object):
508 ... member = None
509 ...
510 >>> mock = create_autospec(Something)
511 >>> mock.member.foo.bar.baz()
512 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
513
514If modifying your production classes to add defaults isn't to your liking
515then there are more options. One of these is simply to use an instance as the
516spec rather than the class. The other is to create a subclass of the
517production class and add the defaults to the subclass without affecting the
518production class. Both of these require you to use an alternative object as
519the spec. Thankfully `patch` supports this - you can simply pass the
520alternative object as the `autospec` argument:
521
522 >>> class Something(object):
523 ... def __init__(self):
524 ... self.a = 33
525 ...
526 >>> class SomethingForTest(Something):
527 ... a = 33
528 ...
529 >>> p = patch('__main__.Something', autospec=SomethingForTest)
530 >>> mock = p.start()
531 >>> mock.a
532 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
533
534
535.. [#] This only applies to classes or already instantiated objects. Calling
536 a mocked class to create a mock instance *does not* create a real instance.
537 It is only attribute lookups - along with calls to `dir` - that are done.