Paul McKenzie
Paul McKenzie

Reputation: 20096

magicmock called several times but I can't assert called with

(Python 2.6)

I have a method:

def send_all(self, messages):
    for message in messages:
        queue.send(message)

I want to assert that queue.send() is called for each message

queue = MagicMock()
myobj= MyObject(queue)
myobj.send_all(test_messages)
for test_message in test_messages:
    queue.send.assert_called_once_with(test_message)

Each of the 55 messages in test_messages is unique. I get the following error:

AssertionError: Expected to be called once. Called 55 times.

Upvotes: 1

Views: 1352

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121834

assert_called_once_with() tests if your mock was called just once; don't use it to test for 55 different calls.

Instead, assert that those 55 calls were made with the mock.assert_has_calls() method:

queue.send.assert_has_calls([call(test_message) for test_message in test_messages])

This will test if that sequence of 55 calls is present; it doesn't limit the mock to having been called more times.

You could also test the mock.mock_calls attribute:

assert queue.send.mock_calls == [call(test_message) for test_message in test_messages]

This will test for exactly those 55 calls.

Upvotes: 4

Related Questions