Selah
Selah

Reputation: 8054

python mock_open assert several write calls

I am trying to test some code that does logging.

logfile = open(file_name, 'w')
logfile.write("blah1")
logfile.write("blah2")

I'd like to assert that both blah1 and blah2 get written. My test function looks like this:

def test_it(self):
    logger.open = mock_open()
    logger.time.time = Mock(return_value=12345)

    logger.run_me()

    logger.open.assert_called_once_with('test_12345.log', 'w');
    file_handle_mock = logger.open()
    file_handle_mock.write.assert_called_with("blah1")
    file_handle_mock.write.assert_called_with("blah2")

But it gives me an error:

AssertionError: Expected call: write('blah1')
Actual call: write('blah2')

How can I properly test multiple calls to the write function?

Versions: Python 2.7.6 mock==1.0.1

Upvotes: 3

Views: 2573

Answers (1)

mgilson
mgilson

Reputation: 309899

According to the docs, assert_called_with and assert_called_once_with only pass if the call is the most recent one1. The trick us to use assert_any_call, or assert_has_calls.

file_handle_mock.write.assert_has_calls([
    mock.call('blah1'),
    mock.call('blah2'),
])

1It's kinda hidden in the docs for assert_any_call, so we can't really blame you for missing it...

Upvotes: 4

Related Questions