問(wèn)題描述
我正在使用 Mock 庫(kù)來(lái)測(cè)試我的應(yīng)用程序,但我想斷言某些函數(shù)沒(méi)有被調(diào)用.模擬文檔談?wù)撓?mock.assert_call_with
和 mock.assert_called_once_with
這樣的方法,但我沒(méi)有找到像 mock.assert_not_call
這樣的東西或與之相關(guān)的東西驗(yàn)證 mock 是否未調(diào)用.
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.
我可以使用類似以下的內(nèi)容,盡管它看起來(lái)既不酷也不像 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
任何想法如何做到這一點(diǎn)?
Any ideas how to accomplish this?
推薦答案
這應(yīng)該適用于您的情況;
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
這篇關(guān)于斷言未使用 Mock 調(diào)用函數(shù)/方法的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!