unittest.mock —- mock对象库

3.3 新版功能.

源代码: Lib/unittest/mock.py


unittest.mock 是一个用于测试的Python库。它允许使用mock对象替换受测试系统的部分,并对它们如何已经被使用进行断言。

unittest.mock 提供的 Mock 类,能在整个测试套件中模拟大量的方法。创建后,就可以断言调用了哪些方法/属性及其参数。还可以以常规方式指定返回值并设置所需的属性。

此外,mock 提供了用于修补测试范围内模块和类级别属性的 patch() 装饰器,和用于创建独特对象的 sentinel 。 阅读 quick guide 中的案例了解如何使用 MockMagicMockpatch()

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

在 Python 的早期版本要单独使用 unittest.mock ,在 PyPI 获取 mock

快速上手

当您访问对象时, MockMagicMock 将创建所有属性和方法,并保存他们在使用时的细节。你可以通过配置,指定返回值或者限制可访问属性,然后断言他们如何被调用:

  1. >>> from unittest.mock import MagicMock
  2. >>> thing = ProductionClass()
  3. >>> thing.method = MagicMock(return_value=3)
  4. >>> thing.method(3, 4, 5, key='value')
  5. 3
  6. >>> thing.method.assert_called_with(3, 4, 5, key='value')

通过 side_effect 设置副作用(side effects) ,可以是一个 mock 被调用是抛出的异常:

  1. >>> mock = Mock(side_effect=KeyError('foo'))
  2. >>> mock()
  3. Traceback (most recent call last):
  4. ...
  5. KeyError: 'foo'
  1. >>> values = {'a': 1, 'b': 2, 'c': 3}
  2. >>> def side_effect(arg):
  3. ... return values[arg]
  4. ...
  5. >>> mock.side_effect = side_effect
  6. >>> mock('a'), mock('b'), mock('c')
  7. (1, 2, 3)
  8. >>> mock.side_effect = [5, 4, 3, 2, 1]
  9. >>> mock(), mock(), mock()
  10. (5, 4, 3)

Mock 还可以通过其他方法配置和控制其行为。例如 mock 可以通过设置 spec 参数来从一个对象中获取其规格(specification)。如果访问 mock 的属性或方法不在 spec 中,会报 AttributeError 错误。

使用 patch() 装饰去/上下文管理器,可以更方便地测试一个模块下的类或对象。你指定的对象会在测试过程中替换成 mock (或者其他对象),测试结束后恢复。

  1. >>> from unittest.mock import patch
  2. >>> @patch('module.ClassName2')
  3. ... @patch('module.ClassName1')
  4. ... def test(MockClass1, MockClass2):
  5. ... module.ClassName1()
  6. ... module.ClassName2()
  7. ... assert MockClass1 is module.ClassName1
  8. ... assert MockClass2 is module.ClassName2
  9. ... assert MockClass1.called
  10. ... assert MockClass2.called
  11. ...
  12. >>> test()

注解

当你嵌套 patch 装饰器时,mock 将以执行顺序传递给装饰器函数(Python 装饰器正常顺序)。由于从下至上,因此在上面的示例中,首先 mock 传入的 module.ClassName1

在查找对象的名称空间中修补对象使用 patch() 。使用起来很简单,阅读 在哪里打补丁 来快速上手。

patch() 也可以 with 语句中使用上下文管理。

  1. >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
  2. ... thing = ProductionClass()
  3. ... thing.method(1, 2, 3)
  4. ...
  5. >>> mock_method.assert_called_once_with(1, 2, 3)

还有一个 patch.dict() 用于在一定范围内设置字典中的值,并在测试结束时将字典恢复为其原始状态:

  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

Mock支持 Python 魔术方法 。使用模式方法最简单的方式是使用 MagicMock class. 。它可以做如下事情:

  1. >>> mock = MagicMock()
  2. >>> mock.__str__.return_value = 'foobarbaz'
  3. >>> str(mock)
  4. 'foobarbaz'
  5. >>> mock.__str__.assert_called_with()

Mock 能指定函数(或其他 Mock 实例)为魔术方法,它们将被适当地调用。 MagicMock 是预先创建了所有魔术方法(所有有用的方法) 的 Mock 。

下面是一个使用了普通 Mock 类的魔术方法的例子

  1. >>> mock = Mock()
  2. >>> mock.__str__ = Mock(return_value='wheeeeee')
  3. >>> str(mock)
  4. 'wheeeeee'

使用 auto-speccing 可以保证测试中的模拟对象与要替换的对象具有相同的api 。在 patch 中可以通过 autospec 参数实现自动推断,或者使用 create_autospec() 函数。自动推断会创建一个与要替换对象相同的属相和方法的模拟对象,并且任何函数和方法(包括构造函数)都具有与真实对象相同的调用签名。

这么做是为了因确保不当地使用 mock 导致与生产代码相同的失败:

  1. >>> from unittest.mock import create_autospec
  2. >>> def function(a, b, c):
  3. ... pass
  4. ...
  5. >>> mock_function = create_autospec(function, return_value='fishy')
  6. >>> mock_function(1, 2, 3)
  7. 'fishy'
  8. >>> mock_function.assert_called_once_with(1, 2, 3)
  9. >>> mock_function('wrong arguments')
  10. Traceback (most recent call last):
  11. ...
  12. TypeError: <lambda>() takes exactly 3 arguments (1 given)

在类中使用 create_autospec() 时,会复制 __init__ 方法的签名,另外在可调用对象上使用时,会复制 __call__ 方法的签名。

Mock 类

Mock 是一个可以灵活的替换存根 (stubs) 的对象,可以测试所有代码。 Mock 是可调用的,在访问其属性时创建一个新的 mock 1 。访问相同的属性只会返回相同的 mock 。 Mock 会保存调用记录,可以通过断言获悉代码的调用。

MagicMockMock 的子类,它有所有预创建且可使用的魔术方法。在需要模拟不可调用对象时,可以使用 NonCallableMockNonCallableMagicMock

patch() 装饰器便于 Mock 对象临时替换特定模块中的类。 patch() 默认创建 MagicMock 。可以使用 patch() 方法的 new_callable 参数指定 Mock 的替代类。

class unittest.mock.Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, \*kwargs*)

创建一个新的 Mock 对象。通过可选参数指定 Mock 对象的行为:

  • spec: 可以是要给字符串列表,也可以是充当模拟对象规范的现有对象(类或实例)。如果传入一个对象,则通过在该对象上调用 dir 来生成字符串列表(不支持的魔法属性和方法除外)。访问不在此列表中的任何属性都将触发 AttributeError

    如果 spec 是一个对象(而不是字符串列表),则 __class__ 返回 spec 对象的类。 这允许模拟程序通过 isinstance() 测试。

  • spec_setspec 的更严格的变体。如果使用了该属性,尝试模拟 setget 的属性不在 spec_set 所包含的对象中时,会抛出 AttributeError

  • side_effect :每当调用 Mock 时都会调用的函数。 参见 side_effect 属性。 对于引发异常或动态更改返回值很有用。 该函数使用与 mock 函数相同的参数调用,并且除非返回 DEFAULT ,否则该函数的返回值将用作返回值。

    另外, side_effect 可以是异常类或实例。 此时,调用模拟程序时将引发异常。

    如果 side_effect 是可迭代对象,则每次调用 mock 都将返回可迭代对象的下一个值。

    设置 side_effectNone 即可清空。

  • return_value :调用 mock 的返回值。 默认情况下,是一个新的Mock(在首次访问时创建)。 参见 return_value 属性 。

  • unsafe :默认情况下,如果任何以 assertassret 开头的属性都将引发 AttributeError 。 当 unsafe=True 时可以访问。

    3.5 新版功能.

  • wraps :要包装的 mock 对象。 如果 wraps 不是 None ,那么调用 Mock 会将调用传递给 wraps 的对象(返回实际结果)。 对模拟的属性访问将返回一个 Mock 对象,该对象包装了 wraps 对象的相应属性(因此,尝试访问不存在的属性将引发 AttributeError )。

    如果明确指定 return_value ,调用是,不会返回包装对象,而是返回 return_value

  • name :mock 的名称。 在调试时很有用。 名称会传递到子 mock 。

