In the last example we patched a method directly on an object to check that it
was called correctly. Another common use case is to pass an object into a
method (or some part of the system under test) and then check that it is used
in the correct way.

The simple ProductionClass below has a closer method. If it is called with
an object then it calls close on it.

We don’t have to do any work to provide the ‘close’ method on our mock.
Accessing close creates it. So, if ‘close’ hasn’t already been called then
accessing it in the test will create it, but assert_called_with()
will raise a failure exception.

A common use case is to mock out classes instantiated by your code under test.
When you patch a class, then that class is replaced with a mock. Instances
are created by calling the class. This means you access the “mock instance”
by looking at the return value of the mocked class.

In the example below we have a function some_function that instantiates Foo
and calls a method on it. The call to patch() replaces the class Foo with a
mock. The Foo instance is the result of calling the mock, so it is configured
by modifying the mock return_value.

It can be useful to give your mocks a name. The name is shown in the repr of
the mock and can be helpful when the mock appears in test failure messages. The
name is also propagated to attributes or methods of the mock:

If you make an assertion about mock_calls and any unexpected methods
have been called, then the assertion will fail. This is useful because as well
as asserting that the calls you expected have been made, you are also checking
that they were made in the right order and with no additional calls:

You use the call object to construct lists for comparing with
mock_calls:

Sometimes you want to mock up a more complex situation, like for example
mock.connection.cursor().execute("SELECT1"). If we wanted this call to
return a list, then we have to configure the result of the nested call.

We can use call to construct the set of calls in a “chained call” like
this for easy assertion afterwards:

side_effect can also be set to a function or an iterable. The use case for
side_effect as an iterable is where your mock is going to be called several
times, and you want each call to return a different value. When you set
side_effect to an iterable every call to the mock returns the next value
from the iterable:

For more advanced use cases, like dynamically varying the return values
depending on what the mock is called with, side_effect can be a function.
The function will be called with the same arguments as the mock. Whatever the
function returns is what the call returns:

One problem with over use of mocking is that it couples your tests to the
implementation of your mocks rather than your real code. Suppose you have a
class that implements some_method. In a test for another class, you
provide a mock of this object that also provides some_method. If later
you refactor the first class, so that it no longer has some_method - then
your tests will continue to pass even though your code is now broken!

Mock allows you to provide an object as a specification for the mock,
using the spec keyword argument. Accessing methods / attributes on the
mock that don’t exist on your specification object will immediately raise an
attribute error. If you change the implementation of your specification, then
tests that use that class will start failing immediately without you having to
instantiate the class in those tests.

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.

A common need in tests is to patch a class attribute or a module attribute,
for example patching a builtin or patching a class in a module to test that it
is instantiated. Modules and classes are effectively global, so patching on
them has to be undone after the test or the patch will persist into other
tests and cause hard to diagnose problems.

mock provides three convenient decorators for this: patch(), patch.object() and
patch.dict(). 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.

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.

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:

As an alternative patch, patch.object and patch.dict can be used as
class decorators. When used in this way it is the same as applying the
decorator individually to every method whose name starts with “test”.

Mocking chained calls is actually straightforward with mock once you
understand the return_value attribute. When a mock is called for
the first time, or you fetch its return_value before it has been called, a
new Mock is created.

This means that you can see how the object returned from a call to a mocked
object has been used by interrogating the return_value mock:

Assuming that BackendProvider is already well tested, how do we test
method()? Specifically, we want to test that the code section #morecode uses the response object in the correct way.

As this chain of calls is made from an instance attribute we can monkey patch
the backend attribute on a Something instance. In this particular case
we are only interested in the return value from the final call to
start_call so we don’t have much configuration to do. Let’s assume the
object it returns is ‘file-like’, so we’ll ensure that our response object
uses the builtin open() as its spec.

To do this we create a mock instance as our mock backend and create a mock
response object for it. To set the response as the return value for that final
start_call we could do this:

With these we monkey patch the “mock backend” in place and can make the real
call:

>>> something.backend=mock_backend>>> something.method()

Using mock_calls we can check the chained call with a single
assert. A chained call is several calls in one line of code, so there will be
several entries in mock_calls. We can use call.call_list() to create
this list of calls for us:

