如果你看一下文件
lib/python3.7/unittest/mock.py
def __getattr__(self, name):
if name in {'_mock_methods', '_mock_unsafe'}:
raise AttributeError(name)
elif self._mock_methods is not None:
if name not in self._mock_methods or name in _all_magics:
raise AttributeError("Mock object has no attribute %r" % name)
elif _is_magic(name):
raise AttributeError(name)
if not self._mock_unsafe:
if name.startswith(('assert', 'assret')):
raise AttributeError(name)
result = self._mock_children.get(name)
if result is _deleted:
raise AttributeError(name)
elif result is None:
wraps = None
if self._mock_wraps is not None:
# XXXX should we get the attribute without triggering code
# execution?
wraps = getattr(self._mock_wraps, name)
result = self._get_child_mock(
parent=self, name=name, wraps=wraps, _new_name=name,
_new_parent=self
)
self._mock_children[name] = result
elif isinstance(result, _SpecState):
result = create_autospec(
result.spec, result.spec_set, result.instance,
result.parent, result.name
)
self._mock_children[name] = result
return result
如您所见,对象被缓存在
_mock_children
因此每个调用都会返回对象。但数据会更新。通过运行下面的代码可以看到
from unittest.mock import Mock
mock = Mock()
mock.a(10)
mock.a.assert_called_with(10)
mock.a(2)
mock.a.assert_called_with(10)
结果呢
Traceback (most recent call last):
File ".../workbench.py", line 8, in <module>
mock.a.assert_called_with(10)
File ....lib/python3.7/unittest/mock.py", line 834, in assert_called_with
raise AssertionError(_error_message()) from cause
AssertionError: Expected call: a(10)
Actual call: a(2)