⚡ NEW: ./library/unittest.mock.html - Full Gallery 2025
unittest.mock — mock object library¶
New in version 3.3.
Source code: Lib/unittest/mock.py
unittest.mock is a library for testing in Python. It allows you to
replace parts of your system under test with mock objects and make assertions
about how they have been used.
unittest.mock provides a core Mock class removing 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.
Additionally, mock 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.
There is a backport of unittest.mock for earlier versions of Python,
available as mock on PyPI.
Quick Guide¶
Mock and MagicMock 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 unittest.mock import MagicMock
>>> thing = ProductionClass()
>>> thing.method = MagicMock(return_value=3)
>>> thing.method(3, 4, 5, key='value')
3
>>> thing.method.assert_called_with(3, 4, 5, key='value')
side_effect allows you to perform side effects, including raising an
exception when a mock is called:
>>> mock = Mock(side_effect=KeyError('foo'))
>>> mock()
Traceback (most recent call last):
...
KeyError: 'foo'
>>> values = {'a': 1, 'b': 2, 'c': 3}
>>> def side_effect(arg):
... return values[arg]
...
>>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, 3)
>>> mock.side_effect = [5, 4, 3, 2, 1]
>>> mock(), mock(), mock()
(5, 4, 3)
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 unittest.mock import patch
>>> @patch('module.ClassName2')
... @patch('module.ClassName1')
... def test(MockClass1, MockClass2):
... module.ClassName1()
... module.ClassName2()
... assert MockClass1 is module.ClassName1
... assert MockClass2 is 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 module.ClassName1 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', return_value=None) as mock_method:
... thing = ProductionClass()
... thing.method(1, 2, 3)
...
>>> mock_method.assert_called_once_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:
>>> 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:
>>> mock = Mock()
>>> mock.__str__ = Mock(return_value='wheeeeee')
>>> str(mock)
'wheeeeee'
For ensuring that the mock objects in your tests have the same api as the
objects they are replacing, you can use auto-speccing.
Auto-speccing can be done through the autospec argument to patch, or the
create_autospec() function. Auto-speccing creates mock objects that
have the same attributes and methods as the objects they are replacing, and
any functions and methods (including constructors) have the same call
signature as the real object.
This ensures that your mocks will fail in the same way as your production code if they are used incorrectly:
>>> from unittest.mock import create_autospec
>>> def function(a, b, c):
... pass
...
>>> mock_function = create_autospec(function, return_value='fishy')
>>> mock_function(1, 2, 3)
'fishy'
>>> mock_function.assert_called_once_with(1, 2, 3)
>>> mock_function('wrong arguments')
Traceback (most recent call last):
...
TypeError: <lambda>() takes exactly 3 arguments (1 given)
create_autospec() 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.
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.
MagicMock is a subclass of Mock with all the magic methods
pre-created and ready to use. There are also non-callable variants, useful
when you are mocking out objects that aren’t callable:
NonCallableMock and NonCallableMagicMock
The patch() decorators makes it easy to temporarily replace classes
in a particular module with a Mock object. By default patch() will create
a MagicMock for you. You can specify an alternative class of Mock using
the new_callable argument to patch().
-
class
unittest.mock.Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)¶ Create a new
Mockobject.Mocktakes 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.If spec is an object (rather than a list of strings) then
__class__returns the class of the spec object. This allows mocks to passisinstance()tests.spec_set: A stricter variant of spec. If used, attempting to set or get an attribute on the mock that isn’t on the object passed as spec_set will raise an
AttributeError.side_effect: A function to be called whenever the Mock is called. See the
side_effectattribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returnsDEFAULT, 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.
If side_effect is an iterable then each call to the mock will return the next value from the iterable.
A side_effect can be cleared by setting it to
None.return_value: The value returned when the mock is called. By default this is a new Mock (created on first access). See the
return_valueattribute.unsafe: By default if any attribute starts with assert or assret will raise an
AttributeError. Passingunsafe=Truewill allow access to these attributes.New in version 3.5.
wraps: Item for the mock object to wrap. If wraps is not
Nonethen calling the Mock will pass the call through to the wrapped object (returning the real result). 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 anAttributeError).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.
name: If the mock has a name then it will be used in the repr of the mock. This can be useful for debugging. The name is propagated to child mocks.
Mocks can also be called with arbitrary keyword arguments. These will be used to set attributes on the mock after it is created. See the
configure_mock()method for details.-
assert_called()¶ Assert that the mock was called at least once.
>>> mock = Mock() >>> mock.method() <Mock name='mock.method()' id='...'> >>> mock.method.assert_called()
New in version 3.6.
-
assert_called_once()¶ Assert that the mock was called exactly once.
>>> mock = Mock() >>> mock.method() <Mock name='mock.method()' id='...'> >>> mock.method.assert_called_once() >>> mock.method() <Mock name='mock.method()' id='...'> >>> mock.method.assert_called_once() Traceback (most recent call last): ... AssertionError: Expected 'method' to have been called once. Called 2 times.
New in version 3.6.
-
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 name='mock.method()' id='...'> >>> mock.method.assert_called_with(1, 2, 3, test='wow')
-
assert_called_once_with(*args, **kwargs)¶ Assert that the mock was called exactly once and that that call was with the specified arguments.
>>> mock = Mock(return_value=None) >>> mock('foo', bar='baz') >>> mock.assert_called_once_with('foo', bar='baz') >>> mock('other', bar='values') >>> mock.assert_called_once_with('other', bar='values') Traceback (most recent call last): ... AssertionError: Expected 'mock' to be called once. Called 2 times.
-
assert_any_call(*args, **kwargs)¶ assert the mock has been called with the specified arguments.
The assert passes if the mock has ever been called, unlike
assert_called_with()andassert_called_once_with()that only pass if the call is the most recent one, and in the case ofassert_called_once_with()it must also be the only call.>>> mock = Mock(return_value=None) >>> mock(1, 2, arg='thing') >>> mock('some', 'thing', 'else') >>> mock.assert_any_call(1, 2, arg='thing')
-
assert_has_calls(calls, any_order=False)¶ assert the mock has been called with the specified calls. The
mock_callslist is checked for the calls.If any_order is false then the calls must be sequential. There can be extra calls before or after the specified calls.
If any_order is true then the calls can be in any order, but they must all appear in
mock_calls.>>> mock = Mock(return_value=None) >>> mock(1) >>> mock(2) >>> mock(3) >>> mock(4) >>> calls = [call(2), call(3)] >>> mock.assert_has_calls(calls) >>> calls = [call(4), call(2), call(3)] >>> mock.assert_has_calls(calls, any_order=True)
-
assert_not_called()¶ Assert the mock was never called.
>>> m = Mock() >>> m.hello.assert_not_called() >>> obj = m.hello() >>> m.hello.assert_not_called() Traceback (most recent call last): ... AssertionError: Expected 'hello' to not have been called. Called 1 times.
New in version 3.5.
-
reset_mock(*, return_value=False, side_effect=False)¶ The reset_mock method resets all the call attributes on a mock object:
>>> mock = Mock(return_value=None) >>> mock('hello') >>> mock.called True >>> mock.reset_mock() >>> mock.called False
Changed in version 3.6: Added two keyword only argument to the reset_mock function.
This can be useful where you want to make a series of assertions that reuse the same object. Note that
reset_mock()doesn’t clear the return value,side_effector any child attributes you have set using normal assignment by default. In case you want to reset return_value orside_effect, then pass the corresponding parameter asTrue. Child mocks and the return value mock (if any) are reset as well.Note
return_value, and
side_effectare keyword only argument.
-
mock_add_spec(spec, spec_set=False)¶ Add a spec to a mock. spec can either be an object or a list of strings. Only attributes on the spec can be fetched as attributes from the mock.
If spec_set is true then only attributes on the spec can be set.
-
attach_mock(mock, attribute)¶ Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the
method_callsandmock_callsattributes of this one.
