我以后如何确认孩子嘲笑是从 call 中产生的parent_mock
?
好吧,有一个未记录的属性_mock_new_parent
,你可以像这样使用它......
>>> from unittest.mock import MagicMock
>>> parent_mock = MagicMock()
>>> child_mock1 = parent_mock(a=1)
>>> child_mock2 = parent_mock(b='spam')
>>> child_mock1._mock_new_parent is parent_mock
True
>>> child_mock2._mock_new_parent is parent_mock
True
...但看起来你所有其他问题的答案都是“你不能”。
我想你可以MagicMock
用这样的子类来跟踪它的孩子......
class MyMock(MagicMock):
def __init__(self, *args, **kwargs):
MagicMock.__init__(self, *args, **kwargs)
self._kids = []
def __call__(self, *args, **kwargs):
result = MagicMock.__call__(self, *args, **kwargs)
self._kids.append((args, kwargs, result))
return result
……那你可以……
>>> parent_mock = MyMock()
>>> child_mock1 = parent_mock(a=1)
>>> child_mock2 = parent_mock(b='spam')
>>> parent_mock._kids
[((), {'a': 1}, <MyMock name='mock()' id='140358357513616'>),
((), {'b': 'spam'}, <MyMock name='mock()' id='140358357513616'>)]
>>> parent_mock._kids[0][2] is child_mock1
True
>>> parent_mock._kids[1][2] is child_mock2
True