![](/img/trans.png)
[英]Magic mock assert_called_once vs assert_called_once_with weird behaviour
[英]How to get Mock().assert_called_once like behavior below python 3.6?
如何使用unittest.mock.Mock().assert_called_once
類似行為的unittest.mock.Mock().assert_called_once_with
,因為在python 3.6下不可用assert_called_once
。
基本上我想要的是檢查該方法是否僅被調用一次,無論使用哪個參數或多少個參數。
我嘗試了unittest.mock.ANY
,但似乎不是我想要的。
assert_called_once()
所做的所有assert_called_once()
就是斷言Mock.call_count
屬性為1; 您可以簡單地執行相同的測試:
self.assertEqual(
mock_object.call_count, 1,
"Expected mock to have been called once. Called {} times.".format(
mock_object.call_count))
如果您嘗試將Mock.assert_called_once_with()
與ANY
對象一起使用,請考慮到該對象代表其中一個參數的值。 Mock.assert_called_once_with(ANY)
僅在對象僅使用一個參數調用且該參數的值無關緊要的情況下才匹配:
>>> from unittest.mock import Mock, ANY
>>> m = Mock()
>>> m(42, 81, spam='eggs') # 2 positional arguments, one keyword argument
<Mock name='mock()' id='4348527952'>
>>> m.assert_called_once_with(ANY) # doesn't match, just one positional argument
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/unittest/mock.py", line 825, in assert_called_once_with
return self.assert_called_with(*args, **kwargs)
File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/unittest/mock.py", line 814, in assert_called_with
raise AssertionError(_error_message()) from cause
AssertionError: Expected call: mock(<ANY>)
Actual call: mock(42, 81, spam='eggs')
您不能將ANY
對象與*called_with
斷言一起使用來表示“任意數量的參數”。 只有在采用call()
對象的斷言中, ANY
才能解釋為任意數量的參數 ; 因此,您還可以在此處使用Mock.assert_has_calls()
,並傳入帶有單個ANY
元素的列表:
>>> m.assert_has_calls([ANY]) # no exception raised
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.