简体   繁体   English

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

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

I struggling to understand what a use for mock.assert_has_calls could be.我很难理解mock.assert_has_calls的用途。
The docs say文档说

assert the mock has been called with the specified calls.断言已使用指定的调用调用模拟。

Forgive me, but if mock something with a call, am I supposed to use this to make sure there's not an error in the source code of python, where my interpreter might decide say, "hummm, this function was mocked with the call Foo but I think I'm going to mock it out with the call Bar instead"?原谅我,但如果用调用模拟某些东西,我是否应该使用它来确保 python 的源代码中没有错误,我的解释器可能会决定说,“嗯,这个 function 被调用 Foo 模拟了但是我想我会用 call Bar 来模拟它”?

You use Mock.assert_has_calls to verify that your Mock has been called with specific sets of arguments. "The specified calls" here refers to mock.call objects, each of which represents a set of arguments for a specific function call.您使用Mock.assert_has_calls来验证您的Mock是否已使用特定的 arguments 集合调用。这里的“指定调用”是指mock.call对象,每个对象代表一组 arguments 用于特定的 function 调用。

Here is a simple example where we use assert_has_calls to verify that foo calls bar(21, 21) followed by bar(40, 2) :这是一个简单的示例,我们使用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