25

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

Nathan Wailes
  • 9,872
  • 7
  • 57
  • 95

3 Answers3

31

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.
blhsing
  • 91,368
  • 6
  • 71
  • 106
8

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
Andrey Semakin
  • 2,032
  • 1
  • 23
  • 50
4

Using Pytest, I assert that "AssertionError" is called:

import pytest
from unittest.mock import Mock


def test_something():
    something.foo = Mock()
    
    # Test that something.foo(bar) is not called.
    with pytest.raises(AssertionError):
        something.foo.assert_called_with(bar)
cozos
  • 787
  • 10
  • 19