Mock - Mocking and Testing Library — Mock v0.7.0 documentation

Mock v0.7.0 documentation

# Mock - Mocking and Testing Library

- Table of Contents
- index
  next

# Mock - Mocking and Testing Library

Author: | Michael Foord
Co-maintainer: | Konrad Delong
Version: | 0.7.0
Date: | 2011/03/05
Homepage: | Mock Homepage
Download: | Mock on PyPI
Documentation: | PDF Documentation
License: | BSD License
Support: | Mailing list (testing-in-python@lists.idyll.org)
Issue tracker: | Google code project

mock is a Python module that provides a core `Mock` class. It removes the need to create a host of stubs throughout your test suite. After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. You can also specify return values and set needed attributes in the normal way.

The mock module also provides a `patch()` decorator that handles patching module and class level attributes within the scope of a test, along with `sentinel` for creating unique objects. See the quick guide for some examples of how to use `Mock`, `MagicMock` and `patch()`.

Mock is very easy to use and is designed for use with unittest. Mock is based on the ‘action -> assertion’ pattern instead of ‘record -> replay’ used by many mocking frameworks.

mock is tested on Python versions 2.4-2.7 and Python 3.

## API Documentation

- The Mock Class
  - Methods
  - Calling
  - Attributes
- Patch Decorators
  - patch
  - patch.object
  - patch_object
  - patch.dict
  - patch methods: start and stop
  - Nesting Patch Decorators
  - Where to patch
  - Patching Descriptors and Proxy Objects
- Sentinel
  - Sentinel Example
- Mocking Magic Methods
- Magic Mock
- mocksignature
  - Example use
  - mocksignature argument to patch

## User Guide

- Getting Started with Mock
  - Using Mock
  - Sentinel
  - Patch Decorators
- Further Examples
  - Mocking chained calls
  - Partial mocking
  - Mocking open
  - Applying the same patch to every test method
  - Mocking Unbound Methods
  - Mocking Properties
  - Checking multiple calls with mock
  - Coping with mutable arguments
  - Mocking multiple calls
- Mock Library Comparison
  - Simple fake object
  - Simple mock
  - Creating partial mocks
  - Ensure calls are made in specific order
  - Raising exceptions
  - Override new instances of a class
  - Call the same method multiple times
  - Mock chained methods
  - Mocking a context manager
  - Mocking the builtin open used as a context manager
- TODO and Limitations
- CHANGELOG
  - 2011/03/05 Version 0.7.0
  - 2011/02/16 Version 0.7.0 RC 1
  - 2010/11/12 Version 0.7.0 beta 4
  - 2010/09/18 Version 0.7.0 beta 3
  - 2010/06/23 Version 0.7.0 beta 2
  - 2010/06/22 Version 0.7.0 beta 1
  - 2009/08/22 Version 0.6.0
  - 2009/04/17 Version 0.5.0
  - 2008/10/12 Version 0.4.0
  - 2007/12/03 Version 0.3.1
  - 2007/11/30 Version 0.3.0
  - 2007/11/21 Version 0.2.1
  - 2007/11/20 Version 0.2.0
  - 2007/11/19 Version 0.1.0

## Installing

The current version is 0.7.0. Mock is still experimental; the API may change (although we are moving towards a 1.0 release when the API will stabilise). If you find bugs or have suggestions for improvements / extensions then please contact us.

- mock on PyPI
- mock documentation as PDF
- Google Code Home & Mercurial Repository

You can checkout the latest development version from the Google Code Mercurial repository with the following command:

> `hg clone https://mock.googlecode.com/hg/ mock`

If you have pip, setuptools or distribute you can install mock with:

> `easy_install -U mock`
> `pip install -U mock`

Alternatively you can download the mock distribution from PyPI and after unpacking run:

> `python setup.py install`

## Quick Guide

`Mock` objects create all attributes and methods as you access them and store details of how they have been used. You can configure them, to specify return values or limit what attributes are available, and then make assertions about how they have been used:

    >>> from mock import Mock
    >>> real = ProductionClass()
    >>> real.method = Mock(return_value=3)
    >>> real.method(3, 4, 5, key='value')
    3
    >>> real.method.assert_called_with(3, 4, 5, key='value')

`side_effect` allows you to perform side effects, return different values or raise an exception when a mock is called:

    >>> from mock import Mock
    >>> mock = Mock(side_effect=KeyError('foo'))
    >>> mock()
    Traceback (most recent call last):
     ...
    KeyError: 'foo'
    >>> values = [1, 2, 3]
    >>> def side_effect():
    ...     return values.pop()
    ...
    >>> mock.side_effect = side_effect
    >>> mock(), mock(), mock()
    (3, 2, 1)

Mock has many other ways you can configure it and control its behaviour. For example the `spec` argument configures the mock to take its specification from another object. Attempting to access attributes or methods on the mock that don’t exist on the spec will fail with an `AttributeError`.

