gpt4 book ai didi

python - 模拟 side_effect 迭代器用完后可以重置吗?

转载 作者:太空狗 更新时间:2023-10-29 21:05:43 27 4
gpt4 key购买 nike

mock.reset_mock() 不会重置副作用迭代器。有没有一种方法可以做到这一点而无需再次创建模拟?

>>> from mock import MagicMock
>>> mock = MagicMock(side_effect = [1,2])
>>> mock(), mock()
(1, 2)
>>> mock()

Traceback (most recent call last):
File "<pyshell#114>", line 1, in <module>
mock()
File "C:\Python27\Lib\site-packages\mock.py", line 955, in __call__
return _mock_self._mock_call(*args, **kwargs)
File "C:\Python27\Lib\site-packages\mock.py", line 1013, in _mock_call
result = next(effect)
StopIteration
>>> mock.reset_mock()
>>> mock()

Traceback (most recent call last):
...
StopIteration
>>> mock = MagicMock(side_effect = [1,2])
>>> mock(), mock()
(1, 2)
>>>

目的是在后续测试中重新使用模拟,但我怀疑它不能像生成器一样重新启动

所以(迟到总比不到好)在被指向正确的方向后,我查看了 mock.py 并发现 side_effect 是一个迭代器对象(不能是 < em>重置一旦耗尽):

def __set_side_effect(self, value):
value = _try_iter(value)
...

def _try_iter(obj):
...
try:
return iter(obj)
except TypeError:
# XXXX backwards compatibility
# but this will blow up on first call - so maybe we should fail early?
return obj

def reset_mock() 没有解决副作用。

最佳答案

正如 user2357112 评论的那样,重新分配 side_effect 将解决您的问题。

>>> from mock import MagicMock
>>>
>>> lst = [1, 2]
>>> mock = MagicMock(side_effect=lst)
>>> mock(), mock()
(1, 2)
>>> mock.side_effect = lst # <-------
>>> mock(), mock()
(1, 2)

关于python - 模拟 side_effect 迭代器用完后可以重置吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25826180/

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