还可以使用任意关键字参数来调用 mock 。 创建模拟后,将使用这些属性来设置 mock 的属性。 有关详细信息,请参见 configure_mock() 方法。

  • assert_called()

    断言至少被调用过一次。

    1. >>> mock = Mock()
    2. >>> mock.method()
    3. <Mock name='mock.method()' id='...'>
    4. >>> mock.method.assert_called()

    3.6 新版功能.

  • assert_called_once()

    断言仅被调用一次。

    1. >>> mock = Mock()
    2. >>> mock.method()
    3. <Mock name='mock.method()' id='...'>
    4. >>> mock.method.assert_called_once()
    5. >>> mock.method()
    6. <Mock name='mock.method()' id='...'>
    7. >>> mock.method.assert_called_once()
    8. Traceback (most recent call last):
    9. ...
    10. AssertionError: Expected 'method' to have been called once. Called 2 times.

    3.6 新版功能.

  • assert_called_with(\args, **kwargs*)

    此方法是断言上次调用已以特定方式进行的一种便捷方法:

    1. >>> mock = Mock()
    2. >>> mock.method(1, 2, 3, test='wow')
    3. <Mock name='mock.method()' id='...'>
    4. >>> mock.method.assert_called_with(1, 2, 3, test='wow')
  • assert_called_once_with(\args, **kwargs*)

    Assert that the mock was called exactly once and that call was with the specified arguments.

    1. >>> mock = Mock(return_value=None)
    2. >>> mock('foo', bar='baz')
    3. >>> mock.assert_called_once_with('foo', bar='baz')
    4. >>> mock('other', bar='values')
    5. >>> mock.assert_called_once_with('other', bar='values')
    6. Traceback (most recent call last):
    7. ...
    8. AssertionError: Expected 'mock' to be called once. Called 2 times.
  • assert_any_call(\args, **kwargs*)

    断言使用指定的参数调用。

    The assert passes if the mock has ever been called, unlike assert_called_with() and assert_called_once_with() that only pass if the call is the most recent one, and in the case of assert_called_once_with() it must also be the only call.

    1. >>> mock = Mock(return_value=None)
    2. >>> mock(1, 2, arg='thing')
    3. >>> mock('some', 'thing', 'else')
    4. >>> mock.assert_any_call(1, 2, arg='thing')
  • assert_has_calls(calls, any_order=False)

    assert the mock has been called with the specified calls. The mock_calls list is checked for the calls.

    If any_order is false then the calls must be sequential. There can be extra calls before or after the specified calls.

    If any_order is true then the calls can be in any order, but they must all appear in mock_calls.

    1. >>> mock = Mock(return_value=None)
    2. >>> mock(1)
    3. >>> mock(2)
    4. >>> mock(3)
    5. >>> mock(4)
    6. >>> calls = [call(2), call(3)]
    7. >>> mock.assert_has_calls(calls)
    8. >>> calls = [call(4), call(2), call(3)]
    9. >>> mock.assert_has_calls(calls, any_order=True)
  • assert_not_called()

    Assert the mock was never called.

    1. >>> m = Mock()
    2. >>> m.hello.assert_not_called()
    3. >>> obj = m.hello()
    4. >>> m.hello.assert_not_called()
    5. Traceback (most recent call last):
    6. ...
    7. AssertionError: Expected 'hello' to not have been called. Called 1 times.

    3.5 新版功能.

  • reset_mock(**, return_value=False, side_effect=False*)

    The reset_mock method resets all the call attributes on a mock object:

    1. >>> mock = Mock(return_value=None)
    2. >>> mock('hello')
    3. >>> mock.called
    4. True
    5. >>> mock.reset_mock()
    6. >>> mock.called
    7. False

    在 3.6 版更改: Added two keyword only argument to the reset_mock function.

    This can be useful where you want to make a series of assertions that reuse the same object. Note that reset_mock() doesn’t clear the return value, side_effect or any child attributes you have set using normal assignment by default. In case you want to reset return_value or side_effect, then pass the corresponding parameter as True. Child mocks and the return value mock (if any) are reset as well.

    注解

    return_value, and side_effect are keyword only argument.

  • mock_add_spec(spec, spec_set=False)

    Add a spec to a mock. spec can either be an object or a list of strings. Only attributes on the spec can be fetched as attributes from the mock.

    If spec_set is true then only attributes on the spec can be set.

  • attach_mock(mock, attribute)

    Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the method_calls and mock_calls attributes of this one.

  • configure_mock(\*kwargs*)

    Set attributes on the mock through keyword arguments.

    Attributes plus return values and side effects can be set on child mocks using standard dot notation and unpacking a dictionary in the method call:

    1. >>> mock = Mock()
    2. >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
    3. >>> mock.configure_mock(**attrs)
    4. >>> mock.method()
    5. 3
    6. >>> mock.other()
    7. Traceback (most recent call last):
    8. ...
    9. KeyError

    The same thing can be achieved in the constructor call to mocks:

    1. >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
    2. >>> mock = Mock(some_attribute='eggs', **attrs)
    3. >>> mock.some_attribute
    4. 'eggs'
    5. >>> mock.method()
    6. 3
    7. >>> mock.other()
    8. Traceback (most recent call last):
    9. ...
    10. KeyError

    configure_mock() exists to make it easier to do configuration after the mock has been created.

  • __dir__()

    Mock objects limit the results of dir(some_mock) to useful results. For mocks with a spec this includes all the permitted attributes for the mock.

    See FILTER_DIR for what this filtering does, and how to switch it off.

  • _get_child_mock(\*kw*)

    Create the child mocks for attributes and return value. By default child mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made.

    For non-callable mocks the callable variant will be used (rather than any custom subclass).

  • called

    A boolean representing whether or not the mock object has been called:

    1. >>> mock = Mock(return_value=None)
    2. >>> mock.called
    3. False
    4. >>> mock()
    5. >>> mock.called
    6. True
  • call_count

    An integer telling you how many times the mock object has been called:

    1. >>> mock = Mock(return_value=None)
    2. >>> mock.call_count
    3. 0
    4. >>> mock()
    5. >>> mock()
    6. >>> mock.call_count
    7. 2
  • return_value

    Set this to configure the value returned by calling the mock:

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

    The default return value is a mock object and you can configure it in the normal way:

    1. >>> mock = Mock()
    2. >>> mock.return_value.attribute = sentinel.Attribute
    3. >>> mock.return_value()
    4. <Mock name='mock()()' id='...'>
    5. >>> mock.return_value.assert_called_with()

    return_value can also be set in the constructor:

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

    This can either be a function to be called when the mock is called, an iterable or an exception (class or instance) to be raised.

    If you pass in a function it will be called with same arguments as the mock and unless the function returns the DEFAULT singleton the call to the mock will then return whatever the function returns. If the function returns DEFAULT then the mock will return its normal value (from the return_value).

    If you pass in an iterable, it is used to retrieve an iterator which must yield a value on every call. This value can either be an exception instance to be raised, or a value to be returned from the call to the mock (DEFAULT handling is identical to the function case).

    An example of a mock that raises an exception (to test exception handling of an API):

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

    Using side_effect to return a sequence of values:

    1. >>> mock = Mock()
    2. >>> mock.side_effect = [3, 2, 1]
    3. >>> mock(), mock(), mock()
    4. (3, 2, 1)

    Using a callable:

    1. >>> mock = Mock(return_value=3)
    2. >>> def side_effect(*args, **kwargs):
    3. ... return DEFAULT
    4. ...
    5. >>> mock.side_effect = side_effect
    6. >>> mock()
    7. 3

    side_effect can be set in the constructor. Here’s an example that adds one to the value the mock is called with and returns it:

    1. >>> side_effect = lambda value: value + 1
    2. >>> mock = Mock(side_effect=side_effect)
    3. >>> mock(3)
    4. 4
    5. >>> mock(-8)
    6. -7

    Setting side_effect to None clears it:

    1. >>> m = Mock(side_effect=KeyError, return_value=3)
    2. >>> m()
    3. Traceback (most recent call last):
    4. ...
    5. KeyError
    6. >>> m.side_effect = None
    7. >>> m()
    8. 3
  • call_args

    This is either None (if the mock hasn’t been called), or the arguments that the mock was last called with. This will be in the form of a tuple: the first member, which can also be accessed through the args property, is any ordered arguments the mock was called with (or an empty tuple) and the second member, which can also be accessed through the kwargs property, is any keyword arguments (or an empty dictionary).

    1. >>> mock = Mock(return_value=None)
    2. >>> print(mock.call_args)
    3. None
    4. >>> mock()
    5. >>> mock.call_args
    6. call()
    7. >>> mock.call_args == ()
    8. True
    9. >>> mock(3, 4)
    10. >>> mock.call_args
    11. call(3, 4)
    12. >>> mock.call_args == ((3, 4),)
    13. True
    14. >>> mock.call_args.args
    15. (3, 4)
    16. >>> mock.call_args.kwargs
    17. {}
    18. >>> mock(3, 4, 5, key='fish', next='w00t!')
    19. >>> mock.call_args
    20. call(3, 4, 5, key='fish', next='w00t!')
    21. >>> mock.call_args.args
    22. (3, 4, 5)
    23. >>> mock.call_args.kwargs
    24. {'key': 'fish', 'next': 'w00t!'}

    call_args, along with members of the lists call_args_list, method_calls and mock_calls are call objects. These are tuples, so they can be unpacked to get at the individual arguments and make more complex assertions. See calls as tuples.

    在 3.8 版更改: Added args and kwargs properties.

  • call_args_list

    This is a list of all the calls made to the mock object in sequence (so the length of the list is the number of times it has been called). Before any calls have been made it is an empty list. The call object can be used for conveniently constructing lists of calls to compare with call_args_list.

    1. >>> mock = Mock(return_value=None)
    2. >>> mock()
    3. >>> mock(3, 4)
    4. >>> mock(key='fish', next='w00t!')
    5. >>> mock.call_args_list
    6. [call(), call(3, 4), call(key='fish', next='w00t!')]
    7. >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
    8. >>> mock.call_args_list == expected
    9. True

    Members of call_args_list are call objects. These can be unpacked as tuples to get at the individual arguments. See calls as tuples.

  • method_calls

    As well as tracking calls to themselves, mocks also track calls to methods and attributes, and their methods and attributes:

    1. >>> mock = Mock()
    2. >>> mock.method()
    3. <Mock name='mock.method()' id='...'>
    4. >>> mock.property.method.attribute()
    5. <Mock name='mock.property.method.attribute()' id='...'>
    6. >>> mock.method_calls
    7. [call.method(), call.property.method.attribute()]

    Members of method_calls are call objects. These can be unpacked as tuples to get at the individual arguments. See calls as tuples.

  • mock_calls

    mock_calls records all calls to the mock object, its methods, magic methods and return value mocks.

    1. >>> mock = MagicMock()
    2. >>> result = mock(1, 2, 3)
    3. >>> mock.first(a=3)
    4. <MagicMock name='mock.first()' id='...'>
    5. >>> mock.second()
    6. <MagicMock name='mock.second()' id='...'>
    7. >>> int(mock)
    8. 1
    9. >>> result(1)
    10. <MagicMock name='mock()()' id='...'>
    11. >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
    12. ... call.__int__(), call()(1)]
    13. >>> mock.mock_calls == expected
    14. True

    Members of mock_calls are call objects. These can be unpacked as tuples to get at the individual arguments. See calls as tuples.

    注解

    The way mock_calls are recorded means that where nested calls are made, the parameters of ancestor calls are not recorded and so will always compare equal:

    1. >>> mock = MagicMock()
    2. >>> mock.top(a=3).bottom()
    3. <MagicMock name='mock.top().bottom()' id='...'>
    4. >>> mock.mock_calls
    5. [call.top(a=3), call.top().bottom()]
    6. >>> mock.mock_calls[-1] == call.top(a=-1).bottom()
    7. True
  • __class__

    Normally the __class__ attribute of an object will return its type. For a mock object with a spec, __class__ returns the spec class instead. This allows mock objects to pass isinstance() tests for the object they are replacing / masquerading as:

    1. >>> mock = Mock(spec=3)
    2. >>> isinstance(mock, int)
    3. True

    __class__ is assignable to, this allows a mock to pass an isinstance() check without forcing you to use a spec:

    1. >>> mock = Mock()
    2. >>> mock.__class__ = dict
    3. >>> isinstance(mock, dict)
    4. True

