Cara menggunakan python mock tutorial

{
  "Comment": "An example of using retry and catch to handle API responses",
  "StartAt": "Call API",
  "States": {
    "Call API": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME",
      "Next" : "OK",
      "Comment": "Catch a 429 (Too many requests) API exception, and resubmit the failed request in a rate-limiting fashion.",
      "Retry" : [ {
        "ErrorEquals": [ "TooManyRequestsException" ],
        "IntervalSeconds": 1,
        "MaxAttempts": 2
      } ],
      "Catch": [ 
        {
          "ErrorEquals": ["TooManyRequestsException"],
          "Next": "Wait and Try Later"
        }, {
          "ErrorEquals": ["ServerUnavailableException"],
          "Next": "Server Unavailable"
        }, {
          "ErrorEquals": ["States.ALL"],
          "Next": "Catch All"
        }
      ]
    },
    "Wait and Try Later": {
      "Type": "Wait",
      "Seconds" : 1,
      "Next" : "Change to 200"
    },
    "Server Unavailable": {
      "Type": "Fail",
      "Error":"ServerUnavailable",
      "Cause": "The server is currently unable to handle the request."
    },
    "Catch All": {
      "Type": "Fail",
      "Cause": "Unknown error!",
      "Error": "An error of unknown type occurred"
    },
    "Change to 200": {
      "Type": "Pass",
      "Result": {"statuscode" :"200"} ,
      "Next": "Call API"
    },
    "OK": {
      "Type": "Pass",
      "Result": "The request has succeeded.",
      "End": true
    }
  }
}

Partial functions allow us to fix a certain number of arguments of a function and generate a new function.

Example:




from functoolsimport partial

  

# A normal function

def f(a, b, c, x):

312
0
312
1
312
2
312
3
312
4
312
5
312
6
312
3
312
8
312
5 from0
312
3from2
312
5 from4

  

from6

from7

from8from9 functools0functools1functools2functools3functools2functools5functools6

  

functools8

functools9import0import1import2

Output:

3145

In the example we have pre-filled our function with some constant values of a, b and c. And g() just takes a single argument i.e. the variable x.

Another Example :




from functoolsimport

312
3

  

# A normal function

def partial0

312
0
312
1
312
6
312
3
312
4
312
5 from0
312
3
312
8
312
5 from2

  

 3

 4from9  6from9  8 9from9 functools3functools6

  

# A normal function4

functools9# A normal function6functools1import2

Output:

312
  • Partial functions can be used to derive specialized functions from general functions and therefore help us to reuse our code.
  • This feature is similar to bind in C++.

This article is contributed by Mayank Rawat .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

You might want to replace a method on an object to check that it is called with the correct arguments by another part of the system:

>>> real = SomeClass()
>>> real.method = MagicMock(name='method')
>>> real.method(3, 4, 5, key='value')

Once our mock has been used (

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
8 in this example) it has methods and attributes that allow you to make assertions about how it has been used.

Note

In most of these examples the and classes are interchangeable. As the

>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
0 is the more capable class it makes a sensible one to use by default.

Once the mock has been called its attribute is set to

>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
3. More importantly we can use the or method to check that it was called with the correct arguments.

This example tests that calling

>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
6 results in a call to the
>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
7 method:

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)

Mock for Method Calls on an Object

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

>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
8 below has a
>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
9 method. If it is called with an object then it calls
>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
0 on it.

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...

So to test it we need to pass in an object with a

>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
0 method and check that it was called correctly.

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()

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 will raise a failure exception.

Mocking Classes

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

>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
3 that instantiates
>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
4 and calls a method on it. The call to replaces the class
>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
4 with a mock. The
>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
4 instance is the result of calling the mock, so it is configured by modifying the mock .

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'

Naming your mocks

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:

>>> mock = MagicMock(name='foo')
>>> mock

>>> mock.method

Tracking all Calls

Often you want to track more than a single call to a method. The attribute records all calls to child attributes of the mock - and also to their children.

>>> mock = MagicMock()
>>> mock.method()

