Python mock: assertions

From wikinotes

These are all pretty well documented, but here are the asserts that I find myself using most frequently.

assert_called_with

Asserts that a function was called at least once with this set of keywords/arguments.

import mock

with mock.patch.object(myobj) as _mock_obj:
	myobj()
_mock_obj.assert_called_with('mournhold', 'is', in='Vvardenfell')

assert_has_calls

Asserts that a function has received calls with these arguments in this order.

import mock
from   mock import call

with mock.patch.object(myobj) as _mock_obj:
	myobj()

_mock_obj.assert_has_calls([call('kubrik is pretentious'), call('dadaism is nonsense')])

called

Asserts the object has been called at least once.

import mock

with mock.patch.object(myobj) as _mock_obj:
	myobj()

assert not _mock_obj.called
assert     _mock_obj.called

mock_calls

A list of all calls to the mock, it's methods, or magic-methods.

mymock = mock.Mock()

mymock('a')
mymock('b')

print(mymock.mock_calls)
>>> [mock.call('a'), mock.call('b')]

unittest asserts

Sometimes it's just more clear to revert to the unittest assertions.

import mock

with mock.patch.object(myobj) as _mock_obj:
	myobj()

self.assertEqual(_mock_obj.called, False)