unittest.mock 上手指南

3.3 新版功能.

使用 mock

模拟方法调用

使用 Mock 的常见场景:

  • 模拟函数调用

  • 记录“对象上的方法调用”

你可能需要替换一个对象上的方法,用于确认此方法被系统中的其他部分调用过,并且调用时使用了正确的参数。

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

使用了 mock(本例中的 real.method)之后,它有方法和属性可以让你针对它是被如何使用的下断言。

注解

在多数示例中,MockMagicMock 两个类可以相互替换,而 MagicMock 是一个更适用的类,通常情况下,使用它就可以了。

如果 mock 被调用,它的 called 属性就会变成 True,更重要的是,我们可以使用 assert_called_with() 或者 assert_called_once_with() 方法来确认它在被调用时使用了正确的参数。

在如下的测试示例中,验证对于 ProductionClass().method 的调用会导致 something 的调用。

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

对象上的方法调用的 mock

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

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

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

So to test it we need to pass in an object with a close method and checkthat it was called correctly.

  1. >>> real = ProductionClass()
  2. >>> mock = Mock()
  3. >>> real.closer(mock)
  4. >>> 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 thenaccessing it in the test will create it, but assert_called_with()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. Instancesare 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 Fooand calls a method on it. The call to patch() replaces the class Foo with amock. The Foo instance is the result of calling the mock, so it is configuredby modifying the mock return_value.

  1. >>> def some_function():
  2. ... instance = module.Foo()
  3. ... return instance.method()
  4. ...
  5. >>> with patch('module.Foo') as mock:
  6. ... instance = mock.return_value
  7. ... instance.method.return_value = 'the result'
  8. ... result = some_function()
  9. ... assert result == 'the result'

Naming your mocks

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

  1. >>> mock = MagicMock(name='foo')
  2. >>> mock
  3. <MagicMock name='foo' id='...'>
  4. >>> mock.method
  5. <MagicMock name='foo.method' id='...'>

Tracking all Calls

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

  1. >>> mock = MagicMock()
  2. >>> mock.method()
  3. <MagicMock name='mock.method()' id='...'>
  4. >>> mock.attribute.method(10, x=53)
  5. <MagicMock name='mock.attribute.method()' id='...'>
  6. >>> mock.mock_calls
  7. [call.method(), call.attribute.method(10, x=53)]

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

You use the call object to construct lists for comparing withmock_calls:

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

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

  1. >>> m = Mock()
  2. >>> m.factory(important=True).deliver()
  3. <Mock name='mock.factory().deliver()' id='...'>
  4. >>> m.mock_calls[-1] == call.factory(important=False).deliver()
  5. True

Setting Return Values and Attributes

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

  1. >>> mock = Mock()
  2. >>> mock.return_value = 3
  3. >>> mock()
  4. 3

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

  1. >>> mock = Mock()
  2. >>> mock.method.return_value = 3
  3. >>> mock.method()
  4. 3

The return value can also be set in the constructor:

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

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

  1. >>> mock = Mock()
  2. >>> mock.x = 3
  3. >>> mock.x
  4. 3

Sometimes you want to mock up a more complex situation, like for examplemock.connection.cursor().execute("SELECT 1"). If we wanted this call toreturn 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" likethis for easy assertion afterwards:

  1. >>> mock = Mock()
  2. >>> cursor = mock.connection.cursor.return_value
  3. >>> cursor.execute.return_value = ['foo']
  4. >>> mock.connection.cursor().execute("SELECT 1")
  5. ['foo']
  6. >>> expected = call.connection.cursor().execute("SELECT 1").call_list()
  7. >>> mock.mock_calls
  8. [call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]
  9. >>> mock.mock_calls == expected
  10. True

It is the call to .call_list() that turns our call object into a list ofcalls representing the chained calls.

Raising exceptions with mocks

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

  1. >>> mock = Mock(side_effect=Exception('Boom!'))
  2. >>> mock()
  3. Traceback (most recent call last):
  4. ...
  5. Exception: Boom!