>>> mock.attribute.method(10, x=53)

>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]

If you make an assertion about

>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
9 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 object to construct lists for comparing with

>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
9:

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True

However, parameters to calls that return mocks are not recorded, which means it is not possible to track nested calls where the parameters used to create ancestors are important:

>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True

Setting Return Values and Attributes

Setting the return values on a mock object is trivially easy:

>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3

Of course you can do the same for methods on the mock:

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
0

The return value can also be set in the constructor:

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
1

If you need an attribute setting on your mock, just do it:

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
2

Sometimes you want to mock up a more complex situation, like for example

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
03. If we wanted this call to return a list, then we have to configure the result of the nested call.

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

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
3

It is the call to

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
05 that turns our call object into a list of calls representing the chained calls.

Raising exceptions with mocks

A useful attribute is . If you set this to an exception class or instance then the exception will be raised when the mock is called.

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
4

Side effect functions and iterables

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
06 can also be set to a function or an iterable. The use case for
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
06 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
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
06 to an iterable every call to the mock returns the next value from the iterable:

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
5

For more advanced use cases, like dynamically varying the return values depending on what the mock is called with,

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
06 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:

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
6

Mocking asynchronous iterators

Since Python 3.8,

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
11 and
>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
0 have support to mock through
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
13. The attribute of
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
13 can be used to set the return values to be used for iteration.

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
7

Mocking asynchronous context manager

Since Python 3.8,

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
11 and
>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
0 have support to mock through
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
18 and
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
19. By default,
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
18 and
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
19 are
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
11 instances that return an async function.

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
8

Creating a Mock from an Existing Object

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

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
23. In a test for another class, you provide a mock of this object that also provides
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
23. If later you refactor the first class, so that it no longer has
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
23 - then your tests will continue to pass even though your code is now broken!

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.

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
9

Using a specification also enables a smarter matching of calls made to the mock, regardless of whether some parameters were passed as positional or named arguments:

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
0

If you want this smarter matching to also work with method calls on the mock, you can use .

If you want a stronger form of specification that prevents the setting of arbitrary attributes as well as the getting of them then you can use spec_set instead of spec.

Patch Decorators

Note

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

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: , and .

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
31 takes a single string, of the form
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
32 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.

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
33:

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
1

If you are patching a module (including ) then use instead of :

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
2

The module name can be ‘dotted’, in the form

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
37 if needed:

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
3

A nice pattern is to actually decorate test methods themselves:

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
4

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

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
5

You can stack up multiple patch decorators using this pattern:

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
6

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

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
40 is passed in first.

There is also for setting values in a dictionary just during a scope and restoring the dictionary to its original state when the test ends:

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
7

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
31,
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
33 and
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
44 can all be used as context managers.

Where you use to create a mock for you, you can get a reference to the mock using the “as” form of the with statement:

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
8

As an alternative

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
31,
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
33 and
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
44 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”.

Further Examples

Here are some more examples for some slightly more advanced scenarios.

Mocking chained calls

Mocking chained calls is actually straightforward with mock once you understand the attribute. When a mock is called for the first time, or you fetch its

>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
8 before it has been called, a new 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

>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
8 mock:

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
9

From here it is a simple step to configure and then make assertions about chained calls. Of course another alternative is writing your code in a more testable way in the first place…

So, suppose we have some code that looks a little bit like this:

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()
0

Assuming that

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
53 is already well tested, how do we test
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
54? Specifically, we want to test that the code section
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
55 uses the response object in the correct way.

As this chain of calls is made from an instance attribute we can monkey patch the

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
56 attribute on a
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
57 instance. In this particular case we are only interested in the return value from the final call to
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
58 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 as its
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
60.

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

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
58 we could do this:

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()
1

We can do that in a slightly nicer way using the method to directly set the return value for us:

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()
2

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

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()
3

Using 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 = Mock()
>>> mock.return_value = 3
>>> mock()
3
9. We can use to create this list of calls for us:

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()
4

Partial mocking

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

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
68 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 is used here to mock out the

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
70 class in the module under test. The
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
06 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
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
06.

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()
5

