python/mock-1.0.0/docs/mock.txt

Thu, 22 Jan 2015 13:21:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 22 Jan 2015 13:21:57 +0100
branch
TOR_BUG_9701
changeset 15
b8a032363ba2
permissions
-rw-r--r--

Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6

     1 The Mock Class
     2 ==============
     4 .. currentmodule:: mock
     6 .. testsetup::
     8     class SomeClass:
     9         pass
    12 `Mock` is a flexible mock object intended to replace the use of stubs and
    13 test doubles throughout your code. Mocks are callable and create attributes as
    14 new mocks when you access them [#]_. Accessing the same attribute will always
    15 return the same mock. Mocks record how you use them, allowing you to make
    16 assertions about what your code has done to them.
    18 :class:`MagicMock` is a subclass of `Mock` with all the magic methods
    19 pre-created and ready to use. There are also non-callable variants, useful
    20 when you are mocking out objects that aren't callable:
    21 :class:`NonCallableMock` and :class:`NonCallableMagicMock`
    23 The :func:`patch` decorators makes it easy to temporarily replace classes
    24 in a particular module with a `Mock` object. By default `patch` will create
    25 a `MagicMock` for you. You can specify an alternative class of `Mock` using
    26 the `new_callable` argument to `patch`.
    29 .. index:: side_effect
    30 .. index:: return_value
    31 .. index:: wraps
    32 .. index:: name
    33 .. index:: spec
    35 .. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, **kwargs)
    37     Create a new `Mock` object. `Mock` takes several optional arguments
    38     that specify the behaviour of the Mock object:
    40     * `spec`: This can be either a list of strings or an existing object (a
    41       class or instance) that acts as the specification for the mock object. If
    42       you pass in an object then a list of strings is formed by calling dir on
    43       the object (excluding unsupported magic attributes and methods).
    44       Accessing any attribute not in this list will raise an `AttributeError`.
    46       If `spec` is an object (rather than a list of strings) then
    47       :attr:`__class__` returns the class of the spec object. This allows mocks
    48       to pass `isinstance` tests.
    50     * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
    51       or get an attribute on the mock that isn't on the object passed as
    52       `spec_set` will raise an `AttributeError`.
    54     * `side_effect`: A function to be called whenever the Mock is called. See
    55       the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or
    56       dynamically changing return values. The function is called with the same
    57       arguments as the mock, and unless it returns :data:`DEFAULT`, the return
    58       value of this function is used as the return value.
    60       Alternatively `side_effect` can be an exception class or instance. In
    61       this case the exception will be raised when the mock is called.
    63       If `side_effect` is an iterable then each call to the mock will return
    64       the next value from the iterable. If any of the members of the iterable
    65       are exceptions they will be raised instead of returned.
    67       A `side_effect` can be cleared by setting it to `None`.
    69     * `return_value`: The value returned when the mock is called. By default
    70       this is a new Mock (created on first access). See the
    71       :attr:`return_value` attribute.
    73     * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
    74       calling the Mock will pass the call through to the wrapped object
    75       (returning the real result and ignoring `return_value`). Attribute access
    76       on the mock will return a Mock object that wraps the corresponding
    77       attribute of the wrapped object (so attempting to access an attribute
    78       that doesn't exist will raise an `AttributeError`).
    80       If the mock has an explicit `return_value` set then calls are not passed
    81       to the wrapped object and the `return_value` is returned instead.
    83     * `name`: If the mock has a name then it will be used in the repr of the
    84       mock. This can be useful for debugging. The name is propagated to child
    85       mocks.
    87     Mocks can also be called with arbitrary keyword arguments. These will be
    88     used to set attributes on the mock after it is created. See the
    89     :meth:`configure_mock` method for details.
    92     .. method:: assert_called_with(*args, **kwargs)
    94         This method is a convenient way of asserting that calls are made in a
    95         particular way:
    97         .. doctest::
    99             >>> mock = Mock()
   100             >>> mock.method(1, 2, 3, test='wow')
   101             <Mock name='mock.method()' id='...'>
   102             >>> mock.method.assert_called_with(1, 2, 3, test='wow')
   105     .. method:: assert_called_once_with(*args, **kwargs)
   107        Assert that the mock was called exactly once and with the specified
   108        arguments.
   110        .. doctest::
   112             >>> mock = Mock(return_value=None)
   113             >>> mock('foo', bar='baz')
   114             >>> mock.assert_called_once_with('foo', bar='baz')
   115             >>> mock('foo', bar='baz')
   116             >>> mock.assert_called_once_with('foo', bar='baz')
   117             Traceback (most recent call last):
   118               ...
   119             AssertionError: Expected to be called once. Called 2 times.
   122     .. method:: assert_any_call(*args, **kwargs)
   124         assert the mock has been called with the specified arguments.
   126         The assert passes if the mock has *ever* been called, unlike
   127         :meth:`assert_called_with` and :meth:`assert_called_once_with` that
   128         only pass if the call is the most recent one.
   130         .. doctest::
   132             >>> mock = Mock(return_value=None)
   133             >>> mock(1, 2, arg='thing')
   134             >>> mock('some', 'thing', 'else')
   135             >>> mock.assert_any_call(1, 2, arg='thing')
   138     .. method:: assert_has_calls(calls, any_order=False)
   140         assert the mock has been called with the specified calls.
   141         The `mock_calls` list is checked for the calls.
   143         If `any_order` is False (the default) then the calls must be
   144         sequential. There can be extra calls before or after the
   145         specified calls.
   147         If `any_order` is True then the calls can be in any order, but
   148         they must all appear in :attr:`mock_calls`.
   150         .. doctest::
   152             >>> mock = Mock(return_value=None)
   153             >>> mock(1)
   154             >>> mock(2)
   155             >>> mock(3)
   156             >>> mock(4)
   157             >>> calls = [call(2), call(3)]
   158             >>> mock.assert_has_calls(calls)
   159             >>> calls = [call(4), call(2), call(3)]
   160             >>> mock.assert_has_calls(calls, any_order=True)
   163     .. method:: reset_mock()
   165         The reset_mock method resets all the call attributes on a mock object:
   167         .. doctest::
   169             >>> mock = Mock(return_value=None)
   170             >>> mock('hello')
   171             >>> mock.called
   172             True
   173             >>> mock.reset_mock()
   174             >>> mock.called
   175             False
   177         This can be useful where you want to make a series of assertions that
   178         reuse the same object. Note that `reset_mock` *doesn't* clear the
   179         return value, :attr:`side_effect` or any child attributes you have
   180         set using normal assignment. Child mocks and the return value mock
   181         (if any) are reset as well.
   184     .. method:: mock_add_spec(spec, spec_set=False)
   186         Add a spec to a mock. `spec` can either be an object or a
   187         list of strings. Only attributes on the `spec` can be fetched as
   188         attributes from the mock.
   190         If `spec_set` is `True` then only attributes on the spec can be set.
   193     .. method:: attach_mock(mock, attribute)
   195         Attach a mock as an attribute of this one, replacing its name and
   196         parent. Calls to the attached mock will be recorded in the
   197         :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
   200     .. method:: configure_mock(**kwargs)
   202         Set attributes on the mock through keyword arguments.
   204         Attributes plus return values and side effects can be set on child
   205         mocks using standard dot notation and unpacking a dictionary in the
   206         method call:
   208         .. doctest::
   210             >>> mock = Mock()
   211             >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
   212             >>> mock.configure_mock(**attrs)
   213             >>> mock.method()
   214             3
   215             >>> mock.other()
   216             Traceback (most recent call last):
   217               ...
   218             KeyError
   220         The same thing can be achieved in the constructor call to mocks:
   222         .. doctest::
   224             >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
   225             >>> mock = Mock(some_attribute='eggs', **attrs)
   226             >>> mock.some_attribute
   227             'eggs'
   228             >>> mock.method()
   229             3
   230             >>> mock.other()
   231             Traceback (most recent call last):
   232               ...
   233             KeyError
   235         `configure_mock` exists to make it easier to do configuration
   236         after the mock has been created.
   239     .. method:: __dir__()
   241         `Mock` objects limit the results of `dir(some_mock)` to useful results.
   242         For mocks with a `spec` this includes all the permitted attributes
   243         for the mock.
   245         See :data:`FILTER_DIR` for what this filtering does, and how to
   246         switch it off.
   249     .. method:: _get_child_mock(**kw)
   251         Create the child mocks for attributes and return value.
   252         By default child mocks will be the same type as the parent.
   253         Subclasses of Mock may want to override this to customize the way
   254         child mocks are made.
   256         For non-callable mocks the callable variant will be used (rather than
   257         any custom subclass).
   260     .. attribute:: called
   262         A boolean representing whether or not the mock object has been called:
   264         .. doctest::
   266             >>> mock = Mock(return_value=None)
   267             >>> mock.called
   268             False
   269             >>> mock()
   270             >>> mock.called
   271             True
   273     .. attribute:: call_count
   275         An integer telling you how many times the mock object has been called:
   277         .. doctest::
   279             >>> mock = Mock(return_value=None)
   280             >>> mock.call_count
   281             0
   282             >>> mock()
   283             >>> mock()
   284             >>> mock.call_count
   285             2
   288     .. attribute:: return_value
   290         Set this to configure the value returned by calling the mock:
   292         .. doctest::
   294             >>> mock = Mock()
   295             >>> mock.return_value = 'fish'
   296             >>> mock()
   297             'fish'
   299         The default return value is a mock object and you can configure it in
   300         the normal way:
   302         .. doctest::
   304             >>> mock = Mock()
   305             >>> mock.return_value.attribute = sentinel.Attribute
   306             >>> mock.return_value()
   307             <Mock name='mock()()' id='...'>
   308             >>> mock.return_value.assert_called_with()
   310         `return_value` can also be set in the constructor:
   312         .. doctest::
   314             >>> mock = Mock(return_value=3)
   315             >>> mock.return_value
   316             3
   317             >>> mock()
   318             3
   321     .. attribute:: side_effect
   323         This can either be a function to be called when the mock is called,
   324         or an exception (class or instance) to be raised.
   326         If you pass in a function it will be called with same arguments as the
   327         mock and unless the function returns the :data:`DEFAULT` singleton the
   328         call to the mock will then return whatever the function returns. If the
   329         function returns :data:`DEFAULT` then the mock will return its normal
   330         value (from the :attr:`return_value`.
   332         An example of a mock that raises an exception (to test exception
   333         handling of an API):
   335         .. doctest::
   337             >>> mock = Mock()
   338             >>> mock.side_effect = Exception('Boom!')
   339             >>> mock()
   340             Traceback (most recent call last):
   341               ...
   342             Exception: Boom!
   344         Using `side_effect` to return a sequence of values:
   346         .. doctest::
   348             >>> mock = Mock()
   349             >>> mock.side_effect = [3, 2, 1]
   350             >>> mock(), mock(), mock()
   351             (3, 2, 1)
   353         The `side_effect` function is called with the same arguments as the
   354         mock (so it is wise for it to take arbitrary args and keyword
   355         arguments) and whatever it returns is used as the return value for
   356         the call. The exception is if `side_effect` returns :data:`DEFAULT`,
   357         in which case the normal :attr:`return_value` is used.
   359         .. doctest::
   361             >>> mock = Mock(return_value=3)
   362             >>> def side_effect(*args, **kwargs):
   363             ...     return DEFAULT
   364             ...
   365             >>> mock.side_effect = side_effect
   366             >>> mock()
   367             3
   369         `side_effect` can be set in the constructor. Here's an example that
   370         adds one to the value the mock is called with and returns it:
   372         .. doctest::
   374             >>> side_effect = lambda value: value + 1
   375             >>> mock = Mock(side_effect=side_effect)
   376             >>> mock(3)
   377             4
   378             >>> mock(-8)
   379             -7
   381         Setting `side_effect` to `None` clears it:
   383         .. doctest::
   385             >>> from mock import Mock
   386             >>> m = Mock(side_effect=KeyError, return_value=3)
   387             >>> m()
   388             Traceback (most recent call last):
   389              ...
   390             KeyError
   391             >>> m.side_effect = None
   392             >>> m()
   393             3
   396     .. attribute:: call_args
   398         This is either `None` (if the mock hasn't been called), or the
   399         arguments that the mock was last called with. This will be in the
   400         form of a tuple: the first member is any ordered arguments the mock
   401         was called with (or an empty tuple) and the second member is any
   402         keyword arguments (or an empty dictionary).
   404         .. doctest::
   406             >>> mock = Mock(return_value=None)
   407             >>> print mock.call_args
   408             None
   409             >>> mock()
   410             >>> mock.call_args
   411             call()
   412             >>> mock.call_args == ()
   413             True
   414             >>> mock(3, 4)
   415             >>> mock.call_args
   416             call(3, 4)
   417             >>> mock.call_args == ((3, 4),)
   418             True
   419             >>> mock(3, 4, 5, key='fish', next='w00t!')
   420             >>> mock.call_args
   421             call(3, 4, 5, key='fish', next='w00t!')
   423         `call_args`, along with members of the lists :attr:`call_args_list`,
   424         :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
   425         These are tuples, so they can be unpacked to get at the individual
   426         arguments and make more complex assertions. See
   427         :ref:`calls as tuples <calls-as-tuples>`.
   430     .. attribute:: call_args_list
   432         This is a list of all the calls made to the mock object in sequence
   433         (so the length of the list is the number of times it has been
   434         called). Before any calls have been made it is an empty list. The
   435         :data:`call` object can be used for conveniently constructing lists of
   436         calls to compare with `call_args_list`.
   438         .. doctest::
   440             >>> mock = Mock(return_value=None)
   441             >>> mock()
   442             >>> mock(3, 4)
   443             >>> mock(key='fish', next='w00t!')
   444             >>> mock.call_args_list
   445             [call(), call(3, 4), call(key='fish', next='w00t!')]
   446             >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
   447             >>> mock.call_args_list == expected
   448             True
   450         Members of `call_args_list` are :data:`call` objects. These can be
   451         unpacked as tuples to get at the individual arguments. See
   452         :ref:`calls as tuples <calls-as-tuples>`.
   455     .. attribute:: method_calls
   457         As well as tracking calls to themselves, mocks also track calls to
   458         methods and attributes, and *their* methods and attributes:
   460         .. doctest::
   462             >>> mock = Mock()
   463             >>> mock.method()
   464             <Mock name='mock.method()' id='...'>
   465             >>> mock.property.method.attribute()
   466             <Mock name='mock.property.method.attribute()' id='...'>
   467             >>> mock.method_calls
   468             [call.method(), call.property.method.attribute()]
   470         Members of `method_calls` are :data:`call` objects. These can be
   471         unpacked as tuples to get at the individual arguments. See
   472         :ref:`calls as tuples <calls-as-tuples>`.
   475     .. attribute:: mock_calls
   477         `mock_calls` records *all* calls to the mock object, its methods, magic
   478         methods *and* return value mocks.
   480         .. doctest::
   482             >>> mock = MagicMock()
   483             >>> result = mock(1, 2, 3)
   484             >>> mock.first(a=3)
   485             <MagicMock name='mock.first()' id='...'>
   486             >>> mock.second()
   487             <MagicMock name='mock.second()' id='...'>
   488             >>> int(mock)
   489             1
   490             >>> result(1)
   491             <MagicMock name='mock()()' id='...'>
   492             >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
   493             ... call.__int__(), call()(1)]
   494             >>> mock.mock_calls == expected
   495             True
   497         Members of `mock_calls` are :data:`call` objects. These can be
   498         unpacked as tuples to get at the individual arguments. See
   499         :ref:`calls as tuples <calls-as-tuples>`.
   502     .. attribute:: __class__
   504         Normally the `__class__` attribute of an object will return its type.
   505         For a mock object with a `spec` `__class__` returns the spec class
   506         instead. This allows mock objects to pass `isinstance` tests for the
   507         object they are replacing / masquerading as:
   509         .. doctest::
   511             >>> mock = Mock(spec=3)
   512             >>> isinstance(mock, int)
   513             True
   515         `__class__` is assignable to, this allows a mock to pass an
   516         `isinstance` check without forcing you to use a spec:
   518         .. doctest::
   520             >>> mock = Mock()
   521             >>> mock.__class__ = dict
   522             >>> isinstance(mock, dict)
   523             True
   525 .. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
   527     A non-callable version of `Mock`. The constructor parameters have the same
   528     meaning of `Mock`, with the exception of `return_value` and `side_effect`
   529     which have no meaning on a non-callable mock.
   531 Mock objects that use a class or an instance as a `spec` or `spec_set` are able
   532 to pass `isintance` tests:
   534 .. doctest::
   536     >>> mock = Mock(spec=SomeClass)
   537     >>> isinstance(mock, SomeClass)
   538     True
   539     >>> mock = Mock(spec_set=SomeClass())
   540     >>> isinstance(mock, SomeClass)
   541     True
   543 The `Mock` classes have support for mocking magic methods. See :ref:`magic
   544 methods <magic-methods>` for the full details.
   546 The mock classes and the :func:`patch` decorators all take arbitrary keyword
   547 arguments for configuration. For the `patch` decorators the keywords are
   548 passed to the constructor of the mock being created. The keyword arguments
   549 are for configuring attributes of the mock:
   551 .. doctest::
   553         >>> m = MagicMock(attribute=3, other='fish')
   554         >>> m.attribute
   555         3
   556         >>> m.other
   557         'fish'
   559 The return value and side effect of child mocks can be set in the same way,
   560 using dotted notation. As you can't use dotted names directly in a call you
   561 have to create a dictionary and unpack it using `**`:
   563 .. doctest::
   565     >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
   566     >>> mock = Mock(some_attribute='eggs', **attrs)
   567     >>> mock.some_attribute
   568     'eggs'
   569     >>> mock.method()
   570     3
   571     >>> mock.other()
   572     Traceback (most recent call last):
   573       ...
   574     KeyError
   577 .. class:: PropertyMock(*args, **kwargs)
   579    A mock intended to be used as a property, or other descriptor, on a class.
   580    `PropertyMock` provides `__get__` and `__set__` methods so you can specify
   581    a return value when it is fetched.
   583    Fetching a `PropertyMock` instance from an object calls the mock, with
   584    no args. Setting it calls the mock with the value being set.
   586    .. doctest::
   588         >>> class Foo(object):
   589         ...     @property
   590         ...     def foo(self):
   591         ...         return 'something'
   592         ...     @foo.setter
   593         ...     def foo(self, value):
   594         ...         pass
   595         ...
   596         >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
   597         ...     mock_foo.return_value = 'mockity-mock'
   598         ...     this_foo = Foo()
   599         ...     print this_foo.foo
   600         ...     this_foo.foo = 6
   601         ...
   602         mockity-mock
   603         >>> mock_foo.mock_calls
   604         [call(), call(6)]
   606 Because of the way mock attributes are stored you can't directly attach a
   607 `PropertyMock` to a mock object. Instead you can attach it to the mock type
   608 object:
   610 .. doctest::
   612     >>> m = MagicMock()
   613     >>> p = PropertyMock(return_value=3)
   614     >>> type(m).foo = p
   615     >>> m.foo
   616     3
   617     >>> p.assert_called_once_with()
   620 .. index:: __call__
   621 .. index:: calling
   623 Calling
   624 =======
   626 Mock objects are callable. The call will return the value set as the
   627 :attr:`~Mock.return_value` attribute. The default return value is a new Mock
   628 object; it is created the first time the return value is accessed (either
   629 explicitly or by calling the Mock) - but it is stored and the same one
   630 returned each time.
   632 Calls made to the object will be recorded in the attributes
   633 like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
   635 If :attr:`~Mock.side_effect` is set then it will be called after the call has
   636 been recorded, so if `side_effect` raises an exception the call is still
   637 recorded.
   639 The simplest way to make a mock raise an exception when called is to make
   640 :attr:`~Mock.side_effect` an exception class or instance:
   642 .. doctest::
   644         >>> m = MagicMock(side_effect=IndexError)
   645         >>> m(1, 2, 3)
   646         Traceback (most recent call last):
   647           ...
   648         IndexError
   649         >>> m.mock_calls
   650         [call(1, 2, 3)]
   651         >>> m.side_effect = KeyError('Bang!')
   652         >>> m('two', 'three', 'four')
   653         Traceback (most recent call last):
   654           ...
   655         KeyError: 'Bang!'
   656         >>> m.mock_calls
   657         [call(1, 2, 3), call('two', 'three', 'four')]
   659 If `side_effect` is a function then whatever that function returns is what
   660 calls to the mock return. The `side_effect` function is called with the
   661 same arguments as the mock. This allows you to vary the return value of the
   662 call dynamically, based on the input:
   664 .. doctest::
   666         >>> def side_effect(value):
   667         ...     return value + 1
   668         ...
   669         >>> m = MagicMock(side_effect=side_effect)
   670         >>> m(1)
   671         2
   672         >>> m(2)
   673         3
   674         >>> m.mock_calls
   675         [call(1), call(2)]
   677 If you want the mock to still return the default return value (a new mock), or
   678 any set return value, then there are two ways of doing this. Either return
   679 `mock.return_value` from inside `side_effect`, or return :data:`DEFAULT`:
   681 .. doctest::
   683         >>> m = MagicMock()
   684         >>> def side_effect(*args, **kwargs):
   685         ...     return m.return_value
   686         ...
   687         >>> m.side_effect = side_effect
   688         >>> m.return_value = 3
   689         >>> m()
   690         3
   691         >>> def side_effect(*args, **kwargs):
   692         ...     return DEFAULT
   693         ...
   694         >>> m.side_effect = side_effect
   695         >>> m()
   696         3
   698 To remove a `side_effect`, and return to the default behaviour, set the
   699 `side_effect` to `None`:
   701 .. doctest::
   703         >>> m = MagicMock(return_value=6)
   704         >>> def side_effect(*args, **kwargs):
   705         ...     return 3
   706         ...
   707         >>> m.side_effect = side_effect
   708         >>> m()
   709         3
   710         >>> m.side_effect = None
   711         >>> m()
   712         6
   714 The `side_effect` can also be any iterable object. Repeated calls to the mock
   715 will return values from the iterable (until the iterable is exhausted and
   716 a `StopIteration` is raised):
   718 .. doctest::
   720         >>> m = MagicMock(side_effect=[1, 2, 3])
   721         >>> m()
   722         1
   723         >>> m()
   724         2
   725         >>> m()
   726         3
   727         >>> m()
   728         Traceback (most recent call last):
   729           ...
   730         StopIteration
   732 If any members of the iterable are exceptions they will be raised instead of
   733 returned:
   735 .. doctest::
   737         >>> iterable = (33, ValueError, 66)
   738         >>> m = MagicMock(side_effect=iterable)
   739         >>> m()
   740         33
   741         >>> m()
   742         Traceback (most recent call last):
   743          ...
   744         ValueError
   745         >>> m()
   746         66
   749 .. _deleting-attributes:
   751 Deleting Attributes
   752 ===================
   754 Mock objects create attributes on demand. This allows them to pretend to be
   755 objects of any type.
   757 You may want a mock object to return `False` to a `hasattr` call, or raise an
   758 `AttributeError` when an attribute is fetched. You can do this by providing
   759 an object as a `spec` for a mock, but that isn't always convenient.
   761 You "block" attributes by deleting them. Once deleted, accessing an attribute
   762 will raise an `AttributeError`.
   764 .. doctest::
   766     >>> mock = MagicMock()
   767     >>> hasattr(mock, 'm')
   768     True
   769     >>> del mock.m
   770     >>> hasattr(mock, 'm')
   771     False
   772     >>> del mock.f
   773     >>> mock.f
   774     Traceback (most recent call last):
   775         ...
   776     AttributeError: f
   779 Attaching Mocks as Attributes
   780 =============================
   782 When you attach a mock as an attribute of another mock (or as the return
   783 value) it becomes a "child" of that mock. Calls to the child are recorded in
   784 the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
   785 parent. This is useful for configuring child mocks and then attaching them to
   786 the parent, or for attaching mocks to a parent that records all calls to the
   787 children and allows you to make assertions about the order of calls between
   788 mocks:
   790 .. doctest::
   792     >>> parent = MagicMock()
   793     >>> child1 = MagicMock(return_value=None)
   794     >>> child2 = MagicMock(return_value=None)
   795     >>> parent.child1 = child1
   796     >>> parent.child2 = child2
   797     >>> child1(1)
   798     >>> child2(2)
   799     >>> parent.mock_calls
   800     [call.child1(1), call.child2(2)]
   802 The exception to this is if the mock has a name. This allows you to prevent
   803 the "parenting" if for some reason you don't want it to happen.
   805 .. doctest::
   807     >>> mock = MagicMock()
   808     >>> not_a_child = MagicMock(name='not-a-child')
   809     >>> mock.attribute = not_a_child
   810     >>> mock.attribute()
   811     <MagicMock name='not-a-child()' id='...'>
   812     >>> mock.mock_calls
   813     []
   815 Mocks created for you by :func:`patch` are automatically given names. To
   816 attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
   817 method:
   819 .. doctest::
   821     >>> thing1 = object()
   822     >>> thing2 = object()
   823     >>> parent = MagicMock()
   824     >>> with patch('__main__.thing1', return_value=None) as child1:
   825     ...     with patch('__main__.thing2', return_value=None) as child2:
   826     ...         parent.attach_mock(child1, 'child1')
   827     ...         parent.attach_mock(child2, 'child2')
   828     ...         child1('one')
   829     ...         child2('two')
   830     ...
   831     >>> parent.mock_calls
   832     [call.child1('one'), call.child2('two')]
   835 -----
   837 .. [#] The only exceptions are magic methods and attributes (those that have
   838        leading and trailing double underscores). Mock doesn't create these but
   839        instead of raises an ``AttributeError``. This is because the interpreter
   840        will often implicitly request these methods, and gets *very* confused to
   841        get a new Mock object when it expects a magic method. If you need magic
   842        method support see :ref:`magic methods <magic-methods>`.

mercurial