我正在尝试重新创建mock_calls 示例,以便我可以检查预期的调用列表是否等于实际调用。但是,我收到一个NameError
例外,因为name 'call' is not defined
:
>>> from mock import MagicMock
>>> mock = MagicMock()
>>> result = mock(1, 2, 3)
>>> mock.first(a=3)
<MagicMock name='mock.first()' id='47645192'>
>>> mock.second()
<MagicMock name='mock.second()' id='47653440'>
>>> int(mock)
1
>>> result(1)
<MagicMock name='mock()()' id='47666064'>
>>> expected = [call(1, 2, 3), call.first(a=3), call.second(), call.__int__(), call()(1)]
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
expected = [call(1, 2, 3), call.first(a=3), call.second(), call.__int__(), call()(1)]
NameError: name 'call' is not defined
我已经尝试将我的expected
变量定义为字符串,但是这仍然不允许直接比较。
>>> expected = """[call(1, 2, 3), call.first(a=3), call.second(), call.__int__(), call()(1)]"""
>>> mock.mock_calls == expected
False
>>> mock.mock_calls
[call(1, 2, 3), call.first(a=3), call.second(), call.__int__(), call()(1)]
关于如何让这个例子工作的任何想法?如果是这样,这是否与检查mock_calls
具有预期调用列表的正确方法相同,并且顺序相同?
编辑:
这是_CallList
类的源代码,它是mock_calls
属性返回的对象的类型。
class _CallList(list):
def __contains__(self, value):
if not isinstance(value, list):
return list.__contains__(self, value)
len_value = len(value)
len_self = len(self)
if len_value > len_self:
return False
for i in range(0, len_self - len_value + 1):
sub_list = self[i:i+len_value]
if sub_list == value:
return True
return False
def __repr__(self):
return pprint.pformat(list(self))