python/mock-1.0.0/docs/helpers.txt

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

     1 =========
     2  Helpers
     3 =========
     5 .. currentmodule:: mock
     7 .. testsetup::
     9     mock.FILTER_DIR = True
    10     from pprint import pprint as pp
    11     original_dir = dir
    12     def dir(obj):
    13         print pp(original_dir(obj))
    15     import urllib2
    16     __main__.urllib2 = urllib2
    18 .. testcleanup::
    20     dir = original_dir
    21     mock.FILTER_DIR = True
    25 call
    26 ====
    28 .. function:: call(*args, **kwargs)
    30     `call` is a helper object for making simpler assertions, for comparing
    31     with :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
    32     :attr:`~Mock.mock_calls` and :attr: `~Mock.method_calls`. `call` can also be
    33     used with :meth:`~Mock.assert_has_calls`.
    35     .. doctest::
    37         >>> m = MagicMock(return_value=None)
    38         >>> m(1, 2, a='foo', b='bar')
    39         >>> m()
    40         >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
    41         True
    43 .. method:: call.call_list()
    45     For a call object that represents multiple calls, `call_list`
    46     returns a list of all the intermediate calls as well as the
    47     final call.
    49 `call_list` is particularly useful for making assertions on "chained calls". A
    50 chained call is multiple calls on a single line of code. This results in
    51 multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
    52 the sequence of calls can be tedious.
    54 :meth:`~call.call_list` can construct the sequence of calls from the same
    55 chained call:
    57 .. doctest::
    59     >>> m = MagicMock()
    60     >>> m(1).method(arg='foo').other('bar')(2.0)
    61     <MagicMock name='mock().method().other()()' id='...'>
    62     >>> kall = call(1).method(arg='foo').other('bar')(2.0)
    63     >>> kall.call_list()
    64     [call(1),
    65      call().method(arg='foo'),
    66      call().method().other('bar'),
    67      call().method().other()(2.0)]
    68     >>> m.mock_calls == kall.call_list()
    69     True
    71 .. _calls-as-tuples:
    73 A `call` object is either a tuple of (positional args, keyword args) or
    74 (name, positional args, keyword args) depending on how it was constructed. When
    75 you construct them yourself this isn't particularly interesting, but the `call`
    76 objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
    77 :attr:`Mock.mock_calls` attributes can be introspected to get at the individual
    78 arguments they contain.
    80 The `call` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
    81 are two-tuples of (positional args, keyword args) whereas the `call` objects
    82 in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
    83 three-tuples of (name, positional args, keyword args).
    85 You can use their "tupleness" to pull out the individual arguments for more
    86 complex introspection and assertions. The positional arguments are a tuple
    87 (an empty tuple if there are no positional arguments) and the keyword
    88 arguments are a dictionary:
    90 .. doctest::
    92     >>> m = MagicMock(return_value=None)
    93     >>> m(1, 2, 3, arg='one', arg2='two')
    94     >>> kall = m.call_args
    95     >>> args, kwargs = kall
    96     >>> args
    97     (1, 2, 3)
    98     >>> kwargs
    99     {'arg2': 'two', 'arg': 'one'}
   100     >>> args is kall[0]
   101     True
   102     >>> kwargs is kall[1]
   103     True
   105     >>> m = MagicMock()
   106     >>> m.foo(4, 5, 6, arg='two', arg2='three')
   107     <MagicMock name='mock.foo()' id='...'>
   108     >>> kall = m.mock_calls[0]
   109     >>> name, args, kwargs = kall
   110     >>> name
   111     'foo'
   112     >>> args
   113     (4, 5, 6)
   114     >>> kwargs
   115     {'arg2': 'three', 'arg': 'two'}
   116     >>> name is m.mock_calls[0][0]
   117     True
   120 create_autospec
   121 ===============
   123 .. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
   125     Create a mock object using another object as a spec. Attributes on the
   126     mock will use the corresponding attribute on the `spec` object as their
   127     spec.
   129     Functions or methods being mocked will have their arguments checked to
   130     ensure that they are called with the correct signature.
   132     If `spec_set` is `True` then attempting to set attributes that don't exist
   133     on the spec object will raise an `AttributeError`.
   135     If a class is used as a spec then the return value of the mock (the
   136     instance of the class) will have the same spec. You can use a class as the
   137     spec for an instance object by passing `instance=True`. The returned mock
   138     will only be callable if instances of the mock are callable.
   140     `create_autospec` also takes arbitrary keyword arguments that are passed to
   141     the constructor of the created mock.
   143 See :ref:`auto-speccing` for examples of how to use auto-speccing with
   144 `create_autospec` and the `autospec` argument to :func:`patch`.
   147 ANY
   148 ===
   150 .. data:: ANY
   152 Sometimes you may need to make assertions about *some* of the arguments in a
   153 call to mock, but either not care about some of the arguments or want to pull
   154 them individually out of :attr:`~Mock.call_args` and make more complex
   155 assertions on them.
   157 To ignore certain arguments you can pass in objects that compare equal to
   158 *everything*. Calls to :meth:`~Mock.assert_called_with` and
   159 :meth:`~Mock.assert_called_once_with` will then succeed no matter what was
   160 passed in.
   162 .. doctest::
   164     >>> mock = Mock(return_value=None)
   165     >>> mock('foo', bar=object())
   166     >>> mock.assert_called_once_with('foo', bar=ANY)
   168 `ANY` can also be used in comparisons with call lists like
   169 :attr:`~Mock.mock_calls`:
   171 .. doctest::
   173     >>> m = MagicMock(return_value=None)
   174     >>> m(1)
   175     >>> m(1, 2)
   176     >>> m(object())
   177     >>> m.mock_calls == [call(1), call(1, 2), ANY]
   178     True
   182 FILTER_DIR
   183 ==========
   185 .. data:: FILTER_DIR
   187 `FILTER_DIR` is a module level variable that controls the way mock objects
   188 respond to `dir` (only for Python 2.6 or more recent). The default is `True`,
   189 which uses the filtering described below, to only show useful members. If you
   190 dislike this filtering, or need to switch it off for diagnostic purposes, then
   191 set `mock.FILTER_DIR = False`.
   193 With filtering on, `dir(some_mock)` shows only useful attributes and will
   194 include any dynamically created attributes that wouldn't normally be shown.
   195 If the mock was created with a `spec` (or `autospec` of course) then all the
   196 attributes from the original are shown, even if they haven't been accessed
   197 yet:
   199 .. doctest::
   201     >>> dir(Mock())
   202     ['assert_any_call',
   203      'assert_called_once_with',
   204      'assert_called_with',
   205      'assert_has_calls',
   206      'attach_mock',
   207      ...
   208     >>> import urllib2
   209     >>> dir(Mock(spec=urllib2))
   210     ['AbstractBasicAuthHandler',
   211      'AbstractDigestAuthHandler',
   212      'AbstractHTTPHandler',
   213      'BaseHandler',
   214      ...
   216 Many of the not-very-useful (private to `Mock` rather than the thing being
   217 mocked) underscore and double underscore prefixed attributes have been
   218 filtered from the result of calling `dir` on a `Mock`. If you dislike this
   219 behaviour you can switch it off by setting the module level switch
   220 `FILTER_DIR`:
   222 .. doctest::
   224     >>> import mock
   225     >>> mock.FILTER_DIR = False
   226     >>> dir(mock.Mock())
   227     ['_NonCallableMock__get_return_value',
   228      '_NonCallableMock__get_side_effect',
   229      '_NonCallableMock__return_value_doc',
   230      '_NonCallableMock__set_return_value',
   231      '_NonCallableMock__set_side_effect',
   232      '__call__',
   233      '__class__',
   234      ...
   236 Alternatively you can just use `vars(my_mock)` (instance members) and
   237 `dir(type(my_mock))` (type members) to bypass the filtering irrespective of
   238 `mock.FILTER_DIR`.
   241 mock_open
   242 =========
   244 .. function:: mock_open(mock=None, read_data=None)
   246     A helper function to create a mock to replace the use of `open`. It works
   247     for `open` called directly or used as a context manager.
   249     The `mock` argument is the mock object to configure. If `None` (the
   250     default) then a `MagicMock` will be created for you, with the API limited
   251     to methods or attributes available on standard file handles.
   253     `read_data` is a string for the `read` method of the file handle to return.
   254     This is an empty string by default.
   256 Using `open` as a context manager is a great way to ensure your file handles
   257 are closed properly and is becoming common::
   259     with open('/some/path', 'w') as f:
   260         f.write('something')
   262 The issue is that even if you mock out the call to `open` it is the
   263 *returned object* that is used as a context manager (and has `__enter__` and
   264 `__exit__` called).
   266 Mocking context managers with a :class:`MagicMock` is common enough and fiddly
   267 enough that a helper function is useful.
   269 .. doctest::
   271     >>> from mock import mock_open
   272     >>> m = mock_open()
   273     >>> with patch('__main__.open', m, create=True):
   274     ...     with open('foo', 'w') as h:
   275     ...         h.write('some stuff')
   276     ...
   277     >>> m.mock_calls
   278     [call('foo', 'w'),
   279      call().__enter__(),
   280      call().write('some stuff'),
   281      call().__exit__(None, None, None)]
   282     >>> m.assert_called_once_with('foo', 'w')
   283     >>> handle = m()
   284     >>> handle.write.assert_called_once_with('some stuff')
   286 And for reading files:
   288 .. doctest::
   290     >>> with patch('__main__.open', mock_open(read_data='bibble'), create=True) as m:
   291     ...     with open('foo') as h:
   292     ...         result = h.read()
   293     ...
   294     >>> m.assert_called_once_with('foo')
   295     >>> assert result == 'bibble'
   298 .. _auto-speccing:
   300 Autospeccing
   301 ============
   303 Autospeccing is based on the existing `spec` feature of mock. It limits the
   304 api of mocks to the api of an original object (the spec), but it is recursive
   305 (implemented lazily) so that attributes of mocks only have the same api as
   306 the attributes of the spec. In addition mocked functions / methods have the
   307 same call signature as the original so they raise a `TypeError` if they are
   308 called incorrectly.
   310 Before I explain how auto-speccing works, here's why it is needed.
   312 `Mock` is a very powerful and flexible object, but it suffers from two flaws
   313 when used to mock out objects from a system under test. One of these flaws is
   314 specific to the `Mock` api and the other is a more general problem with using
   315 mock objects.
   317 First the problem specific to `Mock`. `Mock` has two assert methods that are
   318 extremely handy: :meth:`~Mock.assert_called_with` and
   319 :meth:`~Mock.assert_called_once_with`.
   321 .. doctest::
   323     >>> mock = Mock(name='Thing', return_value=None)
   324     >>> mock(1, 2, 3)
   325     >>> mock.assert_called_once_with(1, 2, 3)
   326     >>> mock(1, 2, 3)
   327     >>> mock.assert_called_once_with(1, 2, 3)
   328     Traceback (most recent call last):
   329      ...
   330     AssertionError: Expected to be called once. Called 2 times.
   332 Because mocks auto-create attributes on demand, and allow you to call them
   333 with arbitrary arguments, if you misspell one of these assert methods then
   334 your assertion is gone:
   336 .. code-block:: pycon
   338     >>> mock = Mock(name='Thing', return_value=None)
   339     >>> mock(1, 2, 3)
   340     >>> mock.assret_called_once_with(4, 5, 6)
   342 Your tests can pass silently and incorrectly because of the typo.
   344 The second issue is more general to mocking. If you refactor some of your
   345 code, rename members and so on, any tests for code that is still using the
   346 *old api* but uses mocks instead of the real objects will still pass. This
   347 means your tests can all pass even though your code is broken.
   349 Note that this is another reason why you need integration tests as well as
   350 unit tests. Testing everything in isolation is all fine and dandy, but if you
   351 don't test how your units are "wired together" there is still lots of room
   352 for bugs that tests might have caught.
   354 `mock` already provides a feature to help with this, called speccing. If you
   355 use a class or instance as the `spec` for a mock then you can only access
   356 attributes on the mock that exist on the real class:
   358 .. doctest::
   360     >>> import urllib2
   361     >>> mock = Mock(spec=urllib2.Request)
   362     >>> mock.assret_called_with
   363     Traceback (most recent call last):
   364      ...
   365     AttributeError: Mock object has no attribute 'assret_called_with'
   367 The spec only applies to the mock itself, so we still have the same issue
   368 with any methods on the mock:
   370 .. code-block:: pycon
   372     >>> mock.has_data()
   373     <mock.Mock object at 0x...>
   374     >>> mock.has_data.assret_called_with()
   376 Auto-speccing solves this problem. You can either pass `autospec=True` to
   377 `patch` / `patch.object` or use the `create_autospec` function to create a
   378 mock with a spec. If you use the `autospec=True` argument to `patch` then the
   379 object that is being replaced will be used as the spec object. Because the
   380 speccing is done "lazily" (the spec is created as attributes on the mock are
   381 accessed) you can use it with very complex or deeply nested objects (like
   382 modules that import modules that import modules) without a big performance
   383 hit.
   385 Here's an example of it in use:
   387 .. doctest::
   389     >>> import urllib2
   390     >>> patcher = patch('__main__.urllib2', autospec=True)
   391     >>> mock_urllib2 = patcher.start()
   392     >>> urllib2 is mock_urllib2
   393     True
   394     >>> urllib2.Request
   395     <MagicMock name='urllib2.Request' spec='Request' id='...'>
   397 You can see that `urllib2.Request` has a spec. `urllib2.Request` takes two
   398 arguments in the constructor (one of which is `self`). Here's what happens if
   399 we try to call it incorrectly:
   401 .. doctest::
   403     >>> req = urllib2.Request()
   404     Traceback (most recent call last):
   405      ...
   406     TypeError: <lambda>() takes at least 2 arguments (1 given)
   408 The spec also applies to instantiated classes (i.e. the return value of
   409 specced mocks):
   411 .. doctest::
   413     >>> req = urllib2.Request('foo')
   414     >>> req
   415     <NonCallableMagicMock name='urllib2.Request()' spec='Request' id='...'>
   417 `Request` objects are not callable, so the return value of instantiating our
   418 mocked out `urllib2.Request` is a non-callable mock. With the spec in place
   419 any typos in our asserts will raise the correct error:
   421 .. doctest::
   423     >>> req.add_header('spam', 'eggs')
   424     <MagicMock name='urllib2.Request().add_header()' id='...'>
   425     >>> req.add_header.assret_called_with
   426     Traceback (most recent call last):
   427      ...
   428     AttributeError: Mock object has no attribute 'assret_called_with'
   429     >>> req.add_header.assert_called_with('spam', 'eggs')
   431 In many cases you will just be able to add `autospec=True` to your existing
   432 `patch` calls and then be protected against bugs due to typos and api
   433 changes.
   435 As well as using `autospec` through `patch` there is a
   436 :func:`create_autospec` for creating autospecced mocks directly:
   438 .. doctest::
   440     >>> import urllib2
   441     >>> mock_urllib2 = create_autospec(urllib2)
   442     >>> mock_urllib2.Request('foo', 'bar')
   443     <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
   445 This isn't without caveats and limitations however, which is why it is not
   446 the default behaviour. In order to know what attributes are available on the
   447 spec object, autospec has to introspect (access attributes) the spec. As you
   448 traverse attributes on the mock a corresponding traversal of the original
   449 object is happening under the hood. If any of your specced objects have
   450 properties or descriptors that can trigger code execution then you may not be
   451 able to use autospec. On the other hand it is much better to design your
   452 objects so that introspection is safe [#]_.
   454 A more serious problem is that it is common for instance attributes to be
   455 created in the `__init__` method and not to exist on the class at all.
   456 `autospec` can't know about any dynamically created attributes and restricts
   457 the api to visible attributes.
   459 .. doctest::
   461     >>> class Something(object):
   462     ...   def __init__(self):
   463     ...     self.a = 33
   464     ...
   465     >>> with patch('__main__.Something', autospec=True):
   466     ...   thing = Something()
   467     ...   thing.a
   468     ...
   469     Traceback (most recent call last):
   470       ...
   471     AttributeError: Mock object has no attribute 'a'
   473 There are a few different ways of resolving this problem. The easiest, but
   474 not necessarily the least annoying, way is to simply set the required
   475 attributes on the mock after creation. Just because `autospec` doesn't allow
   476 you to fetch attributes that don't exist on the spec it doesn't prevent you
   477 setting them:
   479 .. doctest::
   481     >>> with patch('__main__.Something', autospec=True):
   482     ...   thing = Something()
   483     ...   thing.a = 33
   484     ...
   486 There is a more aggressive version of both `spec` and `autospec` that *does*
   487 prevent you setting non-existent attributes. This is useful if you want to
   488 ensure your code only *sets* valid attributes too, but obviously it prevents
   489 this particular scenario:
   491 .. doctest::
   493     >>> with patch('__main__.Something', autospec=True, spec_set=True):
   494     ...   thing = Something()
   495     ...   thing.a = 33
   496     ...
   497     Traceback (most recent call last):
   498      ...
   499     AttributeError: Mock object has no attribute 'a'
   501 Probably the best way of solving the problem is to add class attributes as
   502 default values for instance members initialised in `__init__`. Note that if
   503 you are only setting default attributes in `__init__` then providing them via
   504 class attributes (shared between instances of course) is faster too. e.g.
   506 .. code-block:: python
   508     class Something(object):
   509         a = 33
   511 This brings up another issue. It is relatively common to provide a default
   512 value of `None` for members that will later be an object of a different type.
   513 `None` would be useless as a spec because it wouldn't let you access *any*
   514 attributes or methods on it. As `None` is *never* going to be useful as a
   515 spec, and probably indicates a member that will normally of some other type,
   516 `autospec` doesn't use a spec for members that are set to `None`. These will
   517 just be ordinary mocks (well - `MagicMocks`):
   519 .. doctest::
   521     >>> class Something(object):
   522     ...     member = None
   523     ...
   524     >>> mock = create_autospec(Something)
   525     >>> mock.member.foo.bar.baz()
   526     <MagicMock name='mock.member.foo.bar.baz()' id='...'>
   528 If modifying your production classes to add defaults isn't to your liking
   529 then there are more options. One of these is simply to use an instance as the
   530 spec rather than the class. The other is to create a subclass of the
   531 production class and add the defaults to the subclass without affecting the
   532 production class. Both of these require you to use an alternative object as
   533 the spec. Thankfully `patch` supports this - you can simply pass the
   534 alternative object as the `autospec` argument:
   536 .. doctest::
   538     >>> class Something(object):
   539     ...   def __init__(self):
   540     ...     self.a = 33
   541     ...
   542     >>> class SomethingForTest(Something):
   543     ...   a = 33
   544     ...
   545     >>> p = patch('__main__.Something', autospec=SomethingForTest)
   546     >>> mock = p.start()
   547     >>> mock.a
   548     <NonCallableMagicMock name='Something.a' spec='int' id='...'>
   550 .. note::
   552     An additional limitation (currently) with `autospec` is that unbound
   553     methods on mocked classes *don't* take an "explicit self" as the first
   554     argument - so this usage will fail with `autospec`.
   556     .. doctest::
   558         >>> class Foo(object):
   559         ...   def foo(self):
   560         ...     pass
   561         ...
   562         >>> Foo.foo(Foo())
   563         >>> MockFoo = create_autospec(Foo)
   564         >>> MockFoo.foo(MockFoo())
   565         Traceback (most recent call last):
   566           ...
   567         TypeError: <lambda>() takes exactly 1 argument (2 given)
   569     The reason is that its very hard to tell the difference between functions,
   570     unbound methods and staticmethods across Python 2 & 3 and the alternative
   571     implementations. This restriction may be fixed in future versions.
   574 ------
   576 .. [#] This only applies to classes or already instantiated objects. Calling
   577    a mocked class to create a mock instance *does not* create a real instance.
   578    It is only attribute lookups - along with calls to `dir` - that are done. A
   579    way round this problem would have been to use `getattr_static
   580    <http://docs.python.org/dev/library/inspect.html#inspect.getattr_static>`_,
   581    which can fetch attributes without triggering code execution. Descriptors
   582    like `classmethod` and `staticmethod` *need* to be fetched correctly though,
   583    so that their signatures can be mocked correctly.

mercurial