Note that we don’t patch globally, we patch

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
70 in the module that uses it. See .

When

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
68 is called a known date is returned, but calls to the
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
76 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

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
77 attributes (
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
78 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.

Mocking a Generator Method

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

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 , so we can mock this using a .

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

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()
6

How would we mock this class, and in particular its “iter” method?

To configure the values returned from the iteration (implicit in the call to ), we need to configure the object returned by the call to

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
83.

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()
7

There are also generator expressions and more advanced uses of generators, but we aren’t concerned about them here. A very good introduction to generators and how powerful they are is: Generator Tricks for Systems Programmers.

Applying the same patch to every test method

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. Instead, you can use (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

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
85:

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()
8

An alternative way of managing patches is to use the . These allow you to move the patching into your

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
86 and
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
87 methods.

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()
9

If you use this technique you must ensure that the patching is “undone” by calling

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
88. This can be fiddlier than you might think, because if an exception is raised in the setUp then tearDown is not called. makes this easier:

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'
0

Mocking Unbound Methods

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 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

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
91 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
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
92 passed in as the first argument, which is exactly what I wanted:

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'
1

If we don’t use

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
91 then the unbound method is patched out with a Mock instance instead, and isn’t called with
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
92.

Checking multiple calls with mock

mock has a nice API for making assertions about how your mock objects are used.

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'
2

If your mock is only being called once you can use the

>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
5 method that also asserts that the
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
78 is one.

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'
3

Both

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
97 and
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
98 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 :

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'
4

The helper makes it easy to make assertions about these calls. You can build up a list of expected calls and compare it to

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
99. This looks remarkably similar to the repr of the
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
99:

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'
5

Coping with mutable arguments

Another situation is rare, but can bite you, is when your mock is called with mutable arguments.

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
03 and
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
99 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’:

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'
6

When we try to test that

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
05 calls
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
06 with the correct argument look what happens:

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'
7

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

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
06 functionality. If you provide a
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
06 function for a mock then
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
06 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.

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'
8

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
10 is called with the mock that will be called. It returns a new mock that we do the assertion on. The
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
06 function makes a copy of the args and calls our
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
12 with the copy.

Note

If your mock is only going to be used once there is an easier way of checking arguments at the point they are called. You can simply do the checking inside a

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
06 function.

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'
9

An alternative approach is to create a subclass of or that copies (using ) the arguments. Here’s an example implementation:

>>> mock = MagicMock(name='foo')
>>> mock

>>> mock.method

0

When you subclass

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
7 or
>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
0 all dynamically created attributes, and the
>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
8 will use your subclass automatically. That means all children of a
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
20 will also have the type
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
20.

Nesting Patches

Using patch as a context manager is nice, but if you do multiple patches you can end up with nested with statements indenting further and further to the right:

>>> mock = MagicMock(name='foo')
>>> mock

>>> mock.method

1

With unittest

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
22 functions and the we can achieve the same effect without the nested indentation. A simple helper method,
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
23, puts the patch in place and returns the created mock for us:

>>> mock = MagicMock(name='foo')
>>> mock

>>> mock.method

2

Mocking a dictionary with MagicMock

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 , which will behave like a dictionary, and using to delegate dictionary access to a real underlying dictionary that is under our control.

When the

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
26 and
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
27 methods of our
>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
0 are called (normal dictionary access) then
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
06 is called with the key (and in the case of
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
30 the value too). We can also control what is returned.

After the

>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
0 has been used we can use attributes like to assert about how the dictionary was used:

>>> mock = MagicMock(name='foo')
>>> mock

>>> mock.method

3

Note

An alternative to using

>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
0 is to use
>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
7 and only provide the magic methods you specifically want:

>>> mock = MagicMock(name='foo')
>>> mock

>>> mock.method

4

A third option is to use

>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
0 but passing in
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
36 as the spec (or spec_set) argument so that the
>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
0 created only has dictionary magic methods available:

>>> mock = MagicMock(name='foo')
>>> mock

>>> mock.method

5

With these side effect functions in place, the

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
38 will behave like a normal dictionary but recording the access. It even raises a if you try to access a key that doesn’t exist.

>>> mock = MagicMock(name='foo')
>>> mock

>>> mock.method

6

After it has been used you can make assertions about the access using the normal mock methods and attributes:

>>> mock = MagicMock(name='foo')
>>> mock

>>> mock.method

7

Mock subclasses and their attributes

There are various reasons why you might want to subclass . One reason might be to add helper methods. Here’s a silly example:

>>> mock = MagicMock(name='foo')
>>> mock

>>> mock.method

8

The standard behaviour for

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
7 instances is that attributes and the return value mocks are of the same type as the mock they are accessed on. This ensures that
>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
7 attributes are
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
43 and
>>> m = Mock()
>>> m.factory(important=True).deliver()

>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
0 attributes are
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
45 . 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.

>>> mock = MagicMock(name='foo')
>>> mock

>>> mock.method

9

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.

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
7 (in all its flavours) uses a method called
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
47 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 (
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
48) which are then passed onto the mock constructor:

>>> mock = MagicMock()
>>> mock.method()

>>> mock.attribute.method(10, x=53)

>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
0

An exception to this rule are the non-callable mocks. Attributes use the callable variant because otherwise non-callable mocks couldn’t have callable methods.

Mocking imports with patch.dict

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

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
38 to affect the results of an import. Importing fetches an object from the 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
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
50, so usually when you import something you get a module back. This need not be the case however.

This means you can use to temporarily put a mock in place in . 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

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
54 is called) then whatever was there previously will be restored safely.

Here’s an example that mocks out the ‘fooble’ module.

>>> mock = MagicMock()
>>> mock.method()

>>> mock.attribute.method(10, x=53)

>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
1

As you can see the

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
55 succeeds, but on exit there is no ‘fooble’ left in .

This also works for the

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
57 form:

>>> mock = MagicMock()
>>> mock.method()

>>> mock.attribute.method(10, x=53)

>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
2

With slightly more work you can also mock package imports:

>>> mock = MagicMock()
>>> mock.method()

>>> mock.attribute.method(10, x=53)

>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
3

Tracking order of calls and less verbose call assertions

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

Because mocks track calls to child mocks in

>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
9, 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 = Mock()
>>> mock.return_value = 3
>>> mock()
3
9 of the parent:

>>> mock = MagicMock()
>>> mock.method()

>>> mock.attribute.method(10, x=53)

>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
4

>>> mock = MagicMock()
>>> mock.method()

>>> mock.attribute.method(10, x=53)

>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
5

>>> mock = MagicMock()
>>> mock.method()

>>> mock.attribute.method(10, x=53)

>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
6

We can then assert about the calls, including the order, by comparing with the

>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
9 attribute on the manager mock:

>>> mock = MagicMock()
>>> mock.method()

>>> mock.attribute.method(10, x=53)

>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
7

If

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
31 is creating, and putting in place, your mocks then you can attach them to a manager mock using the method. After attaching calls will be recorded in
>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
9 of the manager.

>>> mock = MagicMock()
>>> mock.method()

>>> mock.attribute.method(10, x=53)

>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
8

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

>>> mock = MagicMock()
>>> mock.method()

>>> mock.attribute.method(10, x=53)

>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
9

Even though the chained call

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
70 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

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
71 to
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
72:

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
0

More complex argument matching

Using the same basic concept as 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 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

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
97 isn’t sufficient:

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
1

A comparison function for our

>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
4 class might look something like this:

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
2

And a matcher object that can use comparison functions like this for its equality operation would look something like this:

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
3

Putting all this together:

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
4

The

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
77 is instantiated with our compare function and the
>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
4 object we want to compare against. In
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
97 the
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
77 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
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
97 passes, and if they don’t an is raised:

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
5

With a bit of tweaking you could have the comparison function raise the directly and provide a more useful failure message.

As of version 1.5, the Python testing library PyHamcrest provides similar functionality, that may be useful here, in the form of its equality matcher ().