我試圖重新創建mock_calls example,這樣我可以檢查呼叫的預期列表等於實際做出的調用。不過,我收到一個NameError
例外,因爲name 'call' is not defined
:斷言`mock_calls`等於預期的通話清單
>>> 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))
謝謝!我也嘗試過尋找'call'方法,但在我的疲倦中無法找到它。 – 2013-02-24 08:03:01