class unittest.mock.NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, \*kwargs*)

A non-callable version of Mock. The constructor parameters have the same meaning of Mock, with the exception of return_value and side_effect which have no meaning on a non-callable mock.

Mock objects that use a class or an instance as a spec or spec_set are able to pass isinstance() tests:

  1. >>> mock = Mock(spec=SomeClass)
  2. >>> isinstance(mock, SomeClass)
  3. True
  4. >>> mock = Mock(spec_set=SomeClass())
  5. >>> isinstance(mock, SomeClass)
  6. True

The Mock classes have support for mocking magic methods. See magic methods for the full details.

The mock classes and the patch() decorators all take arbitrary keyword arguments for configuration. For the patch() decorators the keywords are passed to the constructor of the mock being created. The keyword arguments are for configuring attributes of the mock:

  1. >>> m = MagicMock(attribute=3, other='fish')
  2. >>> m.attribute
  3. 3
  4. >>> m.other
  5. 'fish'

The return value and side effect of child mocks can be set in the same way, using dotted notation. As you can’t use dotted names directly in a call you have to create a dictionary and unpack it using **:

  1. >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
  2. >>> mock = Mock(some_attribute='eggs', **attrs)
  3. >>> mock.some_attribute
  4. 'eggs'
  5. >>> mock.method()
  6. 3
  7. >>> mock.other()
  8. Traceback (most recent call last):
  9. ...
  10. KeyError

A callable mock which was created with a spec (or a spec_set) will introspect the specification object’s signature when matching calls to the mock. Therefore, it can match the actual call’s arguments regardless of whether they were passed positionally or by name:

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

This applies to assert_called_with(), assert_called_once_with(), assert_has_calls() and assert_any_call(). When Autospeccing, it will also apply to method calls on the mock object.

在 3.4 版更改: Added signature introspection on specced and autospecced mock objects.

class unittest.mock.PropertyMock(\args, **kwargs*)

A mock intended to be used as a property, or other descriptor, on a class. PropertyMock provides __get__() and __set__() methods so you can specify a return value when it is fetched.

Fetching a PropertyMock instance from an object calls the mock, with no args. Setting it calls the mock with the value being set.

  1. >>> class Foo:
  2. ... @property
  3. ... def foo(self):
  4. ... return 'something'
  5. ... @foo.setter
  6. ... def foo(self, value):
  7. ... pass
  8. ...
  9. >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
  10. ... mock_foo.return_value = 'mockity-mock'
  11. ... this_foo = Foo()
  12. ... print(this_foo.foo)
  13. ... this_foo.foo = 6
  14. ...
  15. mockity-mock
  16. >>> mock_foo.mock_calls
  17. [call(), call(6)]

Because of the way mock attributes are stored you can’t directly attach a PropertyMock to a mock object. Instead you can attach it to the mock type object:

  1. >>> m = MagicMock()
  2. >>> p = PropertyMock(return_value=3)
  3. >>> type(m).foo = p
  4. >>> m.foo
  5. 3
  6. >>> p.assert_called_once_with()

class unittest.mock.AsyncMock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, \*kwargs*)

An asynchronous version of MagicMock. The AsyncMock object will behave so the object is recognized as an async function, and the result of a call is an awaitable.

  1. >>> mock = AsyncMock()
  2. >>> asyncio.iscoroutinefunction(mock)
  3. True
  4. >>> inspect.isawaitable(mock())
  5. True

The result of mock() is an async function which will have the outcome of side_effect or return_value after it has been awaited:

  • if side_effect is a function, the async function will return the result of that function,

  • if side_effect is an exception, the async function will raise the exception,

  • if side_effect is an iterable, the async function will return the next value of the iterable, however, if the sequence of result is exhausted, StopAsyncIteration is raised immediately,

  • if side_effect is not defined, the async function will return the value defined by return_value, hence, by default, the async function returns a new AsyncMock object.

Setting the spec of a Mock or MagicMock to an async function will result in a coroutine object being returned after calling.

  1. >>> async def async_func(): pass
  2. ...
  3. >>> mock = MagicMock(async_func)
  4. >>> mock
  5. <MagicMock spec='function' id='...'>
  6. >>> mock()
  7. <coroutine object AsyncMockMixin._mock_call at ...>

Setting the spec of a Mock, MagicMock, or AsyncMock to a class with asynchronous and synchronous functions will automatically detect the synchronous functions and set them as MagicMock (if the parent mock is AsyncMock or MagicMock) or Mock (if the parent mock is Mock). All asynchronous functions will be AsyncMock.

  1. >>> class ExampleClass:
  2. ... def sync_foo():
  3. ... pass
  4. ... async def async_foo():
  5. ... pass
  6. ...
  7. >>> a_mock = AsyncMock(ExampleClass)
  8. >>> a_mock.sync_foo
  9. <MagicMock name='mock.sync_foo' id='...'>
  10. >>> a_mock.async_foo
  11. <AsyncMock name='mock.async_foo' id='...'>
  12. >>> mock = Mock(ExampleClass)
  13. >>> mock.sync_foo
  14. <Mock name='mock.sync_foo' id='...'>
  15. >>> mock.async_foo
  16. <AsyncMock name='mock.async_foo' id='...'>

3.8 新版功能.

  • assert_awaited()

    Assert that the mock was awaited at least once. Note that this is separate from the object having been called, the await keyword must be used:

    1. >>> mock = AsyncMock()
    2. >>> async def main(coroutine_mock):
    3. ... await coroutine_mock
    4. ...
    5. >>> coroutine_mock = mock()
    6. >>> mock.called
    7. True
    8. >>> mock.assert_awaited()
    9. Traceback (most recent call last):
    10. ...
    11. AssertionError: Expected mock to have been awaited.
    12. >>> asyncio.run(main(coroutine_mock))
    13. >>> mock.assert_awaited()
  • assert_awaited_once()

    Assert that the mock was awaited exactly once.

    1. >>> mock = AsyncMock()
    2. >>> async def main():
    3. ... await mock()
    4. ...
    5. >>> asyncio.run(main())
    6. >>> mock.assert_awaited_once()
    7. >>> asyncio.run(main())
    8. >>> mock.method.assert_awaited_once()
    9. Traceback (most recent call last):
    10. ...
    11. AssertionError: Expected mock to have been awaited once. Awaited 2 times.
  • assert_awaited_with(\args, **kwargs*)

    Assert that the last await was with the specified arguments.

    1. >>> mock = AsyncMock()
    2. >>> async def main(*args, **kwargs):
    3. ... await mock(*args, **kwargs)
    4. ...
    5. >>> asyncio.run(main('foo', bar='bar'))
    6. >>> mock.assert_awaited_with('foo', bar='bar')
    7. >>> mock.assert_awaited_with('other')
    8. Traceback (most recent call last):
    9. ...
    10. AssertionError: expected call not found.
    11. Expected: mock('other')
    12. Actual: mock('foo', bar='bar')
  • assert_awaited_once_with(\args, **kwargs*)

    Assert that the mock was awaited exactly once and with the specified arguments.

    1. >>> mock = AsyncMock()
    2. >>> async def main(*args, **kwargs):
    3. ... await mock(*args, **kwargs)
    4. ...
    5. >>> asyncio.run(main('foo', bar='bar'))
    6. >>> mock.assert_awaited_once_with('foo', bar='bar')
    7. >>> asyncio.run(main('foo', bar='bar'))
    8. >>> mock.assert_awaited_once_with('foo', bar='bar')
    9. Traceback (most recent call last):
    10. ...
    11. AssertionError: Expected mock to have been awaited once. Awaited 2 times.
  • assert_any_await(\args, **kwargs*)

    Assert the mock has ever been awaited with the specified arguments.

    1. >>> mock = AsyncMock()
    2. >>> async def main(*args, **kwargs):
    3. ... await mock(*args, **kwargs)
    4. ...
    5. >>> asyncio.run(main('foo', bar='bar'))
    6. >>> asyncio.run(main('hello'))
    7. >>> mock.assert_any_await('foo', bar='bar')
    8. >>> mock.assert_any_await('other')
    9. Traceback (most recent call last):
    10. ...
    11. AssertionError: mock('other') await not found
  • assert_has_awaits(calls, any_order=False)

    Assert the mock has been awaited with the specified calls. The await_args_list list is checked for the awaits.

    If any_order is false then the awaits must be sequential. There can be extra calls before or after the specified awaits.

    If any_order is true then the awaits can be in any order, but they must all appear in await_args_list.

    1. >>> mock = AsyncMock()
    2. >>> async def main(*args, **kwargs):
    3. ... await mock(*args, **kwargs)
    4. ...
    5. >>> calls = [call("foo"), call("bar")]
    6. >>> mock.assert_has_awaits(calls)
    7. Traceback (most recent call last):
    8. ...
    9. AssertionError: Awaits not found.
    10. Expected: [call('foo'), call('bar')]
    11. Actual: []
    12. >>> asyncio.run(main('foo'))
    13. >>> asyncio.run(main('bar'))
    14. >>> mock.assert_has_awaits(calls)
  • assert_not_awaited()

    Assert that the mock was never awaited.

    1. >>> mock = AsyncMock()
    2. >>> mock.assert_not_awaited()
  • reset_mock(\args, **kwargs*)

    See Mock.reset_mock(). Also sets await_count to 0, await_args to None, and clears the await_args_list.

  • await_count

    An integer keeping track of how many times the mock object has been awaited.

    1. >>> mock = AsyncMock()
    2. >>> async def main():
    3. ... await mock()
    4. ...
    5. >>> asyncio.run(main())
    6. >>> mock.await_count
    7. 1
    8. >>> asyncio.run(main())
    9. >>> mock.await_count
    10. 2
  • await_args

    This is either None (if the mock hasn’t been awaited), or the arguments that the mock was last awaited with. Functions the same as Mock.call_args.

    1. >>> mock = AsyncMock()
    2. >>> async def main(*args):
    3. ... await mock(*args)
    4. ...
    5. >>> mock.await_args
    6. >>> asyncio.run(main('foo'))
    7. >>> mock.await_args
    8. call('foo')
    9. >>> asyncio.run(main('bar'))
    10. >>> mock.await_args
    11. call('bar')
  • await_args_list

    This is a list of all the awaits made to the mock object in sequence (so the length of the list is the number of times it has been awaited). Before any awaits have been made it is an empty list.

    1. >>> mock = AsyncMock()
    2. >>> async def main(*args):
    3. ... await mock(*args)
    4. ...
    5. >>> mock.await_args_list
    6. []
    7. >>> asyncio.run(main('foo'))
    8. >>> mock.await_args_list
    9. [call('foo')]
    10. >>> asyncio.run(main('bar'))
    11. >>> mock.await_args_list
    12. [call('foo'), call('bar')]

