Skip to content
Advertisement

Python – How can I assert a mock object was not called with specific arguments?

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.

My current solution

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.

Related

Assert a function/method was not called using Mock

Advertisement

Answer

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.
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement