Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 379
Nathan Wailes Avatar asked Feb 23 '19 04:02

Nathan Wailes


2 Answers

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.
like image 182
blhsing Avatar answered Oct 12 '22 20:10

blhsing


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
like image 3
Andrey Semakin Avatar answered Oct 12 '22 22:10

Andrey Semakin