![](/img/trans.png)
[英]How can I verify a Python method was called with parameters including a DataFrames?
[英]How to verify mock method not called in python?
在我的代碼中,我使用assert_any_call()來驗證Django模型過濾器發生的一系列調用,現在,我需要驗證類似assert_not_call(args)的相反情況。
是否有任何斷言語句可以在python中實現?
最簡單的方法是使用Mock.call_args_list
:
assert call(None, a=1, b="") not in mocked_func.call_args_list, "Called with invalid args."
如果要使用方法,請使用:
class NotCalledMagicMock(unittest.mock.MagicMock):
def assert_not_called(_mock_self, *args, **kwargs):
self = _mock_self
if self.call_args is None:
return
expected = self._call_matcher((args, kwargs))
if any(self._call_matcher(ca) == expected for ca in self.call_args_list):
cause = expected if isinstance(expected, Exception) else None
raise AssertionError(
'%r found in call list' % (self._format_mock_call_signature(args, kwargs),)
) from cause
要使用此類,請將此裝飾器放在測試函數之前:
@unittest.mock.patch("unittest.mock.MagicMock", NotCalledMagicMock)
或使用以下方法進行模擬:
func_b_mock = NotCalledMagicMock()
要使用該方法(其中func_b_mock
是例如patch
生成的模擬):
func_b_mock.assert_not_called([12], a=4)
當失敗時,它會引發一個AssertionError
如:
Traceback (most recent call last):
File "your_test.py", line 34, in <module>
test_a()
File "/usr/lib/python3.4/unittest/mock.py", line 1136, in patched
return func(*args, **keywargs)
File "your_test.py", line 33, in test_a
func_b_mock.assert_not_called([1])
File "your_test.py", line 20, in assert_not_called
) from cause
AssertionError: 'func_b([1])' found in call list
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.