michael@0: The Mock Class michael@0: ============== michael@0: michael@0: .. currentmodule:: mock michael@0: michael@0: .. testsetup:: michael@0: michael@0: class SomeClass: michael@0: pass michael@0: michael@0: michael@0: `Mock` is a flexible mock object intended to replace the use of stubs and michael@0: test doubles throughout your code. Mocks are callable and create attributes as michael@0: new mocks when you access them [#]_. Accessing the same attribute will always michael@0: return the same mock. Mocks record how you use them, allowing you to make michael@0: assertions about what your code has done to them. michael@0: michael@0: :class:`MagicMock` is a subclass of `Mock` with all the magic methods michael@0: pre-created and ready to use. There are also non-callable variants, useful michael@0: when you are mocking out objects that aren't callable: michael@0: :class:`NonCallableMock` and :class:`NonCallableMagicMock` michael@0: michael@0: The :func:`patch` decorators makes it easy to temporarily replace classes michael@0: in a particular module with a `Mock` object. By default `patch` will create michael@0: a `MagicMock` for you. You can specify an alternative class of `Mock` using michael@0: the `new_callable` argument to `patch`. michael@0: michael@0: michael@0: .. index:: side_effect michael@0: .. index:: return_value michael@0: .. index:: wraps michael@0: .. index:: name michael@0: .. index:: spec michael@0: michael@0: .. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, **kwargs) michael@0: michael@0: Create a new `Mock` object. `Mock` takes several optional arguments michael@0: that specify the behaviour of the Mock object: michael@0: michael@0: * `spec`: This can be either a list of strings or an existing object (a michael@0: class or instance) that acts as the specification for the mock object. If michael@0: you pass in an object then a list of strings is formed by calling dir on michael@0: the object (excluding unsupported magic attributes and methods). michael@0: Accessing any attribute not in this list will raise an `AttributeError`. michael@0: michael@0: If `spec` is an object (rather than a list of strings) then michael@0: :attr:`__class__` returns the class of the spec object. This allows mocks michael@0: to pass `isinstance` tests. michael@0: michael@0: * `spec_set`: A stricter variant of `spec`. If used, attempting to *set* michael@0: or get an attribute on the mock that isn't on the object passed as michael@0: `spec_set` will raise an `AttributeError`. michael@0: michael@0: * `side_effect`: A function to be called whenever the Mock is called. See michael@0: the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or michael@0: dynamically changing return values. The function is called with the same michael@0: arguments as the mock, and unless it returns :data:`DEFAULT`, the return michael@0: value of this function is used as the return value. michael@0: michael@0: Alternatively `side_effect` can be an exception class or instance. In michael@0: this case the exception will be raised when the mock is called. michael@0: michael@0: If `side_effect` is an iterable then each call to the mock will return michael@0: the next value from the iterable. If any of the members of the iterable michael@0: are exceptions they will be raised instead of returned. michael@0: michael@0: A `side_effect` can be cleared by setting it to `None`. michael@0: michael@0: * `return_value`: The value returned when the mock is called. By default michael@0: this is a new Mock (created on first access). See the michael@0: :attr:`return_value` attribute. michael@0: michael@0: * `wraps`: Item for the mock object to wrap. If `wraps` is not None then michael@0: calling the Mock will pass the call through to the wrapped object michael@0: (returning the real result and ignoring `return_value`). Attribute access michael@0: on the mock will return a Mock object that wraps the corresponding michael@0: attribute of the wrapped object (so attempting to access an attribute michael@0: that doesn't exist will raise an `AttributeError`). michael@0: michael@0: If the mock has an explicit `return_value` set then calls are not passed michael@0: to the wrapped object and the `return_value` is returned instead. michael@0: michael@0: * `name`: If the mock has a name then it will be used in the repr of the michael@0: mock. This can be useful for debugging. The name is propagated to child michael@0: mocks. michael@0: michael@0: Mocks can also be called with arbitrary keyword arguments. These will be michael@0: used to set attributes on the mock after it is created. See the michael@0: :meth:`configure_mock` method for details. michael@0: michael@0: michael@0: .. method:: assert_called_with(*args, **kwargs) michael@0: michael@0: This method is a convenient way of asserting that calls are made in a michael@0: particular way: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock() michael@0: >>> mock.method(1, 2, 3, test='wow') michael@0: michael@0: >>> mock.method.assert_called_with(1, 2, 3, test='wow') michael@0: michael@0: michael@0: .. method:: assert_called_once_with(*args, **kwargs) michael@0: michael@0: Assert that the mock was called exactly once and with the specified michael@0: arguments. michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock(return_value=None) michael@0: >>> mock('foo', bar='baz') michael@0: >>> mock.assert_called_once_with('foo', bar='baz') michael@0: >>> mock('foo', bar='baz') michael@0: >>> mock.assert_called_once_with('foo', bar='baz') michael@0: Traceback (most recent call last): michael@0: ... michael@0: AssertionError: Expected to be called once. Called 2 times. michael@0: michael@0: michael@0: .. method:: assert_any_call(*args, **kwargs) michael@0: michael@0: assert the mock has been called with the specified arguments. michael@0: michael@0: The assert passes if the mock has *ever* been called, unlike michael@0: :meth:`assert_called_with` and :meth:`assert_called_once_with` that michael@0: only pass if the call is the most recent one. michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock(return_value=None) michael@0: >>> mock(1, 2, arg='thing') michael@0: >>> mock('some', 'thing', 'else') michael@0: >>> mock.assert_any_call(1, 2, arg='thing') michael@0: michael@0: michael@0: .. method:: assert_has_calls(calls, any_order=False) michael@0: michael@0: assert the mock has been called with the specified calls. michael@0: The `mock_calls` list is checked for the calls. michael@0: michael@0: If `any_order` is False (the default) then the calls must be michael@0: sequential. There can be extra calls before or after the michael@0: specified calls. michael@0: michael@0: If `any_order` is True then the calls can be in any order, but michael@0: they must all appear in :attr:`mock_calls`. michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock(return_value=None) michael@0: >>> mock(1) michael@0: >>> mock(2) michael@0: >>> mock(3) michael@0: >>> mock(4) michael@0: >>> calls = [call(2), call(3)] michael@0: >>> mock.assert_has_calls(calls) michael@0: >>> calls = [call(4), call(2), call(3)] michael@0: >>> mock.assert_has_calls(calls, any_order=True) michael@0: michael@0: michael@0: .. method:: reset_mock() michael@0: michael@0: The reset_mock method resets all the call attributes on a mock object: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock(return_value=None) michael@0: >>> mock('hello') michael@0: >>> mock.called michael@0: True michael@0: >>> mock.reset_mock() michael@0: >>> mock.called michael@0: False michael@0: michael@0: This can be useful where you want to make a series of assertions that michael@0: reuse the same object. Note that `reset_mock` *doesn't* clear the michael@0: return value, :attr:`side_effect` or any child attributes you have michael@0: set using normal assignment. Child mocks and the return value mock michael@0: (if any) are reset as well. michael@0: michael@0: michael@0: .. method:: mock_add_spec(spec, spec_set=False) michael@0: michael@0: Add a spec to a mock. `spec` can either be an object or a michael@0: list of strings. Only attributes on the `spec` can be fetched as michael@0: attributes from the mock. michael@0: michael@0: If `spec_set` is `True` then only attributes on the spec can be set. michael@0: michael@0: michael@0: .. method:: attach_mock(mock, attribute) michael@0: michael@0: Attach a mock as an attribute of this one, replacing its name and michael@0: parent. Calls to the attached mock will be recorded in the michael@0: :attr:`method_calls` and :attr:`mock_calls` attributes of this one. michael@0: michael@0: michael@0: .. method:: configure_mock(**kwargs) michael@0: michael@0: Set attributes on the mock through keyword arguments. michael@0: michael@0: Attributes plus return values and side effects can be set on child michael@0: mocks using standard dot notation and unpacking a dictionary in the michael@0: method call: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock() michael@0: >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} michael@0: >>> mock.configure_mock(**attrs) michael@0: >>> mock.method() michael@0: 3 michael@0: >>> mock.other() michael@0: Traceback (most recent call last): michael@0: ... michael@0: KeyError michael@0: michael@0: The same thing can be achieved in the constructor call to mocks: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} michael@0: >>> mock = Mock(some_attribute='eggs', **attrs) michael@0: >>> mock.some_attribute michael@0: 'eggs' michael@0: >>> mock.method() michael@0: 3 michael@0: >>> mock.other() michael@0: Traceback (most recent call last): michael@0: ... michael@0: KeyError michael@0: michael@0: `configure_mock` exists to make it easier to do configuration michael@0: after the mock has been created. michael@0: michael@0: michael@0: .. method:: __dir__() michael@0: michael@0: `Mock` objects limit the results of `dir(some_mock)` to useful results. michael@0: For mocks with a `spec` this includes all the permitted attributes michael@0: for the mock. michael@0: michael@0: See :data:`FILTER_DIR` for what this filtering does, and how to michael@0: switch it off. michael@0: michael@0: michael@0: .. method:: _get_child_mock(**kw) michael@0: michael@0: Create the child mocks for attributes and return value. michael@0: By default child mocks will be the same type as the parent. michael@0: Subclasses of Mock may want to override this to customize the way michael@0: child mocks are made. michael@0: michael@0: For non-callable mocks the callable variant will be used (rather than michael@0: any custom subclass). michael@0: michael@0: michael@0: .. attribute:: called michael@0: michael@0: A boolean representing whether or not the mock object has been called: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock(return_value=None) michael@0: >>> mock.called michael@0: False michael@0: >>> mock() michael@0: >>> mock.called michael@0: True michael@0: michael@0: .. attribute:: call_count michael@0: michael@0: An integer telling you how many times the mock object has been called: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock(return_value=None) michael@0: >>> mock.call_count michael@0: 0 michael@0: >>> mock() michael@0: >>> mock() michael@0: >>> mock.call_count michael@0: 2 michael@0: michael@0: michael@0: .. attribute:: return_value michael@0: michael@0: Set this to configure the value returned by calling the mock: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock() michael@0: >>> mock.return_value = 'fish' michael@0: >>> mock() michael@0: 'fish' michael@0: michael@0: The default return value is a mock object and you can configure it in michael@0: the normal way: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock() michael@0: >>> mock.return_value.attribute = sentinel.Attribute michael@0: >>> mock.return_value() michael@0: michael@0: >>> mock.return_value.assert_called_with() michael@0: michael@0: `return_value` can also be set in the constructor: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock(return_value=3) michael@0: >>> mock.return_value michael@0: 3 michael@0: >>> mock() michael@0: 3 michael@0: michael@0: michael@0: .. attribute:: side_effect michael@0: michael@0: This can either be a function to be called when the mock is called, michael@0: or an exception (class or instance) to be raised. michael@0: michael@0: If you pass in a function it will be called with same arguments as the michael@0: mock and unless the function returns the :data:`DEFAULT` singleton the michael@0: call to the mock will then return whatever the function returns. If the michael@0: function returns :data:`DEFAULT` then the mock will return its normal michael@0: value (from the :attr:`return_value`. michael@0: michael@0: An example of a mock that raises an exception (to test exception michael@0: handling of an API): michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock() michael@0: >>> mock.side_effect = Exception('Boom!') michael@0: >>> mock() michael@0: Traceback (most recent call last): michael@0: ... michael@0: Exception: Boom! michael@0: michael@0: Using `side_effect` to return a sequence of values: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock() michael@0: >>> mock.side_effect = [3, 2, 1] michael@0: >>> mock(), mock(), mock() michael@0: (3, 2, 1) michael@0: michael@0: The `side_effect` function is called with the same arguments as the michael@0: mock (so it is wise for it to take arbitrary args and keyword michael@0: arguments) and whatever it returns is used as the return value for michael@0: the call. The exception is if `side_effect` returns :data:`DEFAULT`, michael@0: in which case the normal :attr:`return_value` is used. michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock(return_value=3) michael@0: >>> def side_effect(*args, **kwargs): michael@0: ... return DEFAULT michael@0: ... michael@0: >>> mock.side_effect = side_effect michael@0: >>> mock() michael@0: 3 michael@0: michael@0: `side_effect` can be set in the constructor. Here's an example that michael@0: adds one to the value the mock is called with and returns it: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> side_effect = lambda value: value + 1 michael@0: >>> mock = Mock(side_effect=side_effect) michael@0: >>> mock(3) michael@0: 4 michael@0: >>> mock(-8) michael@0: -7 michael@0: michael@0: Setting `side_effect` to `None` clears it: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> from mock import Mock michael@0: >>> m = Mock(side_effect=KeyError, return_value=3) michael@0: >>> m() michael@0: Traceback (most recent call last): michael@0: ... michael@0: KeyError michael@0: >>> m.side_effect = None michael@0: >>> m() michael@0: 3 michael@0: michael@0: michael@0: .. attribute:: call_args michael@0: michael@0: This is either `None` (if the mock hasn't been called), or the michael@0: arguments that the mock was last called with. This will be in the michael@0: form of a tuple: the first member is any ordered arguments the mock michael@0: was called with (or an empty tuple) and the second member is any michael@0: keyword arguments (or an empty dictionary). michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock(return_value=None) michael@0: >>> print mock.call_args michael@0: None michael@0: >>> mock() michael@0: >>> mock.call_args michael@0: call() michael@0: >>> mock.call_args == () michael@0: True michael@0: >>> mock(3, 4) michael@0: >>> mock.call_args michael@0: call(3, 4) michael@0: >>> mock.call_args == ((3, 4),) michael@0: True michael@0: >>> mock(3, 4, 5, key='fish', next='w00t!') michael@0: >>> mock.call_args michael@0: call(3, 4, 5, key='fish', next='w00t!') michael@0: michael@0: `call_args`, along with members of the lists :attr:`call_args_list`, michael@0: :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects. michael@0: These are tuples, so they can be unpacked to get at the individual michael@0: arguments and make more complex assertions. See michael@0: :ref:`calls as tuples `. michael@0: michael@0: michael@0: .. attribute:: call_args_list michael@0: michael@0: This is a list of all the calls made to the mock object in sequence michael@0: (so the length of the list is the number of times it has been michael@0: called). Before any calls have been made it is an empty list. The michael@0: :data:`call` object can be used for conveniently constructing lists of michael@0: calls to compare with `call_args_list`. michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock(return_value=None) michael@0: >>> mock() michael@0: >>> mock(3, 4) michael@0: >>> mock(key='fish', next='w00t!') michael@0: >>> mock.call_args_list michael@0: [call(), call(3, 4), call(key='fish', next='w00t!')] michael@0: >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)] michael@0: >>> mock.call_args_list == expected michael@0: True michael@0: michael@0: Members of `call_args_list` are :data:`call` objects. These can be michael@0: unpacked as tuples to get at the individual arguments. See michael@0: :ref:`calls as tuples `. michael@0: michael@0: michael@0: .. attribute:: method_calls michael@0: michael@0: As well as tracking calls to themselves, mocks also track calls to michael@0: methods and attributes, and *their* methods and attributes: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock() michael@0: >>> mock.method() michael@0: michael@0: >>> mock.property.method.attribute() michael@0: michael@0: >>> mock.method_calls michael@0: [call.method(), call.property.method.attribute()] michael@0: michael@0: Members of `method_calls` are :data:`call` objects. These can be michael@0: unpacked as tuples to get at the individual arguments. See michael@0: :ref:`calls as tuples `. michael@0: michael@0: michael@0: .. attribute:: mock_calls michael@0: michael@0: `mock_calls` records *all* calls to the mock object, its methods, magic michael@0: methods *and* return value mocks. michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = MagicMock() michael@0: >>> result = mock(1, 2, 3) michael@0: >>> mock.first(a=3) michael@0: michael@0: >>> mock.second() michael@0: michael@0: >>> int(mock) michael@0: 1 michael@0: >>> result(1) michael@0: michael@0: >>> expected = [call(1, 2, 3), call.first(a=3), call.second(), michael@0: ... call.__int__(), call()(1)] michael@0: >>> mock.mock_calls == expected michael@0: True michael@0: michael@0: Members of `mock_calls` are :data:`call` objects. These can be michael@0: unpacked as tuples to get at the individual arguments. See michael@0: :ref:`calls as tuples `. michael@0: michael@0: michael@0: .. attribute:: __class__ michael@0: michael@0: Normally the `__class__` attribute of an object will return its type. michael@0: For a mock object with a `spec` `__class__` returns the spec class michael@0: instead. This allows mock objects to pass `isinstance` tests for the michael@0: object they are replacing / masquerading as: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock(spec=3) michael@0: >>> isinstance(mock, int) michael@0: True michael@0: michael@0: `__class__` is assignable to, this allows a mock to pass an michael@0: `isinstance` check without forcing you to use a spec: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock() michael@0: >>> mock.__class__ = dict michael@0: >>> isinstance(mock, dict) michael@0: True michael@0: michael@0: .. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs) michael@0: michael@0: A non-callable version of `Mock`. The constructor parameters have the same michael@0: meaning of `Mock`, with the exception of `return_value` and `side_effect` michael@0: which have no meaning on a non-callable mock. michael@0: michael@0: Mock objects that use a class or an instance as a `spec` or `spec_set` are able michael@0: to pass `isintance` tests: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = Mock(spec=SomeClass) michael@0: >>> isinstance(mock, SomeClass) michael@0: True michael@0: >>> mock = Mock(spec_set=SomeClass()) michael@0: >>> isinstance(mock, SomeClass) michael@0: True michael@0: michael@0: The `Mock` classes have support for mocking magic methods. See :ref:`magic michael@0: methods ` for the full details. michael@0: michael@0: The mock classes and the :func:`patch` decorators all take arbitrary keyword michael@0: arguments for configuration. For the `patch` decorators the keywords are michael@0: passed to the constructor of the mock being created. The keyword arguments michael@0: are for configuring attributes of the mock: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> m = MagicMock(attribute=3, other='fish') michael@0: >>> m.attribute michael@0: 3 michael@0: >>> m.other michael@0: 'fish' michael@0: michael@0: The return value and side effect of child mocks can be set in the same way, michael@0: using dotted notation. As you can't use dotted names directly in a call you michael@0: have to create a dictionary and unpack it using `**`: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} michael@0: >>> mock = Mock(some_attribute='eggs', **attrs) michael@0: >>> mock.some_attribute michael@0: 'eggs' michael@0: >>> mock.method() michael@0: 3 michael@0: >>> mock.other() michael@0: Traceback (most recent call last): michael@0: ... michael@0: KeyError michael@0: michael@0: michael@0: .. class:: PropertyMock(*args, **kwargs) michael@0: michael@0: A mock intended to be used as a property, or other descriptor, on a class. michael@0: `PropertyMock` provides `__get__` and `__set__` methods so you can specify michael@0: a return value when it is fetched. michael@0: michael@0: Fetching a `PropertyMock` instance from an object calls the mock, with michael@0: no args. Setting it calls the mock with the value being set. michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> class Foo(object): michael@0: ... @property michael@0: ... def foo(self): michael@0: ... return 'something' michael@0: ... @foo.setter michael@0: ... def foo(self, value): michael@0: ... pass michael@0: ... michael@0: >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo: michael@0: ... mock_foo.return_value = 'mockity-mock' michael@0: ... this_foo = Foo() michael@0: ... print this_foo.foo michael@0: ... this_foo.foo = 6 michael@0: ... michael@0: mockity-mock michael@0: >>> mock_foo.mock_calls michael@0: [call(), call(6)] michael@0: michael@0: Because of the way mock attributes are stored you can't directly attach a michael@0: `PropertyMock` to a mock object. Instead you can attach it to the mock type michael@0: object: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> m = MagicMock() michael@0: >>> p = PropertyMock(return_value=3) michael@0: >>> type(m).foo = p michael@0: >>> m.foo michael@0: 3 michael@0: >>> p.assert_called_once_with() michael@0: michael@0: michael@0: .. index:: __call__ michael@0: .. index:: calling michael@0: michael@0: Calling michael@0: ======= michael@0: michael@0: Mock objects are callable. The call will return the value set as the michael@0: :attr:`~Mock.return_value` attribute. The default return value is a new Mock michael@0: object; it is created the first time the return value is accessed (either michael@0: explicitly or by calling the Mock) - but it is stored and the same one michael@0: returned each time. michael@0: michael@0: Calls made to the object will be recorded in the attributes michael@0: like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`. michael@0: michael@0: If :attr:`~Mock.side_effect` is set then it will be called after the call has michael@0: been recorded, so if `side_effect` raises an exception the call is still michael@0: recorded. michael@0: michael@0: The simplest way to make a mock raise an exception when called is to make michael@0: :attr:`~Mock.side_effect` an exception class or instance: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> m = MagicMock(side_effect=IndexError) michael@0: >>> m(1, 2, 3) michael@0: Traceback (most recent call last): michael@0: ... michael@0: IndexError michael@0: >>> m.mock_calls michael@0: [call(1, 2, 3)] michael@0: >>> m.side_effect = KeyError('Bang!') michael@0: >>> m('two', 'three', 'four') michael@0: Traceback (most recent call last): michael@0: ... michael@0: KeyError: 'Bang!' michael@0: >>> m.mock_calls michael@0: [call(1, 2, 3), call('two', 'three', 'four')] michael@0: michael@0: If `side_effect` is a function then whatever that function returns is what michael@0: calls to the mock return. The `side_effect` function is called with the michael@0: same arguments as the mock. This allows you to vary the return value of the michael@0: call dynamically, based on the input: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> def side_effect(value): michael@0: ... return value + 1 michael@0: ... michael@0: >>> m = MagicMock(side_effect=side_effect) michael@0: >>> m(1) michael@0: 2 michael@0: >>> m(2) michael@0: 3 michael@0: >>> m.mock_calls michael@0: [call(1), call(2)] michael@0: michael@0: If you want the mock to still return the default return value (a new mock), or michael@0: any set return value, then there are two ways of doing this. Either return michael@0: `mock.return_value` from inside `side_effect`, or return :data:`DEFAULT`: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> m = MagicMock() michael@0: >>> def side_effect(*args, **kwargs): michael@0: ... return m.return_value michael@0: ... michael@0: >>> m.side_effect = side_effect michael@0: >>> m.return_value = 3 michael@0: >>> m() michael@0: 3 michael@0: >>> def side_effect(*args, **kwargs): michael@0: ... return DEFAULT michael@0: ... michael@0: >>> m.side_effect = side_effect michael@0: >>> m() michael@0: 3 michael@0: michael@0: To remove a `side_effect`, and return to the default behaviour, set the michael@0: `side_effect` to `None`: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> m = MagicMock(return_value=6) michael@0: >>> def side_effect(*args, **kwargs): michael@0: ... return 3 michael@0: ... michael@0: >>> m.side_effect = side_effect michael@0: >>> m() michael@0: 3 michael@0: >>> m.side_effect = None michael@0: >>> m() michael@0: 6 michael@0: michael@0: The `side_effect` can also be any iterable object. Repeated calls to the mock michael@0: will return values from the iterable (until the iterable is exhausted and michael@0: a `StopIteration` is raised): michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> m = MagicMock(side_effect=[1, 2, 3]) michael@0: >>> m() michael@0: 1 michael@0: >>> m() michael@0: 2 michael@0: >>> m() michael@0: 3 michael@0: >>> m() michael@0: Traceback (most recent call last): michael@0: ... michael@0: StopIteration michael@0: michael@0: If any members of the iterable are exceptions they will be raised instead of michael@0: returned: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> iterable = (33, ValueError, 66) michael@0: >>> m = MagicMock(side_effect=iterable) michael@0: >>> m() michael@0: 33 michael@0: >>> m() michael@0: Traceback (most recent call last): michael@0: ... michael@0: ValueError michael@0: >>> m() michael@0: 66 michael@0: michael@0: michael@0: .. _deleting-attributes: michael@0: michael@0: Deleting Attributes michael@0: =================== michael@0: michael@0: Mock objects create attributes on demand. This allows them to pretend to be michael@0: objects of any type. michael@0: michael@0: You may want a mock object to return `False` to a `hasattr` call, or raise an michael@0: `AttributeError` when an attribute is fetched. You can do this by providing michael@0: an object as a `spec` for a mock, but that isn't always convenient. michael@0: michael@0: You "block" attributes by deleting them. Once deleted, accessing an attribute michael@0: will raise an `AttributeError`. michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = MagicMock() michael@0: >>> hasattr(mock, 'm') michael@0: True michael@0: >>> del mock.m michael@0: >>> hasattr(mock, 'm') michael@0: False michael@0: >>> del mock.f michael@0: >>> mock.f michael@0: Traceback (most recent call last): michael@0: ... michael@0: AttributeError: f michael@0: michael@0: michael@0: Attaching Mocks as Attributes michael@0: ============================= michael@0: michael@0: When you attach a mock as an attribute of another mock (or as the return michael@0: value) it becomes a "child" of that mock. Calls to the child are recorded in michael@0: the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the michael@0: parent. This is useful for configuring child mocks and then attaching them to michael@0: the parent, or for attaching mocks to a parent that records all calls to the michael@0: children and allows you to make assertions about the order of calls between michael@0: mocks: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> parent = MagicMock() michael@0: >>> child1 = MagicMock(return_value=None) michael@0: >>> child2 = MagicMock(return_value=None) michael@0: >>> parent.child1 = child1 michael@0: >>> parent.child2 = child2 michael@0: >>> child1(1) michael@0: >>> child2(2) michael@0: >>> parent.mock_calls michael@0: [call.child1(1), call.child2(2)] michael@0: michael@0: The exception to this is if the mock has a name. This allows you to prevent michael@0: the "parenting" if for some reason you don't want it to happen. michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> mock = MagicMock() michael@0: >>> not_a_child = MagicMock(name='not-a-child') michael@0: >>> mock.attribute = not_a_child michael@0: >>> mock.attribute() michael@0: michael@0: >>> mock.mock_calls michael@0: [] michael@0: michael@0: Mocks created for you by :func:`patch` are automatically given names. To michael@0: attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock` michael@0: method: michael@0: michael@0: .. doctest:: michael@0: michael@0: >>> thing1 = object() michael@0: >>> thing2 = object() michael@0: >>> parent = MagicMock() michael@0: >>> with patch('__main__.thing1', return_value=None) as child1: michael@0: ... with patch('__main__.thing2', return_value=None) as child2: michael@0: ... parent.attach_mock(child1, 'child1') michael@0: ... parent.attach_mock(child2, 'child2') michael@0: ... child1('one') michael@0: ... child2('two') michael@0: ... michael@0: >>> parent.mock_calls michael@0: [call.child1('one'), call.child2('two')] michael@0: michael@0: michael@0: ----- michael@0: michael@0: .. [#] The only exceptions are magic methods and attributes (those that have michael@0: leading and trailing double underscores). Mock doesn't create these but michael@0: instead of raises an ``AttributeError``. This is because the interpreter michael@0: will often implicitly request these methods, and gets *very* confused to michael@0: get a new Mock object when it expects a magic method. If you need magic michael@0: method support see :ref:`magic methods `.