I realize unittest.mock
objects now have an assert_not_called
method available, but what I'm looking for is an assert_not_called_with
. Is there anything like that? I looked on Google and didn't see anything, and when I tried just using mock_function.assert_not_called_with(...)
it raised an AttributeError
, meaning the function does not exist with that name.
with self.assertRaises(AssertionError):
mock_function.assert_called_with(arguments_I_want_to_test)
This works but clutters the code if I have several such calls I want to make.
Assert a function/method was not called using Mock
You can add a assert_not_called_with
method to unittest.mock.Mock
on your own:
from unittest.mock import Mock
def assert_not_called_with(self, *args, **kwargs):
try:
self.assert_called_with(*args, **kwargs)
except AssertionError:
return
raise AssertionError('Expected %s to not have been called.' % self._format_mock_call_signature(args, kwargs))
Mock.assert_not_called_with = assert_not_called_with
so that:
m = Mock()
m.assert_not_called_with(1, 2, a=3)
m(3, 4, b=5)
m.assert_not_called_with(3, 4, b=5)
outputs:
AssertionError: Expected mock(3, 4, b=5) to not have been called.
One more solution that uses mock calls history:
from unittest.mock import call
assert call(arguments_I_want_to_test) not in mock_function.mock_calls
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With