In some tests I wanted to mock out a call to datetime.date.today()
to return a known date, but I didn’t want to prevent the code under test from
creating new date objects. Unfortunately datetime.date is written in C, and
so I couldn’t just monkey-patch out the static date.today() method.

I found a simple way of doing this that involved effectively wrapping the date
class with a mock, but passing through calls to the constructor to the real
class (and returning real instances).

The patchdecorator is used here to
mock out the date class in the module under test. The side_effect
attribute on the mock date class is then set to a lambda function that returns
a real date. When the mock date class is called a real date will be
constructed and returned by side_effect.

When date.today() is called a known date is returned, but calls to the
date(...) constructor still return normal dates. Without this you can find
yourself having to calculate an expected result using exactly the same
algorithm as the code under test, which is a classic testing anti-pattern.

Calls to the date constructor are recorded in the mock_date attributes
(call_count and friends) which may also be useful for your tests.

An alternative way of dealing with mocking dates, or other builtin classes,
is discussed in this blog entry.

A Python generator is a function or method that uses the yield statement
to return a series of values when iterated over [1].

A generator method / function is called to return the generator object. It is
the generator object that is then iterated over. The protocol method for
iteration is __iter__(), so we can
mock this using a MagicMock.

Here’s an example class with an “iter” method implemented as a generator:

If you want several patches in place for multiple test methods the obvious way
is to apply the patch decorators to every method. This can feel like unnecessary
repetition. For Python 2.6 or more recent you can use patch() (in all its
various forms) as a class decorator. This applies the patches to all test
methods on the class. A test method is identified by methods whose names start
with test:

If you use this technique you must ensure that the patching is “undone” by
calling stop. This can be fiddlier than you might think, because if an
exception is raised in the setUp then tearDown is not called.
unittest.TestCase.addCleanup() makes this easier:

Whilst writing tests today I needed to patch an unbound method (patching the
method on the class rather than on the instance). I needed self to be passed
in as the first argument because I want to make asserts about which objects
were calling this particular method. The issue is that you can’t patch with a
mock for this, because if you replace an unbound method with a mock it doesn’t
become a bound method when fetched from the instance, and so it doesn’t get
self passed in. The workaround is to patch the unbound method with a real
function instead. The patch() decorator makes it so simple to
patch out methods with a mock that having to create a real function becomes a
nuisance.

If you pass autospec=True to patch then it does the patching with a
real function object. This function object has the same signature as the one
it is replacing, but delegates to a mock under the hood. You still get your
mock auto-created in exactly the same way as before. What it means though, is
that if you use it to patch out an unbound method on a class the mocked
function will be turned into a bound method if it is fetched from an instance.
It will have self passed in as the first argument, which is exactly what I
wanted:

Both assert_called_with and assert_called_once_with make assertions about
the most recent call. If your mock is going to be called several times, and
you want to make assertions about all those calls you can use
call_args_list:

The call helper makes it easy to make assertions about these calls. You
can build up a list of expected calls and compare it to call_args_list. This
looks remarkably similar to the repr of the call_args_list:

Another situation is rare, but can bite you, is when your mock is called with
mutable arguments. call_args and call_args_list store references to the
arguments. If the arguments are mutated by the code under test then you can no
longer make assertions about what the values were when the mock was called.

Here’s some example code that shows the problem. Imagine the following functions
defined in ‘mymodule’:

deffrob(val):passdefgrob(val):"First frob and then clear val"frob(val)val.clear()

When we try to test that grob calls frob with the correct argument look
what happens:

One possibility would be for mock to copy the arguments you pass in. This
could then cause problems if you do assertions that rely on object identity
for equality.

Here’s one solution that uses the side_effect
functionality. If you provide a side_effect function for a mock then
side_effect will be called with the same args as the mock. This gives us an
opportunity to copy the arguments and store them for later assertions. In this
example I’m using another mock to store the arguments so that I can use the
mock methods for doing the assertion. Again a helper function sets this up for
me.

