简体   繁体   中英

When do I use mock.assert_has_calls in python?

I struggling to understand what a use for mock.assert_has_calls could be.
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"?

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.

Here is a simple example where we use assert_has_calls to verify that foo calls bar(21, 21) followed by 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)
    ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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