Side effect functions and iterables

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

  1. >>> mock = MagicMock(side_effect=[4, 5, 6])
  2. >>> mock()
  3. 4
  4. >>> mock()
  5. 5
  6. >>> mock()
  7. 6

For more advanced use cases, like dynamically varying the return valuesdepending 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 thefunction returns is what the call returns:

  1. >>> vals = {(1, 2): 1, (2, 3): 2}
  2. >>> def side_effect(*args):
  3. ... return vals[args]
  4. ...
  5. >>> mock = MagicMock(side_effect=side_effect)
  6. >>> mock(1, 2)
  7. 1
  8. >>> mock(2, 3)
  9. 2

Creating a Mock from an Existing Object

One problem with over use of mocking is that it couples your tests to theimplementation of your mocks rather than your real code. Suppose you have aclass that implements somemethod. In a test for another class, youprovide a mock of this object that _also provides some_method. If lateryou refactor the first class, so that it no longer has some_method - thenyour 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 themock that don't exist on your specification object will immediately raise anattribute error. If you change the implementation of your specification, thentests that use that class will start failing immediately without you having toinstantiate the class in those tests.

  1. >>> mock = Mock(spec=SomeClass)
  2. >>> mock.old_method()
  3. Traceback (most recent call last):
  4. ...
  5. AttributeError: object has no attribute 'old_method'

Using a specification also enables a smarter matching of calls made to themock, regardless of whether some parameters were passed as positional ornamed arguments:

  1. >>> def f(a, b, c): pass
  2. ...
  3. >>> mock = Mock(spec=f)
  4. >>> mock(1, 2, 3)
  5. <Mock name='mock()' id='140161580456576'>
  6. >>> mock.assert_called_with(a=1, b=2, c=3)

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

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

Patch Decorators

注解

With patch() it matters that you patch objects in the namespace wherethey are looked up. This is normally straightforward, but for a quick guideread 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 itis instantiated. Modules and classes are effectively global, so patching onthem has to be undone after the test or the patch will persist into othertests and cause hard to diagnose problems.

mock provides three convenient decorators for this: patch(), patch.object() andpatch.dict(). patch takes a single string, of the formpackage.module.Class.attribute to specify the attribute you are patching. Italso optionally takes a value that you want the attribute (or class orwhatever) to be replaced with. 'patch.object' takes an object and the name ofthe attribute you would like patched, plus optionally the value to patch itwith.

patch.object:

  1. >>> original = SomeClass.attribute
  2. >>> @patch.object(SomeClass, 'attribute', sentinel.attribute)
  3. ... def test():
  4. ... assert SomeClass.attribute == sentinel.attribute
  5. ...
  6. >>> test()
  7. >>> assert SomeClass.attribute == original
  1. >>> @patch('package.module.attribute', sentinel.attribute)
  2. ... def test():
  3. ... from package.module import attribute
  4. ... assert attribute is sentinel.attribute
  5. ...
  6. >>> test()

If you are patching a module (including builtins) then use patch()instead of patch.object():

  1. >>> mock = MagicMock(return_value=sentinel.file_handle)
  2. >>> with patch('builtins.open', mock):
  3. ... handle = open('filename', 'r')
  4. ...
  5. >>> mock.assert_called_with('filename', 'r')
  6. >>> assert handle == sentinel.file_handle, "incorrect file handle returned"

The module name can be 'dotted', in the form package.module if needed:

  1. >>> @patch('package.module.ClassName.attribute', sentinel.attribute)
  2. ... def test():
  3. ... from package.module import ClassName
  4. ... assert ClassName.attribute == sentinel.attribute
  5. ...
  6. >>> test()

A nice pattern is to actually decorate test methods themselves:

  1. >>> class MyTest(unittest.TestCase):
  2. ... @patch.object(SomeClass, 'attribute', sentinel.attribute)
  3. ... def test_something(self):
  4. ... self.assertEqual(SomeClass.attribute, sentinel.attribute)
  5. ...
  6. >>> original = SomeClass.attribute
  7. >>> MyTest('test_something').test_something()
  8. >>> assert SomeClass.attribute == original

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

  1. >>> class MyTest(unittest.TestCase):
  2. ... @patch.object(SomeClass, 'static_method')
  3. ... def test_something(self, mock_method):
  4. ... SomeClass.static_method()
  5. ... mock_method.assert_called_with()
  6. ...
  7. >>> MyTest('test_something').test_something()

