断言未使用Mock调用函数/方法 [英] Assert a function/method was not called using Mock

查看:219
本文介绍了断言未使用Mock调用函数/方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mock库测试我的应用程序,但是我想断言某些函数没有被调用.模拟文档讨论了诸如mock.assert_called_withmock.assert_called_once_with之类的方法,但是我没有找到诸如mock.assert_not_called之类的东西,或者与验证模拟相关的东西未调用.

I'm using the Mock library to test my application, but I want to assert that some function was not called. Mock docs talk about methods like mock.assert_called_with and mock.assert_called_once_with, but I didn't find anything like mock.assert_not_called or something related to verify mock was NOT called.

我可以使用类似以下的内容,尽管它看起来也不酷,也不是pythonic:

I could go with something like the following, though it doesn't seem cool nor 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

有什么想法可以做到这一点吗?

Any ideas how to accomplish this?

感谢您的帮助:)

推荐答案

这应该适合您的情况;

This should work for your case;

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

这篇关于断言未使用Mock调用函数/方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