python – 断言一个函数/方法没有使用Mock调用

我使用Mock库来测试我的应用程序,但我想断言一些函数没有被调用。 Mock文档讨论的方法像mock.assert_called_with和mock.assert_called_once_with,但我没有找到任何类似mock.assert_not_called或相关的验证mock没有被调用。

我可以去像下面的东西,虽然它看起来不酷或pythonic:

def test_something:
    # some actions
    with patch('something') as my_var:
        try:
            # args are not important. func should never be called in this test
            my_var.assert_called_with(some, args)
        except AssertionError:
            pass  # this error being raised means it's ok
    # other stuff

任何想法如何完成这个?

感谢任何帮助:)

这应该适合你的情况;

assert not my_var.called, 'method should not have been called'

样品;

>>> mock=Mock()
>>> mock.a()
<Mock name='mock.a()' id='4349129872'>
>>> assert not mock.b.called, 'b was called and should not have been'
>>> assert not mock.a.called, 'a was called and should not have been'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: a was called and should not have been
http://stackoverflow.com/questions/12187122/assert-a-function-method-was-not-called-using-mock

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – 断言一个函数/方法没有使用Mock调用