Is there a way to get the mock calls counted by call_count
in this example:
from mock import MagicMock
mock = MagicMock()
mock.get_query(arg=1).execute()
mock.get_query(arg=2).execute()
print('count:', mock.get_query.call_count)
print('calls:', mock.get_query.mock_calls)
Actual result:
count: 2
calls: [call(arg=1), call().execute(), call(arg=2), call().execute()]
Desired result:
count: 2
calls: [call(arg=1), call(arg=2)]
I understand mock_calls
. The documentation is quite clear:
mock_calls records all calls to the mock object, its methods, magic methods and return value mocks.
I'm wondering if there's an elegent way to filter mock_calls
. There's also method_calls
but it's still not it.
CodePudding user response:
It looks like you're looking for a list of call()
objects corresponding to each call made to mock.get_query
. I think that mock.get_query.call_args_list
will give you what you want:
>>> from mock import MagicMock
>>> mock = MagicMock()
>>> mock.get_query(arg=1).execute()
<MagicMock name='mock.get_query().execute()' id='139688065592160'>
>>> mock.get_query(arg=2).execute()
<MagicMock name='mock.get_query().execute()' id='139688065592160'>
>>> mock.get_query.call_args_list
[call(arg=1), call(arg=2)]
From the docs:
call_args_list
This is a list of all the calls made to the mock object in sequence (so the length of the list is the number of times it has been called). Before any calls have been made it is an empty list. The call object can be used for conveniently constructing lists of calls to compare with call_args_list.