Calling

Mock objects are callable. The call will return the value set as the return_value attribute. The default return value is a new Mock object; it is created the first time the return value is accessed (either explicitly or by calling the Mock) - but it is stored and the same one returned each time.

Calls made to the object will be recorded in the attributes like call_args and call_args_list.

If side_effect is set then it will be called after the call has been recorded, so if side_effect raises an exception the call is still recorded.

The simplest way to make a mock raise an exception when called is to make side_effect an exception class or instance:

  1. >>> m = MagicMock(side_effect=IndexError)
  2. >>> m(1, 2, 3)
  3. Traceback (most recent call last):
  4. ...
  5. IndexError
  6. >>> m.mock_calls
  7. [call(1, 2, 3)]
  8. >>> m.side_effect = KeyError('Bang!')
  9. >>> m('two', 'three', 'four')
  10. Traceback (most recent call last):
  11. ...
  12. KeyError: 'Bang!'
  13. >>> m.mock_calls
  14. [call(1, 2, 3), call('two', 'three', 'four')]

If side_effect is a function then whatever that function returns is what calls to the mock return. The side_effect function is called with the same arguments as the mock. This allows you to vary the return value of the call dynamically, based on the input:

  1. >>> def side_effect(value):
  2. ... return value + 1
  3. ...
  4. >>> m = MagicMock(side_effect=side_effect)
  5. >>> m(1)
  6. 2
  7. >>> m(2)
  8. 3
  9. >>> m.mock_calls
  10. [call(1), call(2)]

If you want the mock to still return the default return value (a new mock), or any set return value, then there are two ways of doing this. Either return mock.return_value from inside side_effect, or return DEFAULT:

  1. >>> m = MagicMock()
  2. >>> def side_effect(*args, **kwargs):
  3. ... return m.return_value
  4. ...
  5. >>> m.side_effect = side_effect
  6. >>> m.return_value = 3
  7. >>> m()
  8. 3
  9. >>> def side_effect(*args, **kwargs):
  10. ... return DEFAULT
  11. ...
  12. >>> m.side_effect = side_effect
  13. >>> m()
  14. 3

To remove a side_effect, and return to the default behaviour, set the side_effect to None:

  1. >>> m = MagicMock(return_value=6)
  2. >>> def side_effect(*args, **kwargs):
  3. ... return 3
  4. ...
  5. >>> m.side_effect = side_effect
  6. >>> m()
  7. 3
  8. >>> m.side_effect = None
  9. >>> m()
  10. 6

The side_effect can also be any iterable object. Repeated calls to the mock will return values from the iterable (until the iterable is exhausted and a StopIteration is raised):

  1. >>> m = MagicMock(side_effect=[1, 2, 3])
  2. >>> m()
  3. 1
  4. >>> m()
  5. 2
  6. >>> m()
  7. 3
  8. >>> m()
  9. Traceback (most recent call last):
  10. ...
  11. StopIteration

If any members of the iterable are exceptions they will be raised instead of returned:

  1. >>> iterable = (33, ValueError, 66)
  2. >>> m = MagicMock(side_effect=iterable)
  3. >>> m()
  4. 33
  5. >>> m()
  6. Traceback (most recent call last):
  7. ...
  8. ValueError
  9. >>> m()
  10. 66

Deleting Attributes

Mock objects create attributes on demand. This allows them to pretend to be objects of any type.

You may want a mock object to return False to a hasattr() call, or raise an AttributeError when an attribute is fetched. You can do this by providing an object as a spec for a mock, but that isn’t always convenient.

You “block” attributes by deleting them. Once deleted, accessing an attribute will raise an AttributeError.

  1. >>> mock = MagicMock()
  2. >>> hasattr(mock, 'm')
  3. True
  4. >>> del mock.m
  5. >>> hasattr(mock, 'm')
  6. False
  7. >>> del mock.f
  8. >>> mock.f
  9. Traceback (most recent call last):
  10. ...
  11. AttributeError: f

Mock names and the name attribute

Since “name” is an argument to the Mock constructor, if you want your mock object to have a “name” attribute you can’t just pass it in at creation time. There are two alternatives. One option is to use configure_mock():

  1. >>> mock = MagicMock()
  2. >>> mock.configure_mock(name='my_name')
  3. >>> mock.name
  4. 'my_name'

A simpler option is to simply set the “name” attribute after mock creation:

  1. >>> mock = MagicMock()
  2. >>> mock.name = "foo"

Attaching Mocks as Attributes

When you attach a mock as an attribute of another mock (or as the return value) it becomes a “child” of that mock. Calls to the child are recorded in the method_calls and mock_calls attributes of the parent. This is useful for configuring child mocks and then attaching them to the parent, or for attaching mocks to a parent that records all calls to the children and allows you to make assertions about the order of calls between mocks:

  1. >>> parent = MagicMock()
  2. >>> child1 = MagicMock(return_value=None)
  3. >>> child2 = MagicMock(return_value=None)
  4. >>> parent.child1 = child1
  5. >>> parent.child2 = child2
  6. >>> child1(1)
  7. >>> child2(2)
  8. >>> parent.mock_calls
  9. [call.child1(1), call.child2(2)]

The exception to this is if the mock has a name. This allows you to prevent the “parenting” if for some reason you don’t want it to happen.

  1. >>> mock = MagicMock()
  2. >>> not_a_child = MagicMock(name='not-a-child')
  3. >>> mock.attribute = not_a_child
  4. >>> mock.attribute()
  5. <MagicMock name='not-a-child()' id='...'>
  6. >>> mock.mock_calls
  7. []

Mocks created for you by patch() are automatically given names. To attach mocks that have names to a parent you use the attach_mock() method:

  1. >>> thing1 = object()
  2. >>> thing2 = object()
  3. >>> parent = MagicMock()
  4. >>> with patch('__main__.thing1', return_value=None) as child1:
  5. ... with patch('__main__.thing2', return_value=None) as child2:
  6. ... parent.attach_mock(child1, 'child1')
  7. ... parent.attach_mock(child2, 'child2')
  8. ... child1('one')
  9. ... child2('two')
  10. ...
  11. >>> parent.mock_calls
  12. [call.child1('one'), call.child2('two')]

1

The only exceptions are magic methods and attributes (those that have leading and trailing double underscores). Mock doesn’t create these but instead raises an AttributeError. This is because the interpreter will often implicitly request these methods, and gets very confused to get a new Mock object when it expects a magic method. If you need magic method support see magic methods.

The patchers

The patch decorators are used for patching objects only within the scope of the function they decorate. They automatically handle the unpatching for you, even if exceptions are raised. All of these functions can also be used in with statements or as class decorators.

patch

注解

The key is to do the patching in the right namespace. See the section where to patch.

unittest.mock.patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, \*kwargs*)

patch() acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the target is patched with a new object. When the function/with statement exits the patch is undone.

If new is omitted, then the target is replaced with an AsyncMock if the patched object is an async function or a MagicMock otherwise. If patch() is used as a decorator and new is omitted, the created mock is passed in as an extra argument to the decorated function. If patch() is used as a context manager the created mock is returned by the context manager.

target should be a string in the form 'package.module.ClassName'. The target is imported and the specified object replaced with the new object, so the target must be importable from the environment you are calling patch() from. The target is imported when the decorated function is executed, not at decoration time.

The spec and spec_set keyword arguments are passed to the MagicMock if patch is creating one for you.

In addition you can pass spec=True or spec_set=True, which causes patch to pass in the object being mocked as the spec/spec_set object.

new_callable allows you to specify a different class, or callable object, that will be called to create the new object. By default AsyncMock is used for async functions and MagicMock for the rest.

A more powerful form of spec is autospec. If you set autospec=True then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a TypeError if they are called with the wrong signature. For mocks replacing a class, their return value (the ‘instance’) will have the same spec as the class. See the create_autospec() function and Autospeccing.

Instead of autospec=True you can pass autospec=some_object to use an arbitrary object as the spec instead of the one being replaced.

By default patch() will fail to replace attributes that don’t exist. If you pass in create=True, and the attribute doesn’t exist, patch will create the attribute for you when the patched function is called, and delete it again after the patched function has exited. This is useful for writing tests against attributes that your production code creates at runtime. It is off by default because it can be dangerous. With it switched on you can write passing tests against APIs that don’t actually exist!

注解

在 3.5 版更改: If you are patching builtins in a module then you don’t need to pass create=True, it will be added by default.

Patch can be used as a TestCase class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set. patch() finds tests by looking for method names that start with patch.TEST_PREFIX. By default this is 'test', which matches the way unittest finds tests. You can specify an alternative prefix by setting patch.TEST_PREFIX.

Patch can be used as a context manager, with the with statement. Here the patching applies to the indented block after the with statement. If you use “as” then the patched object will be bound to the name after the “as”; very useful if patch() is creating a mock object for you.

patch() takes arbitrary keyword arguments. These will be passed to AsyncMock if the patched object is asynchronous, to MagicMock otherwise or to new_callable if specified.

patch.dict(...), patch.multiple(...) and patch.object(...) are available for alternate use-cases.