The `patch()` decorator / context manager makes it easy to mock classes or objects in a module under test. The object you specify will be replaced with a mock (or other object) during the test and restored when the test ends:

    >>> from mock import patch
    >>> @patch('test_module.ClassName1')
    ... @patch('test_module.ClassName2')
    ... def test(MockClass2, MockClass1):
    ...     test_module.ClassName1()
    ...     test_module.ClassName2()

    ...     assert MockClass1 is test_module.ClassName1
    ...     assert MockClass2 is test_module.ClassName2
    ...     assert MockClass1.called
    ...     assert MockClass2.called
    ...
    >>> test()

Note

When you nest patch decorators the mocks are passed in to the decorated function in the same order they applied (the normal python order that decorators are applied). This means from the bottom up, so in the example above the mock for test_module.ClassName2 is passed in first.

With patch it matters that you patch objects in the namespace where they are looked up. This is normally straightforward, but for a quick guide read where to patch.

As well as a decorator patch can be used as a context manager in a with statement:

    >>> with patch.object(ProductionClass, 'method') as mock_method:
    ...     mock_method.return_value = None
    ...     real = ProductionClass()
    ...     real.method(1, 2, 3)
    ...
    >>> mock_method.assert_called_with(1, 2, 3)

There is also `patch.dict()` for setting values in a dictionary just during a scope and restoring the dictionary to its original state when the test ends:

    >>> foo = {'key': 'value'}
    >>> original = foo.copy()
    >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
    ...     assert foo == {'newkey': 'newvalue'}
    ...
    >>> assert foo == original

Mock supports the mocking of Python magic methods. The easiest way of using magic methods is with the `MagicMock` class. It allows you to do things like:

    >>> from mock import MagicMock
    >>> mock = MagicMock()
    >>> mock.__str__.return_value = 'foobarbaz'
    >>> str(mock)
    'foobarbaz'
    >>> mock.__str__.assert_called_with()

Mock allows you to assign functions (or other Mock instances) to magic methods and they will be called appropriately. The MagicMock class is just a Mock variant that has all of the magic methods pre-created for you (well - all the useful ones anyway).

The following is an example of using magic methods with the ordinary Mock class:

    >>> from mock import Mock
    >>> mock = Mock()
    >>> mock.__str__ = Mock()
    >>> mock.__str__.return_value = 'wheeeeee'
    >>> str(mock)
    'wheeeeee'

`mocksignature()` is a useful companion to Mock and patch. It creates copies of functions that delegate to a mock, but have the same signature as the original function. This ensures that your mocks will fail in the same way as your production code if they are called incorrectly:

    >>> from mock import mocksignature
    >>> def function(a, b, c):
    ...     pass
    ...
    >>> function2 = mocksignature(function)
    >>> function2.mock.return_value = 'fishy'
    >>> function2(1, 2, 3)
    'fishy'
    >>> function2.mock.assert_called_with(1, 2, 3)
    >>> function2('wrong arguments')
    Traceback (most recent call last):
     ...
    TypeError: <lambda>() takes exactly 3 arguments (1 given)

mocksignature can also be used on classes, where it copies the signature of the __init__ method, and on callable objects where it copies the signature of the __call__ method.

## References

Articles and blog entries on testing with Mock:

- Mocking Django
- Mock recipes
- Mockity mock mock - some love for the mock module
- Python Unit Testing with Mock
- Python mock testing techniques and tools
- How To Test Django Template Tags
- A presentation on Unit Testing with Mock
- Mocking with Django and Google AppEngine

## Tests

Mock uses unittest2 for its own test suite. In order to run it, use the `unit2` script that comes with `unittest2` module on a checkout of the source repository:

> `unit2 discover`

If you have setuptools as well as unittest2 you can run:

> `python setup.py test`

On Python 3.2 you can use `unittest` module from the standard library.

> `python3.2 -m unittest discover`

On Python 3 the tests for unicode are skipped as they are not relevant. On Python 2.4 tests that use the with statements are skipped as the with statement is invalid syntax on Python 2.4.

## Older Versions

Documentation for older versions of mock:

- mock 0.6.0

## Terminology

Terminology for objects used to replace other ones can be confusing. Terms like double, fake, mock, stub, and spy are all used with varying meanings.

In classic mock terminology `mock.Mock` is a spy that allows for post-mortem examination. This is what I call the “action -> assertion” pattern of testing.

I’m not however a fan of this “statically typed mocking terminology” promulgated by Martin Fowler. It confuses usage patterns with implementation and prevents you from using natural terminology when discussing mocking.

I much prefer duck typing, if an object used in your test suite looks like a mock object and quacks like a mock object then its fine to call it a mock no matter what the implementation looks like.

This terminology is perhaps more useful in less capable languages where different usage patterns will require different implementations. mock.Mock() is capable of being used in most of the different roles described by Fowler, except (annoyingly / frustratingly / ironically) a Mock itself!

How about a simpler definition: a “mock object” is an object used to replace a real one in a system under test.