[英]How to get Mock().assert_called_once like behavior below python 3.6?
How to get unittest.mock.Mock().assert_called_once
like behavior with unittest.mock.Mock().assert_called_once_with
, as assert_called_once
s not available below python 3.6 . 如何使用unittest.mock.Mock().assert_called_once
类似行为的unittest.mock.Mock().assert_called_once_with
,因为在python 3.6下不可用assert_called_once
。
Basically what I want is checking if the method gets called exactly once, no matter with which argument or how many argument. 基本上我想要的是检查该方法是否仅被调用一次,无论使用哪个参数或多少个参数。
I tried unittest.mock.ANY
, but seems it isn't what I want. 我尝试了unittest.mock.ANY
,但似乎不是我想要的。
All that assert_called_once()
does is assert that the Mock.call_count
attribute is 1; assert_called_once()
所做的所有assert_called_once()
就是断言Mock.call_count
属性为1; you can trivially do the same test: 您可以简单地执行相同的测试:
self.assertEqual(
mock_object.call_count, 1,
"Expected mock to have been called once. Called {} times.".format(
mock_object.call_count))
If you tried to use Mock.assert_called_once_with()
with the ANY
object, take into account that that object stands for the value of one of the arguments . 如果您尝试将Mock.assert_called_once_with()
与ANY
对象一起使用,请考虑到该对象代表其中一个参数的值。 Mock.assert_called_once_with(ANY)
only matches if the object has been called with exactly one argument , and the value of that argument doesn't matter: 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')
You can't use the ANY
object together with the *called_with
assertions to mean 'any number of arguments'. 您不能将ANY
对象与*called_with
断言一起使用来表示“任意数量的参数”。 Only in an assertion that takes call()
objects would ANY
be interpreted as any number of arguments ; 只有在采用call()
对象的断言中, ANY
才能解释为任意数量的参数 ; so you could also use Mock.assert_has_calls()
here, passing in a list with a single ANY
element: 因此,您还可以在此处使用Mock.assert_has_calls()
,并传入带有单个ANY
元素的列表:
>>> m.assert_has_calls([ANY]) # no exception raised
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.