为什么 mock.mock_calls 的内容会根据我是在 shell 中运行还是在程序中运行而有所不同?断言mock.mock_calls == expected
在程序中失败,但在 shell 中通过。该代码基于用于跟踪多个呼叫的文档。(26.5.1.5. 跟踪所有呼叫)
>>> from unittest.mock import MagicMock, call
>>> mock = MagicMock()
>>> mock.method()
<MagicMock name='mock.method()' id='57725952'>
>>> mock.attribute.method(10, x=53)
<MagicMock name='mock.attribute.method()' id='57775944'>
>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
>>> mock.method_calls
[call.method(), call.attribute.method(10, x=53)]
>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> expected == mock.mock_calls
True
>>> expected == mock.method_calls
True
到目前为止,这一切都完全符合预期。但是看看mock.mock_calls
程序中发生了什么:它记录了__str__
对每个被调用方法的方法的额外调用。mock.method_calls 不受影响。
import unittest.mock
mock = unittest.mock.MagicMock()
print(mock.method())
print(mock.attribute.method(10, x=53))
print('\nmock.mock_calls\n', mock.mock_calls)
print('\nmock.method_calls\n', mock.method_calls)
expected = [unittest.mock.call.method(),
unittest.mock.call.attribute.method(10, x=53)]
print(expected == mock.mock_calls)
print(expected == mock.method_calls)
输出:
<MagicMock name='mock.method()' id='45740272'>
<MagicMock name='mock.attribute.method()' id='45850128'>
mock.mock_calls
[call.method(),
call.method().__str__(),
call.attribute.method(10, x=53),
call.attribute.method().__str__()]
mock.method_calls
[call.method(), call.attribute.method(10, x=53)]
False
True
我在 Windows 7 计算机上运行 Python 3.4。