Assert a function/method was not called using Mock(断言未使用 Mock 调用函数/方法)
问题描述
我正在使用 Mock 库来测试我的应用程序,但我想断言某些函数没有被调用.模拟文档谈论像 mock.assert_call_with
和 mock.assert_called_once_with
这样的方法,但我没有找到像 mock.assert_not_call
这样的东西或与之相关的东西验证 mock 是否未调用.
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.
我可以使用类似以下的内容,尽管它看起来既不酷也不像 Python:
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 调用函数/方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:断言未使用 Mock 调用函数/方法
基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01