繁体   English   中英

我什么时候在 python 中使用 mock.assert_has_calls?

[英]When do I use mock.assert_has_calls in python?

我很难理解mock.assert_has_calls的用途。
文档说

断言已使用指定的调用调用模拟。

原谅我,但如果用调用模拟某些东西,我是否应该使用它来确保 python 的源代码中没有错误,我的解释器可能会决定说,“嗯,这个 function 被调用 Foo 模拟了但是我想我会用 call Bar 来模拟它”?

您使用Mock.assert_has_calls来验证您的Mock是否已使用特定的 arguments 集合调用。这里的“指定调用”是指mock.call对象,每个对象代表一组 arguments 用于特定的 function 调用。

这是一个简单的示例,我们使用assert_has_calls来验证foo调用bar(21, 21)后跟bar(40, 2)

from unittest import mock

def bar(a, b):
    return a + b

def foo():
    bar(21, 21)
    bar(40, 2)

@mock.patch(f"{__name__}.bar")
def test_foo(mock_bar):
    foo()
    mock_bar.assert_has_calls([
        mock.call(21, 21),
        mock.call(40, 2)
    ])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM