The Mock Class

Mock is a flexible mock object intended to replace the use of stubs and test doubles throughout your code. Mocks are callable and create attributes as new mocks when you access them [1]. Accessing the same attribute will always return the same mock. Mocks record how you use them, allowing you to make assertions about what your code has done to them.

The mock.patch() decorators makes it easy to temporarily replace classes in a particular module with a Mock object.

class Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None)

Create a new Mock object. Mock takes several optional arguments that specify the behaviour of the Mock object:

  • spec: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an AttributeError.

  • side_effect: A function to be called whenever the Mock is called. See the Mock.side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT, the return value of this function is used as the return value.

    Alternatively side_effect can be an exception class or instance. In this case the exception will be raised when the mock is called.

  • return_value: The value returned when the mock is called. By default this is a new Mock (created on first access). See the Mock.return_value attribute.

  • wraps: Item for the mock object to wrap. If wraps is not None then calling the Mock will pass the call through to the wrapped object (returning the real result and ignoring return_value). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn’t exist will raise an AttributeError).

    If the mock has an explicit return_value set then calls are not passed to the wrapped object and the return_value is returned instead.

Methods

Mock.assert_called_with(*args, **kwargs)

This method is a convenient way of asserting that calls are made in a particular way:

>>> mock = Mock()
>>> mock.method(1, 2, 3, test='wow')
<mock.Mock object at 0x...>
>>> mock.method.assert_called_with(1, 2, 3, test='wow')
Mock.reset_mock()

The reset_mock method resets all the call attributes on a mock object:

>>> mock = Mock()
>>> mock('hello')
<mock.Mock object at 0x...>
>>> mock.called
True
>>> mock.reset_mock()
>>> mock.called
False

This can be useful where you want to make a series of assertions that reuse the same object. Note that reset doesn’t clear the return value, side_effect or any child attributes. Attributes you have set using normal assignment are also left in place. Child mocks and the return value mock (if any) are reset as well.

Calling

Mock objects are callable. The call will return the value set as the Mock.return_value attribute. The default return value is a new Mock object; it is created the first time the return value is accessed (either explicitly or by calling the Mock) - but it is stored and the same one returned each time.

Calls made to the object will be recorded in the attributes.

If Mock.side_effect is set then it will be called after the call has been recorded but before any value is returned.

Attributes

Mock.called

A boolean representing whether or not the mock object has been called:

>>> mock = Mock(return_value=None)
>>> mock.called
False
>>> mock()
>>> mock.called
True
Mock.call_count

An integer telling you how many times the mock object has been called:

>>> mock = Mock(return_value=None)
>>> mock.call_count
0
>>> mock()
>>> mock()
>>> mock.call_count
2
Mock.return_value

Set this to configure the value returned by calling the mock:

>>> mock = Mock()
>>> mock.return_value = 'fish'
>>> mock()
'fish'

The default return value is a mock object and you can configure it in the normal way:

>>> mock = Mock()
>>> mock.return_value.attribute = sentinel.Attribute
>>> mock.return_value()
<mock.Mock object at 0x...>
>>> mock.return_value.assert_called_with()
Mock.side_effect

This can either be a function to be called when the mock is called, or an exception (class or instance) to raised.

If you pass in a function it will be called with same arguments as the mock and unless the mock returns the DEFAULT singleton the mock will return whatever the function returns. If the function returns default then the mock will return its normal value (from the Mock.return_value.

An example of a mock that raises an exception (to test exception handling of an API):

>>> mock = Mock()
>>> mock.side_effect = Exception('Boom!')
>>> mock()
Traceback (most recent call last):
  ...
Exception: Boom!

Using side_effect to return a sequence of values:

>>> mock = Mock()
>>> results = [1, 2, 3]
>>> def side_effect(*args, **kwargs):
...     return results.pop()
...
>>> mock.side_effect = side_effect
>>> mock(), mock(), mock()
(3, 2, 1)

The side_effect function is called with the same arguments as the mock (so it is wise for it to take arbitrary args and keyword arguments) and whatever it returns is used as the return value for the call. The exception is if it returns DEFAULT, in which case the normal Mock.return_value is used.

>>> mock = Mock(return_value=3)
>>> def side_effect(*args, **kwargs):
...     return DEFAULT
...
>>> mock.side_effect = side_effect
>>> mock()
3
Mock.call_args

This is either None (if the mock hasn’t been called), or the arguments that the mock was last called with. This will be in the form of a tuple: the first member is any ordered arguments the mock was called with (or an empty tuple) and the second member is any keyword arguments (or an empty dictionary):

>>> mock = Mock(return_value=None)
>>> print mock.call_args
None
>>> mock()
>>> mock.call_args
((), {})
>>>
>>> mock(3, 4, 5, key='fish', next='w00t!')
>>> mock.call_args
((3, 4, 5), {'key': 'fish', 'next': 'w00t!'})
Mock.call_args_list

This is a list of all the calls made to the mock object in sequence (so the length of the list is the number of times it has been called). Before any calls have been made it is an empty list:

>>> mock = Mock()
>>> mock()
<mock.Mock object at 0x...>
>>> mock(3, 4, 5, key='fish', next='w00t!')
<mock.Mock object at 0x...>
>>> mock.call_args_list
[((), {}), ((3, 4, 5), {'key': 'fish', 'next': 'w00t!'})]
Mock.method_calls

As well as tracking calls to themselves, mocks also track calls to methods and attributes, and their methods and attributes:

>>> mock = Mock()
>>> mock.method()
<mock.Mock object at 0x...>
>>> mock.property.method.attribute()
<mock.Mock object at 0x...>
>>> mock.method_calls
[('method', (), {}), ('property.method.attribute', (), {})]

[1]The only exceptions are magic methods and attributes (those that have leading and trailing double underscores). Mock doesn’t create these but instead of raises an AttributeError. This is because the interpreter will often implicitly request these methods, and gets very confused to get a new Mock object when it expects a magic method.

Table Of Contents

Previous topic

Mock - Mocking and Testing Library

Next topic

Patch Decorators

This Page