You can stack up multiple patch decorators using this pattern:

  1. >>> class MyTest(unittest.TestCase):
  2. ... @patch('package.module.ClassName1')
  3. ... @patch('package.module.ClassName2')
  4. ... def test_something(self, MockClass2, MockClass1):
  5. ... self.assertIs(package.module.ClassName1, MockClass1)
  6. ... self.assertIs(package.module.ClassName2, MockClass2)
  7. ...
  8. >>> MyTest('test_something').test_something()

When you nest patch decorators the mocks are passed in to the decoratedfunction in the same order they applied (the normal Python order thatdecorators are applied). This means from the bottom up, so in the exampleabove the mock for test_module.ClassName2 is passed in first.

There is also patch.dict() for setting values in a dictionary justduring a scope and restoring the dictionary to its original state when the testends:

  1. >>> foo = {'key': 'value'}
  2. >>> original = foo.copy()
  3. >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
  4. ... assert foo == {'newkey': 'newvalue'}
  5. ...
  6. >>> assert foo == original

patch, patch.object and patch.dict can all be used as context managers.

Where you use patch() to create a mock for you, you can get a reference to themock using the "as" form of the with statement:

  1. >>> class ProductionClass:
  2. ... def method(self):
  3. ... pass
  4. ...
  5. >>> with patch.object(ProductionClass, 'method') as mock_method:
  6. ... mock_method.return_value = None
  7. ... real = ProductionClass()
  8. ... real.method(1, 2, 3)
  9. ...
  10. >>> mock_method.assert_called_with(1, 2, 3)

As an alternative patch, patch.object and patch.dict can be used asclass decorators. When used in this way it is the same as applying thedecorator 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 youunderstand the return_value attribute. When a mock is called forthe first time, or you fetch its return_value before it has been called, anew Mock is created.

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

  1. >>> mock = Mock()
  2. >>> mock().foo(a=2, b=3)
  3. <Mock name='mock().foo()' id='...'>
  4. >>> mock.return_value.foo.assert_called_with(a=2, b=3)

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

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

  1. >>> class Something:
  2. ... def __init__(self):
  3. ... self.backend = BackendProvider()
  4. ... def method(self):
  5. ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
  6. ... # more code

