[英]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.