gpt4 book ai didi

python - 我们如何确保 Mock.call_args_list 中的调用包含参数与调用 Mock 对象时处于相同状态的调用?

转载 作者:行者123 更新时间:2023-12-03 00:10:11 25 4
gpt4 key购买 nike

from mock import Mock
j = []
u = Mock()
u(j)
# At this point u.call_args_list == [call([])]
print u.call_args_list
j.append(100)
# At this point u.call_args_list == [call([100])], but I expect it to be [call([])], since it was never called when j had a value of 100 in it
print u.call_args_list

我的问题是如何确保 u.call_args_list 中的调用包含调用模拟时而不是检查模拟参数时所有对象的状态?

我现在正在使用mock==1.0.1

最佳答案

这在文档部分 26.6.3.7. Coping with mutable arguments 中进行了讨论。

不幸的是,他们确实没有任何优雅的解决方案来解决这个问题!建议的解决方法是使用 side_effect 从可变参数中复制元素。

If you provide a side_effect function for a mock then side_effect will be called with the same args as the mock. This gives us an opportunity to copy the arguments and store them for later assertions.

在我看来,实现起来有点困惑。如果您在多个地方需要该功能,您可能更愿意继承 Mock 并直接添加该功能:

from copy import deepcopy

class CopyingMock(MagicMock):
def __call__(self, *args, **kwargs):
args = deepcopy(args)
kwargs = deepcopy(kwargs)
return super(CopyingMock, self).__call__(*args, **kwargs)
<小时/>

2017:现在可以在第三方发行版中使用(pip install copyingmock)。

>>> from copyingmock import CopyingMock
>>> mock = CopyingMock()
>>> list_ = [1,2]
>>> mock(list_)
<CopyingMock name='mock()' id='4366094008'>
>>> list_.append(3)
>>> mock.assert_called_once_with([1,2])
>>> mock.assert_called_once_with(list_)

AssertionError: Expected call: mock([1, 2, 3])
Actual call: mock([1, 2])

关于python - 我们如何确保 Mock.call_args_list 中的调用包含参数与调用 Mock 对象时处于相同状态的调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51032853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com