patch() as function decorator, creating the mock for you and passing it into the decorated function:

  1. >>> @patch('__main__.SomeClass')
  2. ... def function(normal_argument, mock_class):
  3. ... print(mock_class is SomeClass)
  4. ...
  5. >>> function(None)
  6. True

Patching a class replaces the class with a MagicMock instance. If the class is instantiated in the code under test then it will be the return_value of the mock that will be used.

If the class is instantiated multiple times you could use side_effect to return a new mock each time. Alternatively you can set the return_value to be anything you want.

To configure return values on methods of instances on the patched class you must do this on the return_value. For example:

  1. >>> class Class:
  2. ... def method(self):
  3. ... pass
  4. ...
  5. >>> with patch('__main__.Class') as MockClass:
  6. ... instance = MockClass.return_value
  7. ... instance.method.return_value = 'foo'
  8. ... assert Class() is instance
  9. ... assert Class().method() == 'foo'
  10. ...

If you use spec or spec_set and patch() is replacing a class, then the return value of the created mock will have the same spec.

  1. >>> Original = Class
  2. >>> patcher = patch('__main__.Class', spec=True)
  3. >>> MockClass = patcher.start()
  4. >>> instance = MockClass()
  5. >>> assert isinstance(instance, Original)
  6. >>> patcher.stop()

The new_callable argument is useful where you want to use an alternative class to the default MagicMock for the created mock. For example, if you wanted a NonCallableMock to be used:

  1. >>> thing = object()
  2. >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
  3. ... assert thing is mock_thing
  4. ... thing()
  5. ...
  6. Traceback (most recent call last):
  7. ...
  8. TypeError: 'NonCallableMock' object is not callable

Another use case might be to replace an object with an io.StringIO instance:

  1. >>> from io import StringIO
  2. >>> def foo():
  3. ... print('Something')
  4. ...
  5. >>> @patch('sys.stdout', new_callable=StringIO)
  6. ... def test(mock_stdout):
  7. ... foo()
  8. ... assert mock_stdout.getvalue() == 'Something\n'
  9. ...
  10. >>> test()

When patch() is creating a mock for you, it is common that the first thing you need to do is to configure the mock. Some of that configuration can be done in the call to patch. Any arbitrary keywords you pass into the call will be used to set attributes on the created mock:

  1. >>> patcher = patch('__main__.thing', first='one', second='two')
  2. >>> mock_thing = patcher.start()
  3. >>> mock_thing.first
  4. 'one'
  5. >>> mock_thing.second
  6. 'two'

As well as attributes on the created mock attributes, like the return_value and side_effect, of child mocks can also be configured. These aren’t syntactically valid to pass in directly as keyword arguments, but a dictionary with these as keys can still be expanded into a patch() call using **:

  1. >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
  2. >>> patcher = patch('__main__.thing', **config)
  3. >>> mock_thing = patcher.start()
  4. >>> mock_thing.method()
  5. 3
  6. >>> mock_thing.other()
  7. Traceback (most recent call last):
  8. ...
  9. KeyError

By default, attempting to patch a function in a module (or a method or an attribute in a class) that does not exist will fail with AttributeError:

  1. >>> @patch('sys.non_existing_attribute', 42)
  2. ... def test():
  3. ... assert sys.non_existing_attribute == 42
  4. ...
  5. >>> test()
  6. Traceback (most recent call last):
  7. ...
  8. AttributeError: <module 'sys' (built-in)> does not have the attribute 'non_existing'

but adding create=True in the call to patch() will make the previous example work as expected:

  1. >>> @patch('sys.non_existing_attribute', 42, create=True)
  2. ... def test(mock_stdout):
  3. ... assert sys.non_existing_attribute == 42
  4. ...
  5. >>> test()

在 3.8 版更改: patch() now returns an AsyncMock if the target is an async function.

patch.object

patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, \*kwargs*)

patch the named member (attribute) on an object (target) with a mock object.

patch.object() can be used as a decorator, class decorator or a context manager. Arguments new, spec, create, spec_set, autospec and new_callable have the same meaning as for patch(). Like patch(), patch.object() takes arbitrary keyword arguments for configuring the mock object it creates.

When used as a class decorator patch.object() honours patch.TEST_PREFIX for choosing which methods to wrap.

You can either call patch.object() with three arguments or two arguments. The three argument form takes the object to be patched, the attribute name and the object to replace the attribute with.

When calling with the two argument form you omit the replacement object, and a mock is created for you and passed in as an extra argument to the decorated function:

  1. >>> @patch.object(SomeClass, 'class_method')
  2. ... def test(mock_method):
  3. ... SomeClass.class_method(3)
  4. ... mock_method.assert_called_with(3)
  5. ...
  6. >>> test()

spec, create and the other arguments to patch.object() have the same meaning as they do for patch().

patch.dict

patch.dict(in_dict, values=(), clear=False, \*kwargs*)

Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test.

in_dict can be a dictionary or a mapping like container. If it is a mapping then it must at least support getting, setting and deleting items plus iterating over keys.

in_dict can also be a string specifying the name of the dictionary, which will then be fetched by importing it.

values can be a dictionary of values to set in the dictionary. values can also be an iterable of (key, value) pairs.

If clear is true then the dictionary will be cleared before the new values are set.

patch.dict() can also be called with arbitrary keyword arguments to set values in the dictionary.

在 3.8 版更改: patch.dict() now returns the patched dictionary when used as a context manager.

patch.dict() can be used as a context manager, decorator or class decorator:

  1. >>> foo = {}
  2. >>> @patch.dict(foo, {'newkey': 'newvalue'})
  3. ... def test():
  4. ... assert foo == {'newkey': 'newvalue'}
  5. >>> test()
  6. >>> assert foo == {}

When used as a class decorator patch.dict() honours patch.TEST_PREFIX (default to 'test') for choosing which methods to wrap:

  1. >>> import os
  2. >>> import unittest
  3. >>> from unittest.mock import patch
  4. >>> @patch.dict('os.environ', {'newkey': 'newvalue'})
  5. ... class TestSample(unittest.TestCase):
  6. ... def test_sample(self):
  7. ... self.assertEqual(os.environ['newkey'], 'newvalue')

If you want to use a different prefix for your test, you can inform the patchers of the different prefix by setting patch.TEST_PREFIX. For more details about how to change the value of see TEST_PREFIX.

patch.dict() can be used to add members to a dictionary, or simply let a test change a dictionary, and ensure the dictionary is restored when the test ends.

  1. >>> foo = {}
  2. >>> with patch.dict(foo, {'newkey': 'newvalue'}) as patched_foo:
  3. ... assert foo == {'newkey': 'newvalue'}
  4. ... assert patched_foo == {'newkey': 'newvalue'}
  5. ... # You can add, update or delete keys of foo (or patched_foo, it's the same dict)
  6. ... patched_foo['spam'] = 'eggs'
  7. ...
  8. >>> assert foo == {}
  9. >>> assert patched_foo == {}
  1. >>> import os
  2. >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
  3. ... print(os.environ['newkey'])
  4. ...
  5. newvalue
  6. >>> assert 'newkey' not in os.environ

Keywords can be used in the patch.dict() call to set values in the dictionary:

  1. >>> mymodule = MagicMock()
  2. >>> mymodule.function.return_value = 'fish'
  3. >>> with patch.dict('sys.modules', mymodule=mymodule):
  4. ... import mymodule
  5. ... mymodule.function('some', 'args')
  6. ...
  7. 'fish'

patch.dict() can be used with dictionary like objects that aren’t actually dictionaries. At the very minimum they must support item getting, setting, deleting and either iteration or membership test. This corresponds to the magic methods __getitem__(), __setitem__(), __delitem__() and either __iter__() or __contains__().

  1. >>> class Container:
  2. ... def __init__(self):
  3. ... self.values = {}
  4. ... def __getitem__(self, name):
  5. ... return self.values[name]
  6. ... def __setitem__(self, name, value):
  7. ... self.values[name] = value
  8. ... def __delitem__(self, name):
  9. ... del self.values[name]
  10. ... def __iter__(self):
  11. ... return iter(self.values)
  12. ...
  13. >>> thing = Container()
  14. >>> thing['one'] = 1
  15. >>> with patch.dict(thing, one=2, two=3):
  16. ... assert thing['one'] == 2
  17. ... assert thing['two'] == 3
  18. ...
  19. >>> assert thing['one'] == 1
  20. >>> assert list(thing) == ['one']

patch.multiple

patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, \*kwargs*)

Perform multiple patches in a single call. It takes the object to be patched (either as an object or a string to fetch the object by importing) and keyword arguments for the patches:

  1. with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
  2. ...

Use DEFAULT as the value if you want patch.multiple() to create mocks for you. In this case the created mocks are passed into a decorated function by keyword, and a dictionary is returned when patch.multiple() is used as a context manager.

patch.multiple() can be used as a decorator, class decorator or a context manager. The arguments spec, spec_set, create, autospec and new_callable have the same meaning as for patch(). These arguments will be applied to all patches done by patch.multiple().

When used as a class decorator patch.multiple() honours patch.TEST_PREFIX for choosing which methods to wrap.

If you want patch.multiple() to create mocks for you, then you can use DEFAULT as the value. If you use patch.multiple() as a decorator then the created mocks are passed into the decorated function by keyword.

  1. >>> thing = object()
  2. >>> other = object()
  3. >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
  4. ... def test_function(thing, other):
  5. ... assert isinstance(thing, MagicMock)
  6. ... assert isinstance(other, MagicMock)
  7. ...
  8. >>> test_function()

patch.multiple() can be nested with other patch decorators, but put arguments passed by keyword after any of the standard arguments created by patch():

  1. >>> @patch('sys.exit')
  2. ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
  3. ... def test_function(mock_exit, other, thing):
  4. ... assert 'other' in repr(other)
  5. ... assert 'thing' in repr(thing)
  6. ... assert 'exit' in repr(mock_exit)
  7. ...
  8. >>> test_function()

