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 .
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.
All that assert_called_once()
does is assert that the Mock.call_count
attribute is 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)
only matches if the object has been called with exactly one argument , and the value of that argument doesn't matter:
>>> 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'. Only in an assertion that takes call()
objects would ANY
be interpreted as any number of arguments ; so you could also use Mock.assert_has_calls()
here, passing in a list with a single ANY
element:
>>> m.assert_has_calls([ANY]) # no exception raised
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.