Assuming that BackendProvider is already well tested, how do we testmethod()? 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 patchthe backend attribute on a Something instance. In this particular casewe are only interested in the return value from the final call tostart_call so we don't have much configuration to do. Let's assume theobject it returns is 'file-like', so we'll ensure that our response objectuses the builtin open() as its spec.

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

  1. mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response

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

  1. >>> something = Something()
  2. >>> mock_response = Mock(spec=open)
  3. >>> mock_backend = Mock()
  4. >>> config = {'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response}
  5. >>> mock_backend.configure_mock(**config)

With these we monkey patch the "mock backend" in place and can make the realcall:

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

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

  1. >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
  2. >>> call_list = chained.call_list()
  3. >>> assert mock_backend.mock_calls == call_list

Partial mocking

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 fromcreating new date objects. Unfortunately datetime.date is written in C, andso 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 dateclass with a mock, but passing through calls to the constructor to the realclass (and returning real instances).

The patch decorator is used here tomock out the date class in the module under test. The side_effectattribute on the mock date class is then set to a lambda function that returnsa real date. When the mock date class is called a real date will beconstructed and returned by side_effect.

  1. >>> from datetime import date
  2. >>> with patch('mymodule.date') as mock_date:
  3. ... mock_date.today.return_value = date(2010, 10, 8)
  4. ... mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
  5. ...
  6. ... assert mymodule.date.today() == date(2010, 10, 8)
  7. ... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
  8. ...

Note that we don't patch datetime.date globally, we patch date in themodule that uses it. See where to patch.

When date.today() is called a known date is returned, but calls to thedate(…) constructor still return normal dates. Without this you can findyourself having to calculate an expected result using exactly the samealgorithm 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.

Mocking a Generator Method

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

A generator method / function is called to return the generator object. It isthe generator object that is then iterated over. The protocol method foriteration is iter(), so we canmock this using a MagicMock.

Here's an example class with an "iter" method implemented as a generator:

  1. >>> class Foo:
  2. ... def iter(self):
  3. ... for i in [1, 2, 3]:
  4. ... yield i
  5. ...
  6. >>> foo = Foo()
  7. >>> list(foo.iter())
  8. [1, 2, 3]

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

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

  1. >>> mock_foo = MagicMock()
  2. >>> mock_foo.iter.return_value = iter([1, 2, 3])
  3. >>> list(mock_foo.iter())
  4. [1, 2, 3]

Applying the same patch to every test method

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

  1. >>> @patch('mymodule.SomeClass')
  2. ... class MyTest(TestCase):
  3. ...
  4. ... def test_one(self, MockSomeClass):
  5. ... self.assertIs(mymodule.SomeClass, MockSomeClass)
  6. ...
  7. ... def test_two(self, MockSomeClass):
  8. ... self.assertIs(mymodule.SomeClass, MockSomeClass)
  9. ...
  10. ... def not_a_test(self):
  11. ... return 'something'
  12. ...
  13. >>> MyTest('test_one').test_one()
  14. >>> MyTest('test_two').test_two()
  15. >>> MyTest('test_two').not_a_test()
  16. 'something'

An alternative way of managing patches is to use the patch methods: start and stop.These allow you to move the patching into your setUp and tearDown methods.

  1. >>> class MyTest(TestCase):
  2. ... def setUp(self):
  3. ... self.patcher = patch('mymodule.foo')
  4. ... self.mock_foo = self.patcher.start()
  5. ...
  6. ... def test_foo(self):
  7. ... self.assertIs(mymodule.foo, self.mock_foo)
  8. ...
  9. ... def tearDown(self):
  10. ... self.patcher.stop()
  11. ...
  12. >>> MyTest('test_foo').run()

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

  1. >>> class MyTest(TestCase):
  2. ... def setUp(self):
  3. ... patcher = patch('mymodule.foo')
  4. ... self.addCleanup(patcher.stop)
  5. ... self.mock_foo = patcher.start()
  6. ...
  7. ... def test_foo(self):
  8. ... self.assertIs(mymodule.foo, self.mock_foo)
  9. ...
  10. >>> MyTest('test_foo').run()

Mocking Unbound Methods

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

If you pass autospec=True to patch then it does the patching with areal function object. This function object has the same signature as the oneit is replacing, but delegates to a mock under the hood. You still get yourmock auto-created in exactly the same way as before. What it means though, isthat if you use it to patch out an unbound method on a class the mockedfunction 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 Iwanted:

  1. >>> class Foo:
  2. ... def foo(self):
  3. ... pass
  4. ...
  5. >>> with patch.object(Foo, 'foo', autospec=True) as mock_foo:
  6. ... mock_foo.return_value = 'foo'
  7. ... foo = Foo()
  8. ... foo.foo()
  9. ...
  10. 'foo'
  11. >>> mock_foo.assert_called_once_with(foo)

If we don't use autospec=True then the unbound method is patched outwith a Mock instance instead, and isn't called with self.

Checking multiple calls with mock

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

  1. >>> mock = Mock()
  2. >>> mock.foo_bar.return_value = None
  3. >>> mock.foo_bar('baz', spam='eggs')
  4. >>> mock.foo_bar.assert_called_with('baz', spam='eggs')

If your mock is only being called once you can use theassert_called_once_with() method that also asserts that thecall_count is one.

  1. >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
  2. >>> mock.foo_bar()
  3. >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
  4. Traceback (most recent call last):
  5. ...
  6. AssertionError: Expected to be called once. Called 2 times.

Both assertcalled_with and assert_called_once_with make assertions aboutthe _most recent call. If your mock is going to be called several times, andyou want to make assertions about all those calls you can usecall_args_list:

  1. >>> mock = Mock(return_value=None)
  2. >>> mock(1, 2, 3)
  3. >>> mock(4, 5, 6)
  4. >>> mock()
  5. >>> mock.call_args_list
  6. [call(1, 2, 3), call(4, 5, 6), call()]

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

  1. >>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
  2. >>> mock.call_args_list == expected
  3. True

Coping with mutable arguments

Another situation is rare, but can bite you, is when your mock is called withmutable arguments. callargs and call_args_list store _references to thearguments. If the arguments are mutated by the code under test then you can nolonger make assertions about what the values were when the mock was called.

Here's some example code that shows the problem. Imagine the following functionsdefined in 'mymodule':

  1. def frob(val):
  2. pass
  3.  
  4. def grob(val):
  5. "First frob and then clear val"
  6. frob(val)
  7. val.clear()

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

  1. >>> with patch('mymodule.frob') as mock_frob:
  2. ... val = {6}
  3. ... mymodule.grob(val)
  4. ...
  5. >>> val
  6. set()
  7. >>> mock_frob.assert_called_with({6})
  8. Traceback (most recent call last):
  9. ...
  10. AssertionError: Expected: (({6},), {})
  11. Called with: ((set(),), {})

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

Here's one solution that uses the sideeffectfunctionality. If you provide a side_effect function for a mock thenside_effect will be called with the same args as the mock. This gives us anopportunity to copy the arguments and store them for later assertions. In thisexample I'm using _another mock to store the arguments so that I can use themock methods for doing the assertion. Again a helper function sets this up forme.

  1. >>> from copy import deepcopy
  2. >>> from unittest.mock import Mock, patch, DEFAULT
  3. >>> def copy_call_args(mock):
  4. ... new_mock = Mock()
  5. ... def side_effect(*args, **kwargs):
  6. ... args = deepcopy(args)
  7. ... kwargs = deepcopy(kwargs)
  8. ... new_mock(*args, **kwargs)
  9. ... return DEFAULT
  10. ... mock.side_effect = side_effect
  11. ... return new_mock
  12. ...
  13. >>> with patch('mymodule.frob') as mock_frob:
  14. ... new_mock = copy_call_args(mock_frob)
  15. ... val = {6}
  16. ... mymodule.grob(val)
  17. ...
  18. >>> new_mock.assert_called_with({6})
  19. >>> new_mock.call_args
  20. call({6})

copy_call_args is called with the mock that will be called. It returns a newmock that we do the assertion on. The side_effect function makes a copy ofthe args and calls our new_mock with the copy.

注解

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

  1. >>> def side_effect(arg):
  2. ... assert arg == {6}
  3. ...
  4. >>> mock = Mock(side_effect=side_effect)
  5. >>> mock({6})
  6. >>> mock(set())
  7. Traceback (most recent call last):
  8. ...
  9. AssertionError

An alternative approach is to create a subclass of Mock orMagicMock that copies (using copy.deepcopy()) the arguments.Here's an example implementation:

  1. >>> from copy import deepcopy
  2. >>> class CopyingMock(MagicMock):
  3. ... def __call__(self, *args, **kwargs):
  4. ... args = deepcopy(args)
  5. ... kwargs = deepcopy(kwargs)
  6. ... return super(CopyingMock, self).__call__(*args, **kwargs)
  7. ...
  8. >>> c = CopyingMock(return_value=None)
  9. >>> arg = set()
  10. >>> c(arg)
  11. >>> arg.add(1)
  12. >>> c.assert_called_with(set())
  13. >>> c.assert_called_with(arg)
  14. Traceback (most recent call last):
  15. ...
  16. AssertionError: Expected call: mock({1})
  17. Actual call: mock(set())
  18. >>> c.foo
  19. <CopyingMock name='mock.foo' id='...'>

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

Nesting Patches

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

  1. >>> class MyTest(TestCase):
  2. ...
  3. ... def test_foo(self):
  4. ... with patch('mymodule.Foo') as mock_foo:
  5. ... with patch('mymodule.Bar') as mock_bar:
  6. ... with patch('mymodule.Spam') as mock_spam:
  7. ... assert mymodule.Foo is mock_foo
  8. ... assert mymodule.Bar is mock_bar
  9. ... assert mymodule.Spam is mock_spam
  10. ...
  11. >>> original = mymodule.Foo
  12. >>> MyTest('test_foo').test_foo()
  13. >>> assert mymodule.Foo is original

With unittest cleanup functions and the patch methods: start and stop we canachieve the same effect without the nested indentation. A simple helpermethod, create_patch, puts the patch in place and returns the created mockfor us:

  1. >>> class MyTest(TestCase):
  2. ...
  3. ... def create_patch(self, name):
  4. ... patcher = patch(name)
  5. ... thing = patcher.start()
  6. ... self.addCleanup(patcher.stop)
  7. ... return thing
  8. ...
  9. ... def test_foo(self):
  10. ... mock_foo = self.create_patch('mymodule.Foo')
  11. ... mock_bar = self.create_patch('mymodule.Bar')
  12. ... mock_spam = self.create_patch('mymodule.Spam')
  13. ...
  14. ... assert mymodule.Foo is mock_foo
  15. ... assert mymodule.Bar is mock_bar
  16. ... assert mymodule.Spam is mock_spam
  17. ...
  18. >>> original = mymodule.Foo
  19. >>> MyTest('test_foo').run()
  20. >>> assert mymodule.Foo is original

Mocking a dictionary with MagicMock

You may want to mock a dictionary, or other container object, recording allaccess 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 realunderlying dictionary that is under our control.

When the getitem() and setitem() methods of our MagicMock are called(normal dictionary access) then sideeffect is called with the key (and inthe case of _setitem the value too). We can also control what is returned.

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

  1. >>> my_dict = {'a': 1, 'b': 2, 'c': 3}
  2. >>> def getitem(name):
  3. ... return my_dict[name]
  4. ...
  5. >>> def setitem(name, val):
  6. ... my_dict[name] = val
  7. ...
  8. >>> mock = MagicMock()
  9. >>> mock.__getitem__.side_effect = getitem
  10. >>> mock.__setitem__.side_effect = setitem

注解

An alternative to using MagicMock is to use Mock and only providethe magic methods you specifically want:

  1. >>> mock = Mock()
  2. >>> mock.__getitem__ = Mock(side_effect=getitem)
  3. >>> mock.__setitem__ = Mock(side_effect=setitem)

A third option is to use MagicMock but passing in dict as the spec(or spec_set) argument so that the MagicMock created only hasdictionary magic methods available:

  1. >>> mock = MagicMock(spec_set=dict)
  2. >>> mock.__getitem__.side_effect = getitem
  3. >>> mock.__setitem__.side_effect = setitem

With these side effect functions in place, the mock will behave like a normaldictionary but recording the access. It even raises a KeyError if you tryto access a key that doesn't exist.

  1. >>> mock['a']
  2. 1
  3. >>> mock['c']
  4. 3
  5. >>> mock['d']
  6. Traceback (most recent call last):
  7. ...
  8. KeyError: 'd'
  9. >>> mock['b'] = 'fish'
  10. >>> mock['d'] = 'eggs'
  11. >>> mock['b']
  12. 'fish'
  13. >>> mock['d']
  14. 'eggs'

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

  1. >>> mock.__getitem__.call_args_list
  2. [call('a'), call('c'), call('d'), call('b'), call('d')]
  3. >>> mock.__setitem__.call_args_list
  4. [call('b', 'fish'), call('d', 'eggs')]
  5. >>> my_dict
  6. {'a': 1, 'c': 3, 'b': 'fish', 'd': 'eggs'}

Mock subclasses and their attributes

There are various reasons why you might want to subclass Mock. Onereason might be to add helper methods. Here's a silly example:

  1. >>> class MyMock(MagicMock):
  2. ... def has_been_called(self):
  3. ... return self.called
  4. ...
  5. >>> mymock = MyMock(return_value=None)
  6. >>> mymock
  7. <MyMock id='...'>
  8. >>> mymock.has_been_called()
  9. False
  10. >>> mymock()
  11. >>> mymock.has_been_called()
  12. True

The standard behaviour for Mock instances is that attributes and the returnvalue mocks are of the same type as the mock they are accessed on. This ensuresthat Mock attributes are Mocks and MagicMock attributes are MagicMocks2. So if you're subclassing to add helper methods then they'll also beavailable on the attributes and return value mock of instances of yoursubclass.

  1. >>> mymock.foo
  2. <MyMock name='mock.foo' id='...'>
  3. >>> mymock.foo.has_been_called()
  4. False
  5. >>> mymock.foo()
  6. <MyMock name='mock.foo()' id='...'>
  7. >>> mymock.foo.has_been_called()
  8. True

Sometimes this is inconvenient. For example, one user is subclassing mock tocreated 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 createthese "sub-mocks" for attributes and return values. You can prevent yoursubclass being used for attributes by overriding this method. The signature isthat it takes arbitrary keyword arguments (**kwargs) which are then passedonto the mock constructor:

  1. >>> class Subclass(MagicMock):
  2. ... def _get_child_mock(self, **kwargs):
  3. ... return MagicMock(**kwargs)
  4. ...
  5. >>> mymock = Subclass()
  6. >>> mymock.foo
  7. <MagicMock name='mock.foo' id='...'>
  8. >>> assert isinstance(mymock, Subclass)
  9. >>> assert not isinstance(mymock.foo, Subclass)
  10. >>> assert not isinstance(mymock(), Subclass)
  • 2
  • An exception to this rule are the non-callable mocks. Attributes use thecallable variant because otherwise non-callable mocks couldn't have callablemethods.

Mocking imports with patch.dict

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

Generally local imports are to be avoided. They are sometimes done to preventcircular dependencies, for which there is usually a much better way to solvethe problem (refactor the code) or to prevent "up front costs" by delaying theimport. This can also be solved in better ways than an unconditional localimport (store the module as a class or module attribute and only do the importon 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 itfetches an object, which need not be a module. Importing a module for thefirst time results in a module object being put in sys.modules, so usuallywhen you import something you get a module back. This need not be the casehowever.

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

Here's an example that mocks out the 'fooble' module.

  1. >>> mock = Mock()
  2. >>> with patch.dict('sys.modules', {'fooble': mock}):
  3. ... import fooble
  4. ... fooble.blob()
  5. ...
  6. <Mock name='mock.blob()' id='...'>
  7. >>> assert 'fooble' not in sys.modules
  8. >>> mock.blob.assert_called_once_with()

As you can see the import fooble succeeds, but on exit there is no 'fooble'left in sys.modules.

This also works for the from module import name form:

  1. >>> mock = Mock()
  2. >>> with patch.dict('sys.modules', {'fooble': mock}):
  3. ... from fooble import blob
  4. ... blob.blip()
  5. ...
  6. <Mock name='mock.blob.blip()' id='...'>
  7. >>> mock.blob.blip.assert_called_once_with()

With slightly more work you can also mock package imports:

  1. >>> mock = Mock()
  2. >>> modules = {'package': mock, 'package.module': mock.module}
  3. >>> with patch.dict('sys.modules', modules):
  4. ... from package.module import fooble
  5. ... fooble()
  6. ...
  7. <Mock name='mock.module.fooble()' id='...'>
  8. >>> mock.module.fooble.assert_called_once_with()

Tracking order of calls and less verbose call assertions

The Mock class allows you to track the order of method calls onyour mock objects through the method_calls attribute. Thisdoesn'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 anarbitrary attribute of a mock creates a child mock, we can create our separatemocks from a parent one. Calls to those child mock will then all be recorded,in order, in the mock_calls of the parent:

  1. >>> manager = Mock()
  2. >>> mock_foo = manager.foo
  3. >>> mock_bar = manager.bar
  1. >>> mock_foo.something()
  2. <Mock name='mock.foo.something()' id='...'>
  3. >>> mock_bar.other.thing()
  4. <Mock name='mock.bar.other.thing()' id='...'>
  1. >>> manager.mock_calls
  2. [call.foo.something(), call.bar.other.thing()]

We can then assert about the calls, including the order, by comparing withthe mock_calls attribute on the manager mock:

  1. >>> expected_calls = [call.foo.something(), call.bar.other.thing()]
  2. >>> manager.mock_calls == expected_calls
  3. True

If patch is creating, and putting in place, your mocks then you can attachthem to a manager mock using the attach_mock() method. Afterattaching calls will be recorded in mock_calls of the manager.

  1. >>> manager = MagicMock()
  2. >>> with patch('mymodule.Class1') as MockClass1:
  3. ... with patch('mymodule.Class2') as MockClass2:
  4. ... manager.attach_mock(MockClass1, 'MockClass1')
  5. ... manager.attach_mock(MockClass2, 'MockClass2')
  6. ... MockClass1().foo()
  7. ... MockClass2().bar()
  8. ...
  9. <MagicMock name='mock.MockClass1().foo()' id='...'>
  10. <MagicMock name='mock.MockClass2().bar()' id='...'>
  11. >>> manager.mock_calls
  12. [call.MockClass1(),
  13. call.MockClass1().foo(),
  14. call.MockClass2(),
  15. call.MockClass2().bar()]

If many calls have been made, but you're only interested in a particularsequence of them then an alternative is to use theassert_has_calls() method. This takes a list of calls (constructedwith the call object). If that sequence of calls are inmock_calls then the assert succeeds.

  1. >>> m = MagicMock()
  2. >>> m().foo().bar().baz()
  3. <MagicMock name='mock().foo().bar().baz()' id='...'>
  4. >>> m.one().two().three()
  5. <MagicMock name='mock.one().two().three()' id='...'>
  6. >>> calls = call.one().two().three().call_list()
  7. >>> m.assert_has_calls(calls)

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

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

  1. >>> m = MagicMock()
  2. >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
  3. (...)
  4. >>> calls = [call.fifty('50'), call(1), call.seven(7)]
  5. >>> m.assert_has_calls(calls, any_order=True)

More complex argument matching

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

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

You can see in this example how a 'standard' call to assert_called_with isn'tsufficient:

  1. >>> class Foo:
  2. ... def __init__(self, a, b):
  3. ... self.a, self.b = a, b
  4. ...
  5. >>> mock = Mock(return_value=None)
  6. >>> mock(Foo(1, 2))
  7. >>> mock.assert_called_with(Foo(1, 2))
  8. Traceback (most recent call last):
  9. ...
  10. AssertionError: Expected: call(<__main__.Foo object at 0x...>)
  11. Actual call: call(<__main__.Foo object at 0x...>)

A comparison function for our Foo class might look something like this:

  1. >>> def compare(self, other):
  2. ... if not type(self) == type(other):
  3. ... return False
  4. ... if self.a != other.a:
  5. ... return False
  6. ... if self.b != other.b:
  7. ... return False
  8. ... return True
  9. ...

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

  1. >>> class Matcher:
  2. ... def __init__(self, compare, some_obj):
  3. ... self.compare = compare
  4. ... self.some_obj = some_obj
  5. ... def __eq__(self, other):
  6. ... return self.compare(self.some_obj, other)
  7. ...

Putting all this together:

  1. >>> match_foo = Matcher(compare, Foo(1, 2))
  2. >>> mock.assert_called_with(match_foo)

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

  1. >>> match_wrong = Matcher(compare, Foo(3, 4))
  2. >>> mock.assert_called_with(match_wrong)
  3. Traceback (most recent call last):
  4. ...
  5. AssertionError: Expected: ((<Matcher object at 0x...>,), {})
  6. Called with: ((<Foo object at 0x...>,), {})

With a bit of tweaking you could have the comparison function raise theAssertionError 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(hamcrest.library.integration.match_equality).