If patch.multiple() is used as a context manager, the value returned by the context manager is a dictionary where created mocks are keyed by name:

  1. >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
  2. ... assert 'other' in repr(values['other'])
  3. ... assert 'thing' in repr(values['thing'])
  4. ... assert values['thing'] is thing
  5. ... assert values['other'] is other
  6. ...

patch methods: start and stop

All the patchers have start() and stop() methods. These make it simpler to do patching in setUp methods or where you want to do multiple patches without nesting decorators or with statements.

To use them call patch(), patch.object() or patch.dict() as normal and keep a reference to the returned patcher object. You can then call start() to put the patch in place and stop() to undo it.

If you are using patch() to create a mock for you then it will be returned by the call to patcher.start.

  1. >>> patcher = patch('package.module.ClassName')
  2. >>> from package import module
  3. >>> original = module.ClassName
  4. >>> new_mock = patcher.start()
  5. >>> assert module.ClassName is not original
  6. >>> assert module.ClassName is new_mock
  7. >>> patcher.stop()
  8. >>> assert module.ClassName is original
  9. >>> assert module.ClassName is not new_mock

A typical use case for this might be for doing multiple patches in the setUp method of a TestCase:

  1. >>> class MyTest(unittest.TestCase):
  2. ... def setUp(self):
  3. ... self.patcher1 = patch('package.module.Class1')
  4. ... self.patcher2 = patch('package.module.Class2')
  5. ... self.MockClass1 = self.patcher1.start()
  6. ... self.MockClass2 = self.patcher2.start()
  7. ...
  8. ... def tearDown(self):
  9. ... self.patcher1.stop()
  10. ... self.patcher2.stop()
  11. ...
  12. ... def test_something(self):
  13. ... assert package.module.Class1 is self.MockClass1
  14. ... assert package.module.Class2 is self.MockClass2
  15. ...
  16. >>> MyTest('test_something').run()

警告

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

  1. >>> class MyTest(unittest.TestCase):
  2. ... def setUp(self):
  3. ... patcher = patch('package.module.Class')
  4. ... self.MockClass = patcher.start()
  5. ... self.addCleanup(patcher.stop)
  6. ...
  7. ... def test_something(self):
  8. ... assert package.module.Class is self.MockClass
  9. ...

As an added bonus you no longer need to keep a reference to the patcher object.

It is also possible to stop all patches which have been started by using patch.stopall().

patch.stopall()

Stop all active patches. Only stops patches started with start.

patch builtins

You can patch any builtins within a module. The following example patches builtin ord():

  1. >>> @patch('__main__.ord')
  2. ... def test(mock_ord):
  3. ... mock_ord.return_value = 101
  4. ... print(ord('c'))
  5. ...
  6. >>> test()
  7. 101

TEST_PREFIX

All of the patchers can be used as class decorators. When used in this way they wrap every test method on the class. The patchers recognise methods that start with 'test' as being test methods. This is the same way that the unittest.TestLoader finds test methods by default.

It is possible that you want to use a different prefix for your tests. You can inform the patchers of the different prefix by setting patch.TEST_PREFIX:

  1. >>> patch.TEST_PREFIX = 'foo'
  2. >>> value = 3
  3. >>>
  4. >>> @patch('__main__.value', 'not three')
  5. ... class Thing:
  6. ... def foo_one(self):
  7. ... print(value)
  8. ... def foo_two(self):
  9. ... print(value)
  10. ...
  11. >>>
  12. >>> Thing().foo_one()
  13. not three
  14. >>> Thing().foo_two()
  15. not three
  16. >>> value
  17. 3

Nesting Patch Decorators

If you want to perform multiple patches then you can simply stack up the decorators.

You can stack up multiple patch decorators using this pattern:

  1. >>> @patch.object(SomeClass, 'class_method')
  2. ... @patch.object(SomeClass, 'static_method')
  3. ... def test(mock1, mock2):
  4. ... assert SomeClass.static_method is mock1
  5. ... assert SomeClass.class_method is mock2
  6. ... SomeClass.static_method('foo')
  7. ... SomeClass.class_method('bar')
  8. ... return mock1, mock2
  9. ...
  10. >>> mock1, mock2 = test()
  11. >>> mock1.assert_called_once_with('foo')
  12. >>> mock2.assert_called_once_with('bar')

Note that the decorators are applied from the bottom upwards. This is the standard way that Python applies decorators. The order of the created mocks passed into your test function matches this order.

Where to patch

patch() works by (temporarily) changing the object that a name points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.

The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined. A couple of examples will help to clarify this.

Imagine we have a project that we want to test with the following structure:

  1. a.py
  2. -> Defines SomeClass
  3. b.py
  4. -> from a import SomeClass
  5. -> some_function instantiates SomeClass

Now we want to test some_function but we want to mock out SomeClass using patch(). The problem is that when we import module b, which we will have to do then it imports SomeClass from module a. If we use patch() to mock out a.SomeClass then it will have no effect on our test; module b already has a reference to the real SomeClass and it looks like our patching had no effect.

The key is to patch out SomeClass where it is used (or where it is looked up). In this case some_function will actually look up SomeClass in module b, where we have imported it. The patching should look like:

  1. @patch('b.SomeClass')

However, consider the alternative scenario where instead of from a import SomeClass module b does import a and some_function uses a.SomeClass. Both of these import forms are common. In this case the class we want to patch is being looked up in the module and so we have to patch a.SomeClass instead:

  1. @patch('a.SomeClass')

Patching Descriptors and Proxy Objects

Both patch and patch.object correctly patch and restore descriptors: class methods, static methods and properties. You should patch these on the class rather than an instance. They also work with some objects that proxy attribute access, like the django settings object.

MagicMock and magic method support

Mocking Magic Methods

Mock supports mocking the Python protocol methods, also known as “magic methods”. This allows mock objects to replace containers or other objects that implement Python protocols.

Because magic methods are looked up differently from normal methods 2, this support has been specially implemented. This means that only specific magic methods are supported. The supported list includes almost all of them. If there are any missing that you need please let us know.

You mock magic methods by setting the method you are interested in to a function or a mock instance. If you are using a function then it must take self as the first argument 3.

  1. >>> def __str__(self):
  2. ... return 'fooble'
  3. ...
  4. >>> mock = Mock()
  5. >>> mock.__str__ = __str__
  6. >>> str(mock)
  7. 'fooble'
  1. >>> mock = Mock()
  2. >>> mock.__str__ = Mock()
  3. >>> mock.__str__.return_value = 'fooble'
  4. >>> str(mock)
  5. 'fooble'
  1. >>> mock = Mock()
  2. >>> mock.__iter__ = Mock(return_value=iter([]))
  3. >>> list(mock)
  4. []

One use case for this is for mocking objects used as context managers in a with statement:

  1. >>> mock = Mock()
  2. >>> mock.__enter__ = Mock(return_value='foo')
  3. >>> mock.__exit__ = Mock(return_value=False)
  4. >>> with mock as m:
  5. ... assert m == 'foo'
  6. ...
  7. >>> mock.__enter__.assert_called_with()
  8. >>> mock.__exit__.assert_called_with(None, None, None)

Calls to magic methods do not appear in method_calls, but they are recorded in mock_calls.

注解

If you use the spec keyword argument to create a mock then attempting to set a magic method that isn’t in the spec will raise an AttributeError.

The full list of supported magic methods is:

  • __hash__, __sizeof__, __repr__ and __str__

  • __dir__, __format__ and __subclasses__

  • __round__, __floor__, __trunc__ and __ceil__

  • Comparisons: __lt__, __gt__, __le__, __ge__, __eq__ and __ne__

  • Container methods: __getitem__, __setitem__, __delitem__, __contains__, __len__, __iter__, __reversed__ and __missing__

  • Context manager: __enter__, __exit__, __aenter__ and __aexit__

  • Unary numeric methods: __neg__, __pos__ and __invert__

  • The numeric methods (including right hand and in-place variants): __add__, __sub__, __mul__, __matmul__, __div__, __truediv__, __floordiv__, __mod__, __divmod__, __lshift__, __rshift__, __and__, __xor__, __or__, and __pow__

  • Numeric conversion methods: __complex__, __int__, __float__ and __index__

  • Descriptor methods: __get__, __set__ and __delete__

  • Pickling: __reduce__, __reduce_ex__, __getinitargs__, __getnewargs__, __getstate__ and __setstate__

  • File system path representation: __fspath__

  • Asynchronous iteration methods: __aiter__ and __anext__

在 3.8 版更改: Added support for os.PathLike.__fspath__().

在 3.8 版更改: Added support for __aenter__, __aexit__, __aiter__ and __anext__.

The following methods exist but are not supported as they are either in use by mock, can’t be set dynamically, or can cause problems:

  • __getattr__, __setattr__, __init__ and __new__

  • __prepare__, __instancecheck__, __subclasscheck__, __del__

Magic Mock

There are two MagicMock variants: MagicMock and NonCallableMagicMock.

class unittest.mock.MagicMock(\args, **kw*)

MagicMock is a subclass of Mock with default implementations of most of the magic methods. You can use MagicMock without having to configure the magic methods yourself.

The constructor parameters have the same meaning as for Mock.

If you use the spec or spec_set arguments then only magic methods that exist in the spec will be created.

class unittest.mock.NonCallableMagicMock(\args, **kw*)

A non-callable version of MagicMock.

The constructor parameters have the same meaning as for MagicMock, with the exception of return_value and side_effect which have no meaning on a non-callable mock.

The magic methods are setup with MagicMock objects, so you can configure them and use them in the usual way:

  1. >>> mock = MagicMock()
  2. >>> mock[3] = 'fish'
  3. >>> mock.__setitem__.assert_called_with(3, 'fish')
  4. >>> mock.__getitem__.return_value = 'result'
  5. >>> mock[2]
  6. 'result'

By default many of the protocol methods are required to return objects of a specific type. These methods are preconfigured with a default return value, so that they can be used without you having to do anything if you aren’t interested in the return value. You can still set the return value manually if you want to change the default.

