查找子对象的父模拟对象,paren的子模拟对象

2024-04-16 13:44:35 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以标识子模拟对象实例的父级^{}模拟对象实例,或父级模拟对象实例的子级?例如,如果我有以下代码

>>> from unittest.mock import MagicMock
>>> parent_mock = MagicMock()
>>> child_mock1 = parent_mock(a=1)
>>> child_mock2 = parent_mock(b='spam')

我以后如何确认调用parent_mock生成了子模拟?如何检查parent_mock生成了哪些模拟对象?在

另外,我如何区分child_mock1来自调用parent_mock(a=1),而{}来自调用{}?在

我知道一个人可以manually attach mocks as attributes of other mocks,但是,它需要大量的设置,因为您需要确保显式定义父mock的返回调用,以便它返回指定的子mock,因此它不能扩展到几个调用之后。在


Tags: 对象实例代码fromimportchildunittestmock
2条回答

小心点!在

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

如果你想让不同的调用得到不同的结果,你需要给你的模拟一个^{}属性。如果mock.side_effect是一个函数,那么mock(*args, **kwargs)将调用mock.side_effect(*args, **kwargs)并返回返回的任何内容。您可以让您的自定义mock.side_effect跟踪哪些调用产生了什么值。在

How could I confirm later that the child mocks spawned from calling 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来跟踪它的子类。。。在

^{pr2}$

…那你就可以。。。在

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

相关问题 更多 >