为什么根据我在shell中还是在shell中运行,mock.mock_calls的内容不同?
在程序中? mock.mock_calls == expected的断言在程序中失败,但在外壳中传递。
该代码基于用于跟踪多个呼叫的文档。 (26.5.1.5. Tracking all Calls)

>>> 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。

最佳答案

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

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)]

关于python - 模拟:跟踪所有调用。 Shell与程序不一致,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23846973/

10-16 05:06