【问题标题】:How to verify mock method not called in python?如何验证python中未调用的模拟方法?
【发布时间】:2014-07-14 08:46:00
【问题描述】:

在我的代码中,我使用 assert_any_call() 来验证 django 模型过滤器发生的一系列调用,现在我需要验证这种相反的情况,例如 assert_not_call(args)。

在 python 中是否有任何断言语句来实现这一点?

【问题讨论】:

标签: python mocking


【解决方案1】:

最简单的方法是使用Mock.call_args_list

assert call(None, a=1, b="") not in mocked_func.call_args_list, "Called with invalid args."

如果你想要一个方法,使用:

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 生成的模拟):

func_b_mock.assert_not_called([12], a=4)

当它失败时,它会引发一个AssertionError,例如:

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

【讨论】:

    猜你喜欢
    • 2014-06-08
    • 1970-01-01
    • 2017-07-01
    • 2015-08-23
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    相关资源
    最近更新 更多