Title: Python: Unpack call_args_list from unittest.mock
Tags: python;python-3.x;mocking;python-unittest;python-unittest.mock
Question: i would like to unpack the arguments of a mocked method. I have a mocked subscriber which is called by the code under test and i would like to verify the invocation of the notify() method.
class Subscriber:
def notify(self, event):
pass
I'm using the following snippet to unpack the arguments and verify two invocations:
calls= self.subscriber.notify.call_args_list
event1 = calls[0][0][0]
event2 = calls[1][0][0]
assert_that(event1, instance_of(CreatedEvent))
assert_that(event1.file.name, equal_to("foo.txt"))
But the two lines to unpack the events are very clumsy and far away from readable code.
Does somebody know a better approach to unpack the arguments?
Thanks a lot!
Comment: Updated the question. :-)

Comment: What will you do with `event1` and `event2`? I don't understand...


Here is another answer: If you're trying to assert the same thing for events in each call, then using a simple for loop might help:
for call in calls:
event = call[0][0]
assert_that(event, instance_of(CreatedEvent))
assert_that(event.file.name, equal_to("foo.txt"))

Here is another answer: You can use assert_has_calls
calls.assert_has_calls(call(ANY, ...), call(...))

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2018:00:01/18/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><python-3.x><mocking><python-unittest><python-unittest.mock>', 'Title': 'Python: Unpack call_args_list from unittest.mock', 'ViewCount': 1645, 'id': 48316224, 'user_AboutMe': '', 'user_AccountId': 2339887.0, 'user_DisplayName': 'kKdH', 'user_Reputation': 483.0, 'user_Views': 65.0, 'user_id': 2051427.0}}