gpt4 book ai didi

python - 断言未使用 Mock 调用函数/方法

转载 作者:IT老高 更新时间:2023-10-28 21:06:01 24 4
gpt4 key购买 nike

我正在使用 Mock 库来测试我的应用程序,但我想断言某些函数没有被调用。模拟文档谈论像 mock.assert_call_withmock.assert_call_once_with 这样的方法,但我没有找到像 mock.assert_not_call 这样的东西或与验证 mock 是否未调用

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

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'

sample ;

>>> 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

关于python - 断言未使用 Mock 调用函数/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12187122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com