繁体   English   中英

Python - 我如何断言模拟 object 没有被特定的 arguments 调用?

[英]Python - How can I assert a mock object was not called with specific arguments?

我意识到unittest.mock对象现在有一个可用的assert_not_called方法,但我正在寻找的是一个assert_not_called_with 有没有这样的东西? 我查看了 Google 并没有看到任何东西,当我尝试仅使用mock_function.assert_not_called_with(...)它引发了一个AttributeError ,这意味着 function 不存在该名称。

我目前的解决方案

with self.assertRaises(AssertionError):
    mock_function.assert_called_with(arguments_I_want_to_test)

这行得通,但如果我想进行多个此类调用,则会使代码混乱。

有关的

断言未使用 Mock 调用函数/方法

您可以自己将assert_not_called_with方法添加到unittest.mock.Mock

from unittest.mock import Mock

def assert_not_called_with(self, *args, **kwargs):
    try:
        self.assert_called_with(*args, **kwargs)
    except AssertionError:
        return
    raise AssertionError('Expected %s to not have been called.' % self._format_mock_call_signature(args, kwargs))

Mock.assert_not_called_with = assert_not_called_with

以便:

m = Mock()
m.assert_not_called_with(1, 2, a=3)
m(3, 4, b=5)
m.assert_not_called_with(3, 4, b=5)

输出:

AssertionError: Expected mock(3, 4, b=5) to not have been called.

另一种使用模拟调用历史记录的解决方案:

from unittest.mock import call

assert call(arguments_I_want_to_test) not in mock_function.mock_calls

使用 Pytest,我断言调用了“AssertionError”:

import pytest
from unittest.mock import Mock


def test_something():
    something.foo = Mock()
    
    # Test that something.foo(bar) is not called.
    with pytest.raises(AssertionError):
        something.foo.assert_called_with(bar)

暂无
暂无

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

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