1

为什么 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。

4

1 回答 1

2

这是因为您正在打印方法调用。它导致__str__()调用魔术方法:

print(mock.method())
print(mock.attribute.method(10, x=53))

消除print()呼叫,您将看到所需的行为:

mock.method()
mock.attribute.method(10, x=53)

仅供参考,来自控制台的示例:

>>> mock = unittest.mock.MagicMock()
>>> print(mock.method())
<MagicMock name='mock.method()' id='4433183576'>
>>> print(mock.attribute.method(10, x=53))
<MagicMock name='mock.attribute.method()' id='4433223752'>
>>> mock.mock_calls
[call.method(),
 call.method().__str__(),
 call.attribute.method(10, x=53),
 call.attribute.method().__str__()]

或者,或者,使用普通Mock类:

>>> mock = unittest.mock.Mock()
>>> print(mock.method())
<Mock name='mock.method()' id='4433235528'>
>>> print(mock.attribute.method(10, x=53))
<Mock name='mock.attribute.method()' id='4433252648'>
>>> mock.method_calls
[call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
于 2014-05-24T17:33:43.663 回答