如何验证python中未调用的mock方法?

如何验证python中未调用的mock方法?,python,mocking,Python,Mocking,在我的代码中,我使用assert_any_call()来验证django模型过滤器的一系列调用,现在我需要验证类似assert_not_called(args)的相反情况 在python中是否有任何assert语句可以实现这一点 最简单的方法是使用: 如果需要方法,请使用: class NotCalledMagicMock(unittest.mock.MagicMock): def assert_not_called(_mock_self, *args, **kwargs):

在我的代码中,我使用assert_any_call()来验证django模型过滤器的一系列调用,现在我需要验证类似assert_not_called(args)的相反情况


在python中是否有任何assert语句可以实现这一点

最简单的方法是使用:

如果需要方法,请使用:

class NotCalledMagicMock(unittest.mock.MagicMock):
    def assert_not_called(_mock_self, *args, **kwargs):
        self = _mock_self
        if self.call_args is None:
            return

        expected = self._call_matcher((args, kwargs))
        if any(self._call_matcher(ca) == expected for ca in self.call_args_list):
            cause = expected if isinstance(expected, Exception) else None
            raise AssertionError(
                '%r found in call list' % (self._format_mock_call_signature(args, kwargs),)
            ) from cause
要使用此类,请将此装饰器放在测试函数之前:

@unittest.mock.patch("unittest.mock.MagicMock", NotCalledMagicMock)
或者使用以下方法进行模拟:

func_b_mock = NotCalledMagicMock()
要使用该方法(其中
func_b_mock
是由例如
patch
生成的模拟):

当它失败时,会引发一个断言错误,如:

Traceback (most recent call last):
  File "your_test.py", line 34, in <module>
    test_a()
  File "/usr/lib/python3.4/unittest/mock.py", line 1136, in patched
    return func(*args, **keywargs)
  File "your_test.py", line 33, in test_a
    func_b_mock.assert_not_called([1])
  File "your_test.py", line 20, in assert_not_called
    ) from cause
AssertionError: 'func_b([1])' found in call list
回溯(最近一次呼叫最后一次):
文件“your_test.py”,第34行,在
测试a()
文件“/usr/lib/python3.4/unittest/mock.py”,第1136行,带补丁
返回函数(*参数,**键盘)
文件“your_test.py”,第33行,在test_a中
func\u b\u mock.assert\u未调用([1])
文件“your_test.py”,第20行,在assert_not_调用中
)起因
在调用列表中找到断言错误:“func_b([1])”

可能有帮助吗?我想用参数检查通话。
func_b_mock.assert_not_called([12], a=4)
Traceback (most recent call last):
  File "your_test.py", line 34, in <module>
    test_a()
  File "/usr/lib/python3.4/unittest/mock.py", line 1136, in patched
    return func(*args, **keywargs)
  File "your_test.py", line 33, in test_a
    func_b_mock.assert_not_called([1])
  File "your_test.py", line 20, in assert_not_called
    ) from cause
AssertionError: 'func_b([1])' found in call list