gpt4 book ai didi

python - 断言对模拟方法的连续调用

转载 作者:IT老高 更新时间:2023-10-28 12:32:26 35 4
gpt4 key购买 nike

Mock 有一个 helpful assert_called_with() method .但是,据我了解,这只检查 last 对方法的调用。
如果我有代码连续 3 次调用模拟方法,每次都使用不同的参数,我如何用它们的特定参数断言这 3 次调用?

最佳答案

assert_has_calls 是解决此问题的另一种方法。

来自文档:

assert_has_calls (calls, any_order=False)

assert the mock has been called with the specified calls. The mock_calls list is checked for the calls.

If any_order is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls.

If any_order is True then the calls can be in any order, but they must all appear in mock_calls.

例子:

>>> from unittest.mock import call, Mock
>>> mock = Mock(return_value=None)
>>> mock(1)
>>> mock(2)
>>> mock(3)
>>> mock(4)
>>> calls = [call(2), call(3)]
>>> mock.assert_has_calls(calls)
>>> calls = [call(4), call(2), call(3)]
>>> mock.assert_has_calls(calls, any_order=True)

来源:https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_has_calls

关于python - 断言对模拟方法的连续调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7242433/

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