Methods and their defaults:

  • __lt__: NotImplemented

  • __gt__: NotImplemented

  • __le__: NotImplemented

  • __ge__: NotImplemented

  • __int__: 1

  • __contains__: False

  • __len__: 0

  • __iter__: iter([])

  • __exit__: False

  • __aexit__: False

  • __complex__: 1j

  • __float__: 1.0

  • __bool__: True

  • __index__: 1

  • __hash__: default hash for the mock

  • __str__: default str for the mock

  • __sizeof__: default sizeof for the mock

例如:

  1. >>> mock = MagicMock()
  2. >>> int(mock)
  3. 1
  4. >>> len(mock)
  5. 0
  6. >>> list(mock)
  7. []
  8. >>> object() in mock
  9. False

The two equality methods, __eq__() and __ne__(), are special. They do the default equality comparison on identity, using the side_effect attribute, unless you change their return value to return something else:

  1. >>> MagicMock() == 3
  2. False
  3. >>> MagicMock() != 3
  4. True
  5. >>> mock = MagicMock()
  6. >>> mock.__eq__.return_value = True
  7. >>> mock == 3
  8. True

The return value of MagicMock.__iter__() can be any iterable object and isn’t required to be an iterator:

  1. >>> mock = MagicMock()
  2. >>> mock.__iter__.return_value = ['a', 'b', 'c']
  3. >>> list(mock)
  4. ['a', 'b', 'c']
  5. >>> list(mock)
  6. ['a', 'b', 'c']

If the return value is an iterator, then iterating over it once will consume it and subsequent iterations will result in an empty list:

  1. >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
  2. >>> list(mock)
  3. ['a', 'b', 'c']
  4. >>> list(mock)
  5. []

MagicMock has all of the supported magic methods configured except for some of the obscure and obsolete ones. You can still set these up if you want.

Magic methods that are supported but not setup by default in MagicMock are:

  • __subclasses__

  • __dir__

  • __format__

  • __get__, __set__ and __delete__

  • __reversed__ and __missing__

  • __reduce__, __reduce_ex__, __getinitargs__, __getnewargs__, __getstate__ and __setstate__

  • __getformat__ and __setformat__

2

Magic methods should be looked up on the class rather than the instance. Different versions of Python are inconsistent about applying this rule. The supported protocol methods should work with all supported versions of Python.

3

The function is basically hooked up to the class, but each Mock instance is kept isolated from the others.

Helpers

sentinel

unittest.mock.sentinel

The sentinel object provides a convenient way of providing unique objects for your tests.

Attributes are created on demand when you access them by name. Accessing the same attribute will always return the same object. The objects returned have a sensible repr so that test failure messages are readable.

在 3.7 版更改: The sentinel attributes now preserve their identity when they are copied or pickled.

Sometimes when testing you need to test that a specific object is passed as an argument to another method, or returned. It can be common to create named sentinel objects to test this. sentinel provides a convenient way of creating and testing the identity of objects like this.

In this example we monkey patch method to return sentinel.some_object:

  1. >>> real = ProductionClass()
  2. >>> real.method = Mock(name="method")
  3. >>> real.method.return_value = sentinel.some_object
  4. >>> result = real.method()
  5. >>> assert result is sentinel.some_object
  6. >>> sentinel.some_object
  7. sentinel.some_object

DEFAULT

unittest.mock.DEFAULT

The DEFAULT object is a pre-created sentinel (actually sentinel.DEFAULT). It can be used by side_effect functions to indicate that the normal return value should be used.

call

unittest.mock.call(\args, **kwargs*)

call() is a helper object for making simpler assertions, for comparing with call_args, call_args_list, mock_calls and method_calls. call() can also be used with assert_has_calls().

  1. >>> m = MagicMock(return_value=None)
  2. >>> m(1, 2, a='foo', b='bar')
  3. >>> m()
  4. >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
  5. True

call.call_list()

For a call object that represents multiple calls, call_list() returns a list of all the intermediate calls as well as the final call.

call_list is particularly useful for making assertions on “chained calls”. A chained call is multiple calls on a single line of code. This results in multiple entries in mock_calls on a mock. Manually constructing the sequence of calls can be tedious.

call_list() can construct the sequence of calls from the same chained call:

  1. >>> m = MagicMock()
  2. >>> m(1).method(arg='foo').other('bar')(2.0)
  3. <MagicMock name='mock().method().other()()' id='...'>
  4. >>> kall = call(1).method(arg='foo').other('bar')(2.0)
  5. >>> kall.call_list()
  6. [call(1),
  7. call().method(arg='foo'),
  8. call().method().other('bar'),
  9. call().method().other()(2.0)]
  10. >>> m.mock_calls == kall.call_list()
  11. True

A call object is either a tuple of (positional args, keyword args) or (name, positional args, keyword args) depending on how it was constructed. When you construct them yourself this isn’t particularly interesting, but the call objects that are in the Mock.call_args, Mock.call_args_list and Mock.mock_calls attributes can be introspected to get at the individual arguments they contain.

The call objects in Mock.call_args and Mock.call_args_list are two-tuples of (positional args, keyword args) whereas the call objects in Mock.mock_calls, along with ones you construct yourself, are three-tuples of (name, positional args, keyword args).

You can use their “tupleness” to pull out the individual arguments for more complex introspection and assertions. The positional arguments are a tuple (an empty tuple if there are no positional arguments) and the keyword arguments are a dictionary:

  1. >>> m = MagicMock(return_value=None)
  2. >>> m(1, 2, 3, arg='one', arg2='two')
  3. >>> kall = m.call_args
  4. >>> kall.args
  5. (1, 2, 3)
  6. >>> kall.kwargs
  7. {'arg': 'one', 'arg2': 'two'}
  8. >>> kall.args is kall[0]
  9. True
  10. >>> kall.kwargs is kall[1]
  11. True
  1. >>> m = MagicMock()
  2. >>> m.foo(4, 5, 6, arg='two', arg2='three')
  3. <MagicMock name='mock.foo()' id='...'>
  4. >>> kall = m.mock_calls[0]
  5. >>> name, args, kwargs = kall
  6. >>> name
  7. 'foo'
  8. >>> args
  9. (4, 5, 6)
  10. >>> kwargs
  11. {'arg': 'two', 'arg2': 'three'}
  12. >>> name is m.mock_calls[0][0]
  13. True

create_autospec

unittest.mock.create_autospec(spec, spec_set=False, instance=False, \*kwargs*)

Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the spec object as their spec.

Functions or methods being mocked will have their arguments checked to ensure that they are called with the correct signature.

If spec_set is True then attempting to set attributes that don’t exist on the spec object will raise an AttributeError.

If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec. You can use a class as the spec for an instance object by passing instance=True. The returned mock will only be callable if instances of the mock are callable.

create_autospec() also takes arbitrary keyword arguments that are passed to the constructor of the created mock.

See Autospeccing for examples of how to use auto-speccing with create_autospec() and the autospec argument to patch().

在 3.8 版更改: create_autospec() now returns an AsyncMock if the target is an async function.

ANY

unittest.mock.ANY

Sometimes you may need to make assertions about some of the arguments in a call to mock, but either not care about some of the arguments or want to pull them individually out of call_args and make more complex assertions on them.

To ignore certain arguments you can pass in objects that compare equal to everything. Calls to assert_called_with() and assert_called_once_with() will then succeed no matter what was passed in.

  1. >>> mock = Mock(return_value=None)
  2. >>> mock('foo', bar=object())
  3. >>> mock.assert_called_once_with('foo', bar=ANY)

ANY can also be used in comparisons with call lists like mock_calls:

  1. >>> m = MagicMock(return_value=None)
  2. >>> m(1)
  3. >>> m(1, 2)
  4. >>> m(object())
  5. >>> m.mock_calls == [call(1), call(1, 2), ANY]
  6. True

FILTER_DIR

unittest.mock.FILTER_DIR

FILTER_DIR is a module level variable that controls the way mock objects respond to dir() (only for Python 2.6 or more recent). The default is True, which uses the filtering described below, to only show useful members. If you dislike this filtering, or need to switch it off for diagnostic purposes, then set mock.FILTER_DIR = False.

