【发布时间】:2022-02-02 01:59:57
【问题描述】:
我在一个类上有一个长期存在的补丁,它的实例经历了多批断言。场景请看下面的代码sn-p。
它暴露了MagicMock.reset_mock 中的(我认为很烦人的)行为,它似乎在子MagicMock 中创建了一个新的MagicMock:
from unittest.mock import MagicMock
mock_cls = MagicMock()
mock_cls.return_value.method.side_effect = [5]
instance = mock_cls()
# Batch 1 of usage: uses side_effect
assert instance.method() == 5
mock_cls.reset_mock(return_value=True, side_effect=True)
# After this, mock_cls.return_value.method has a new id
# Batch 2 of usage: uses return_value
instance.return_value.method.return_value = 6
assert instance.method() == 6 # StopIteration
当使用 Python 3.10.2 运行时,它会引发 StopIteration:
Traceback (most recent call last):
File "/path/to/code/play/quick_play.py", line 9, in <module>
assert instance.method() == 6
File "/path/to/.pyenv/versions/3.10.2/lib/python3.10/unittest/mock.py", line 1104, in __call__
return self._mock_call(*args, **kwargs)
File "/path/to/.pyenv/versions/3.10.2/lib/python3.10/unittest/mock.py", line 1108, in _mock_call
return self._execute_mock_call(*args, **kwargs)
File "/path/to/.pyenv/versions/3.10.2/lib/python3.10/unittest/mock.py", line 1165, in _execute_mock_call
result = next(effect)
StopIteration
是否可以在不创建新的MagicMock 的情况下使用reset_mock?
或者,如何手动重置side_effect 以便 sn-p 运行?
一边
reset_mock 的签名中的 visited=None 参数是什么?它在3.10 docs 中没有记录,在这里
def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
【问题讨论】:
-
来自文档:“请注意,reset_mock() 不会清除返回值、副作用或任何子属性...”
-
@KlausD。因此 kwargs 传递给
reset_mock,阅读文档的接下来几句话
标签: python mocking python-unittest.mock magicmock