gpt4 book ai didi

python - Mock : Tracking all Calls. Shell 与程序不一致

转载 作者:行者123 更新时间:2023-12-01 05:12:37 26 4
gpt4 key购买 nike

为什么mock.mock_calls的内容会根据我是否在shell中运行而有所不同在一个程序中? mock.mock_calls == Expected 断言在程序中失败,但在 shell 中传递。该代码基于跟踪多个调用的文档。 (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__()调用的魔术方法:

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 - Mock : Tracking all Calls. Shell 与程序不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23846973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com