When you subclass Mock or MagicMock all dynamically created attributes,
and the return_value will use your subclass automatically. That means all
children of a CopyingMock will also have the type CopyingMock.

With unittest cleanup functions and the patch methods: start and stop we can
achieve the same effect without the nested indentation. A simple helper
method, create_patch, puts the patch in place and returns the created mock
for us:

You may want to mock a dictionary, or other container object, recording all
access to it whilst having it still behave like a dictionary.

We can do this with MagicMock, which will behave like a dictionary,
and using side_effect to delegate dictionary access to a real
underlying dictionary that is under our control.

When the __getitem__() and __setitem__() methods of our MagicMock are called
(normal dictionary access) then side_effect is called with the key (and in
the case of __setitem__ the value too). We can also control what is returned.

After the MagicMock has been used we can use attributes like
call_args_list to assert about how the dictionary was used:

The standard behaviour for Mock instances is that attributes and the return
value mocks are of the same type as the mock they are accessed on. This ensures
that Mock attributes are Mocks and MagicMock attributes are MagicMocks[2]. So if you’re subclassing to add helper methods then they’ll also be
available on the attributes and return value mock of instances of your
subclass.

Sometimes this is inconvenient. For example, one user is subclassing mock to
created a Twisted adaptor.
Having this applied to attributes too actually causes errors.

Mock (in all its flavours) uses a method called _get_child_mock to create
these “sub-mocks” for attributes and return values. You can prevent your
subclass being used for attributes by overriding this method. The signature is
that it takes arbitrary keyword arguments (**kwargs) which are then passed
onto the mock constructor:

One situation where mocking can be hard is where you have a local import inside
a function. These are harder to mock because they aren’t using an object from
the module namespace that we can patch out.

Generally local imports are to be avoided. They are sometimes done to prevent
circular dependencies, for which there is usually a much better way to solve
the problem (refactor the code) or to prevent “up front costs” by delaying the
import. This can also be solved in better ways than an unconditional local
import (store the module as a class or module attribute and only do the import
on first use).

That aside there is a way to use mock to affect the results of an import.
Importing fetches an object from the sys.modules dictionary. Note that it
fetches an object, which need not be a module. Importing a module for the
first time results in a module object being put in sys.modules, so usually
when you import something you get a module back. This need not be the case
however.

This means you can use patch.dict() to temporarily put a mock in place
in sys.modules. Any imports whilst this patch is active will fetch the mock.
When the patch is complete (the decorated function exits, the with statement
body is complete or patcher.stop() is called) then whatever was there
previously will be restored safely.

The Mock class allows you to track the order of method calls on
your mock objects through the method_calls attribute. This
doesn’t allow you to track the order of calls between separate mock objects,
however we can use mock_calls to achieve the same effect.

Because mocks track calls to child mocks in mock_calls, and accessing an
arbitrary attribute of a mock creates a child mock, we can create our separate
mocks from a parent one. Calls to those child mock will then all be recorded,
in order, in the mock_calls of the parent:

If many calls have been made, but you’re only interested in a particular
sequence of them then an alternative is to use the
assert_has_calls() method. This takes a list of calls (constructed
with the call object). If that sequence of calls are in
mock_calls then the assert succeeds.

Even though the chained call m.one().two().three() aren’t the only calls that
have been made to the mock, the assert still succeeds.

Sometimes a mock may have several calls made to it, and you are only interested
in asserting about some of those calls. You may not even care about the
order. In this case you can pass any_order=True to assert_has_calls:

Using the same basic concept as ANY we can implement matchers to do more
complex assertions on objects used as arguments to mocks.

Suppose we expect some object to be passed to a mock that by default
compares equal based on object identity (which is the Python default for user
defined classes). To use assert_called_with() we would need to pass
in the exact same object. If we are only interested in some of the attributes
of this object then we can create a matcher that will check these attributes
for us.

You can see in this example how a ‘standard’ call to assert_called_with isn’t
sufficient:

The Matcher is instantiated with our compare function and the Foo object
we want to compare against. In assert_called_with the Matcher equality
method will be called, which compares the object the mock was called with
against the one we created our matcher with. If they match then
assert_called_with passes, and if they don’t an AssertionError is raised: