Getting Started with Mock — Mock v0.7.0rc1 documentation

### Navigation

- index
- next |
- previous |
- Mock v0.7.0rc1 documentation »

# Getting Started with Mock

## Using Mock

`Mock` objects can be used for:

- Patching methods
- Recording method calls on objects

    >>> from mock import Mock
    >>> real = ProductionClass()
    >>> real.method = Mock()
    >>>
    >>> real.method(3, 4, 5, key='value')
    <mock.Mock object at 0x...>
    >>>

Once the mock has been used it has methods and attributes that allow you to make assertions about how it has been used:

    >>> real.method.assert_called_with(3, 4, 5, key='value')
    >>> real.method.called
    True
    >>> real.method.call_args
    ((3, 4, 5), {'key': 'value'})
    >>>

Mocks also record calls made to attributes, their ‘child’ attributes:

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

You can also create Mock objects that behave like the class they are intended to mock. This is done with the `spec` keyword argument, which either takes a list of strings describing the attributes that the mock should have - or you can pass in the object (class or instance) that you are mocking out. Attempting to access an attribute on the mock that isn’t in the spec will raise an `AttributeError`.

    >>> mock = Mock(spec=['something'])
    >>> mock.something()
    <mock.Mock object at 0x...>
    >>> mock.something_else()
    Traceback (most recent call last):
       ...
    AttributeError: object has no attribute 'something_else'

There are various ways of configuring the mock, including setting return values on the mock and its methods. A useful attribute is `side_effect`. If you set this to an exception class or instance then the exception will be raised when the mock is called. If you set it to a callable then it will be called whenever the mock is called. This allows you to do things like return members of a sequence from repeated calls:

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

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

## Sentinel

`sentinel` is a useful object for providing unique objects in your tests:

    >>> from mock import sentinel
    >>> real = ProductionClass()
    >>> real.method = Mock()
    >>>
    >>> real.method.return_value = sentinel.return_value
    >>> real.method()
    <SentinelObject "return_value">

## Patch Decorators

There are also decorators for doing module and class level patching. As modules and classes are effectively globals any patching has to be undone (or it persists into other tests). These decorators do the unpatching for you, making it easier to test with module and class level patching.

The two decorators are ‘patch’ and ‘patch.object’. ‘patch’ takes a single string, of the form `package.module.Class.attribute` to specify the attribute you are patching. It also optionally takes a value that you want the attribute (or class or whatever) to be replaced with. ‘patch.object’ takes an object and the name of the attribute you would like patched, plus optionally the value to patch it with.

    original = SomeClass.attribute
    @patch.object(SomeClass, 'attribute', sentinel.Attribute)
    def test():
        self.assertEqual(SomeClass.attribute, sentinel.Attribute, "class attribute not patched")
    test()

    self.assertEqual(SomeClass.attribute, original, "attribute not restored")

    @patch('Package.Module.attribute', sentinel.Attribute)
    def test():
        "do something"
    test()

If you don’t want to call the decorated test function yourself, you can add `apply` as a decorator on top:

    @apply
    @patch('Package.Module.attribute', sentinel.Attribute)
    def test():
        "do something"

(Note that this leaves test == None)

A nice pattern is to actually decorate test methods themselves:

    @patch('Package.Module.attribute', sentinel.Attribute)
    def testMethod(self):
        "do something"

If you want to patch with a Mock, you can use `patch` with only one argument (or `patch.object` with two arguments). The mock will be created for you and passed into the test function / method:

    @patch('Package.Module.Class')
    def testMethod(self, mMckClass):
        "do something"

### Navigation

- index
- next |
- previous |
- Mock v0.7.0rc1 documentation »