With filtering on, dir(some_mock) shows only useful attributes and will include any dynamically created attributes that wouldn’t normally be shown. If the mock was created with a spec (or autospec of course) then all the attributes from the original are shown, even if they haven’t been accessed yet:

  1. >>> dir(Mock())
  2. ['assert_any_call',
  3. 'assert_called',
  4. 'assert_called_once',
  5. 'assert_called_once_with',
  6. 'assert_called_with',
  7. 'assert_has_calls',
  8. 'assert_not_called',
  9. 'attach_mock',
  10. ...
  11. >>> from urllib import request
  12. >>> dir(Mock(spec=request))
  13. ['AbstractBasicAuthHandler',
  14. 'AbstractDigestAuthHandler',
  15. 'AbstractHTTPHandler',
  16. 'BaseHandler',
  17. ...

Many of the not-very-useful (private to Mock rather than the thing being mocked) underscore and double underscore prefixed attributes have been filtered from the result of calling dir() on a Mock. If you dislike this behaviour you can switch it off by setting the module level switch FILTER_DIR:

  1. >>> from unittest import mock
  2. >>> mock.FILTER_DIR = False
  3. >>> dir(mock.Mock())
  4. ['_NonCallableMock__get_return_value',
  5. '_NonCallableMock__get_side_effect',
  6. '_NonCallableMock__return_value_doc',
  7. '_NonCallableMock__set_return_value',
  8. '_NonCallableMock__set_side_effect',
  9. '__call__',
  10. '__class__',
  11. ...

Alternatively you can just use vars(my_mock) (instance members) and dir(type(my_mock)) (type members) to bypass the filtering irrespective of mock.FILTER_DIR.

mock_open

unittest.mock.mock_open(mock=None, read_data=None)

A helper function to create a mock to replace the use of open(). It works for open() called directly or used as a context manager.

The mock argument is the mock object to configure. If None (the default) then a MagicMock will be created for you, with the API limited to methods or attributes available on standard file handles.

read_data is a string for the read(), readline(), and readlines() methods of the file handle to return. Calls to those methods will take data from read_data until it is depleted. The mock of these methods is pretty simplistic: every time the mock is called, the read_data is rewound to the start. If you need more control over the data that you are feeding to the tested code you will need to customize this mock for yourself. When that is insufficient, one of the in-memory filesystem packages on PyPI can offer a realistic filesystem for testing.

在 3.4 版更改: Added readline() and readlines() support. The mock of read() changed to consume read_data rather than returning it on each call.

在 3.5 版更改: read_data is now reset on each call to the mock.

在 3.8 版更改: Added __iter__() to implementation so that iteration (such as in for loops) correctly consumes read_data.

Using open() as a context manager is a great way to ensure your file handles are closed properly and is becoming common:

  1. with open('/some/path', 'w') as f:
  2. f.write('something')

The issue is that even if you mock out the call to open() it is the returned object that is used as a context manager (and has __enter__() and __exit__() called).

Mocking context managers with a MagicMock is common enough and fiddly enough that a helper function is useful.

  1. >>> m = mock_open()
  2. >>> with patch('__main__.open', m):
  3. ... with open('foo', 'w') as h:
  4. ... h.write('some stuff')
  5. ...
  6. >>> m.mock_calls
  7. [call('foo', 'w'),
  8. call().__enter__(),
  9. call().write('some stuff'),
  10. call().__exit__(None, None, None)]
  11. >>> m.assert_called_once_with('foo', 'w')
  12. >>> handle = m()
  13. >>> handle.write.assert_called_once_with('some stuff')

And for reading files:

  1. >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
  2. ... with open('foo') as h:
  3. ... result = h.read()
  4. ...
  5. >>> m.assert_called_once_with('foo')
  6. >>> assert result == 'bibble'

Autospeccing

Autospeccing is based on the existing spec feature of mock. It limits the api of mocks to the api of an original object (the spec), but it is recursive (implemented lazily) so that attributes of mocks only have the same api as the attributes of the spec. In addition mocked functions / methods have the same call signature as the original so they raise a TypeError if they are called incorrectly.

Before I explain how auto-speccing works, here’s why it is needed.

Mock is a very powerful and flexible object, but it suffers from two flaws when used to mock out objects from a system under test. One of these flaws is specific to the Mock api and the other is a more general problem with using mock objects.

First the problem specific to Mock. Mock has two assert methods that are extremely handy: assert_called_with() and assert_called_once_with().

  1. >>> mock = Mock(name='Thing', return_value=None)
  2. >>> mock(1, 2, 3)
  3. >>> mock.assert_called_once_with(1, 2, 3)
  4. >>> mock(1, 2, 3)
  5. >>> mock.assert_called_once_with(1, 2, 3)
  6. Traceback (most recent call last):
  7. ...
  8. AssertionError: Expected 'mock' to be called once. Called 2 times.

Because mocks auto-create attributes on demand, and allow you to call them with arbitrary arguments, if you misspell one of these assert methods then your assertion is gone:

  1. >>> mock = Mock(name='Thing', return_value=None)
  2. >>> mock(1, 2, 3)
  3. >>> mock.assret_called_once_with(4, 5, 6)

Your tests can pass silently and incorrectly because of the typo.

The second issue is more general to mocking. If you refactor some of your code, rename members and so on, any tests for code that is still using the old api but uses mocks instead of the real objects will still pass. This means your tests can all pass even though your code is broken.

Note that this is another reason why you need integration tests as well as unit tests. Testing everything in isolation is all fine and dandy, but if you don’t test how your units are “wired together” there is still lots of room for bugs that tests might have caught.

mock already provides a feature to help with this, called speccing. If you use a class or instance as the spec for a mock then you can only access attributes on the mock that exist on the real class:

  1. >>> from urllib import request
  2. >>> mock = Mock(spec=request.Request)
  3. >>> mock.assret_called_with
  4. Traceback (most recent call last):
  5. ...
  6. AttributeError: Mock object has no attribute 'assret_called_with'

The spec only applies to the mock itself, so we still have the same issue with any methods on the mock:

  1. >>> mock.has_data()
  2. <mock.Mock object at 0x...>
  3. >>> mock.has_data.assret_called_with()

Auto-speccing solves this problem. You can either pass autospec=True to patch() / patch.object() or use the create_autospec() function to create a mock with a spec. If you use the autospec=True argument to patch() then the object that is being replaced will be used as the spec object. Because the speccing is done “lazily” (the spec is created as attributes on the mock are accessed) you can use it with very complex or deeply nested objects (like modules that import modules that import modules) without a big performance hit.

Here’s an example of it in use:

  1. >>> from urllib import request
  2. >>> patcher = patch('__main__.request', autospec=True)
  3. >>> mock_request = patcher.start()
  4. >>> request is mock_request
  5. True
  6. >>> mock_request.Request
  7. <MagicMock name='request.Request' spec='Request' id='...'>

You can see that request.Request has a spec. request.Request takes two arguments in the constructor (one of which is self). Here’s what happens if we try to call it incorrectly:

  1. >>> req = request.Request()
  2. Traceback (most recent call last):
  3. ...
  4. TypeError: <lambda>() takes at least 2 arguments (1 given)

The spec also applies to instantiated classes (i.e. the return value of specced mocks):

  1. >>> req = request.Request('foo')
  2. >>> req
  3. <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>

Request objects are not callable, so the return value of instantiating our mocked out request.Request is a non-callable mock. With the spec in place any typos in our asserts will raise the correct error:

  1. >>> req.add_header('spam', 'eggs')
  2. <MagicMock name='request.Request().add_header()' id='...'>
  3. >>> req.add_header.assret_called_with
  4. Traceback (most recent call last):
  5. ...
  6. AttributeError: Mock object has no attribute 'assret_called_with'
  7. >>> req.add_header.assert_called_with('spam', 'eggs')

In many cases you will just be able to add autospec=True to your existing patch() calls and then be protected against bugs due to typos and api changes.

As well as using autospec through patch() there is a create_autospec() for creating autospecced mocks directly:

  1. >>> from urllib import request
  2. >>> mock_request = create_autospec(request)
  3. >>> mock_request.Request('foo', 'bar')
  4. <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>

This isn’t without caveats and limitations however, which is why it is not the default behaviour. In order to know what attributes are available on the spec object, autospec has to introspect (access attributes) the spec. As you traverse attributes on the mock a corresponding traversal of the original object is happening under the hood. If any of your specced objects have properties or descriptors that can trigger code execution then you may not be able to use autospec. On the other hand it is much better to design your objects so that introspection is safe 4.

A more serious problem is that it is common for instance attributes to be created in the __init__() method and not to exist on the class at all. autospec can’t know about any dynamically created attributes and restricts the api to visible attributes.

  1. >>> class Something:
  2. ... def __init__(self):
  3. ... self.a = 33
  4. ...
  5. >>> with patch('__main__.Something', autospec=True):
  6. ... thing = Something()
  7. ... thing.a
  8. ...
  9. Traceback (most recent call last):
  10. ...
  11. AttributeError: Mock object has no attribute 'a'

There are a few different ways of resolving this problem. The easiest, but not necessarily the least annoying, way is to simply set the required attributes on the mock after creation. Just because autospec doesn’t allow you to fetch attributes that don’t exist on the spec it doesn’t prevent you setting them:

  1. >>> with patch('__main__.Something', autospec=True):
  2. ... thing = Something()
  3. ... thing.a = 33
  4. ...

There is a more aggressive version of both spec and autospec that does prevent you setting non-existent attributes. This is useful if you want to ensure your code only sets valid attributes too, but obviously it prevents this particular scenario:

  1. >>> with patch('__main__.Something', autospec=True, spec_set=True):
  2. ... thing = Something()
  3. ... thing.a = 33
  4. ...
  5. Traceback (most recent call last):
  6. ...
  7. AttributeError: Mock object has no attribute 'a'

Probably the best way of solving the problem is to add class attributes as default values for instance members initialised in __init__(). Note that if you are only setting default attributes in __init__() then providing them via class attributes (shared between instances of course) is faster too. e.g.

  1. class Something:
  2. a = 33

This brings up another issue. It is relatively common to provide a default value of None for members that will later be an object of a different type. None would be useless as a spec because it wouldn’t let you access any attributes or methods on it. As None is never going to be useful as a spec, and probably indicates a member that will normally of some other type, autospec doesn’t use a spec for members that are set to None. These will just be ordinary mocks (well - MagicMocks):

  1. >>> class Something:
  2. ... member = None
  3. ...
  4. >>> mock = create_autospec(Something)
  5. >>> mock.member.foo.bar.baz()
  6. <MagicMock name='mock.member.foo.bar.baz()' id='...'>

If modifying your production classes to add defaults isn’t to your liking then there are more options. One of these is simply to use an instance as the spec rather than the class. The other is to create a subclass of the production class and add the defaults to the subclass without affecting the production class. Both of these require you to use an alternative object as the spec. Thankfully patch() supports this - you can simply pass the alternative object as the autospec argument:

  1. >>> class Something:
  2. ... def __init__(self):
  3. ... self.a = 33
  4. ...
  5. >>> class SomethingForTest(Something):
  6. ... a = 33
  7. ...
  8. >>> p = patch('__main__.Something', autospec=SomethingForTest)
  9. >>> mock = p.start()
  10. >>> mock.a
  11. <NonCallableMagicMock name='Something.a' spec='int' id='...'>

4

This only applies to classes or already instantiated objects. Calling a mocked class to create a mock instance does not create a real instance. It is only attribute lookups - along with calls to dir() - that are done.

Sealing mocks

unittest.mock.seal(mock)

Seal will disable the automatic creation of mocks when accessing an attribute of the mock being sealed or any of its attributes that are already mocks recursively.

If a mock instance with a name or a spec is assigned to an attribute it won’t be considered in the sealing chain. This allows one to prevent seal from fixing part of the mock object.

  1. >>> mock = Mock()
  2. >>> mock.submock.attribute1 = 2
  3. >>> mock.not_submock = mock.Mock(name="sample_name")
  4. >>> seal(mock)
  5. >>> mock.new_attribute # This will raise AttributeError.
  6. >>> mock.submock.attribute2 # This will raise AttributeError.
  7. >>> mock.not_submock.attribute2 # This won't raise.

3.7 新版功能.