2

In my code I am using assert_any_call() to verify series of call that happens to the django model filter, Now I need to verify the reverse case of this like assert_not_called(args).

Is there any assert statement to achieve this in python?

2
  • Possibly of help? stackoverflow.com/a/12187244/314291 Commented May 25, 2014 at 13:01
  • 1
    I wanted to check calls with parameters. Commented May 25, 2014 at 13:07

1 Answer 1

3

The simplest way is to use Mock.call_args_list:

assert call(None, a=1, b="") not in mocked_func.call_args_list, "Called with invalid args."

If you want a method, use:

class NotCalledMagicMock(unittest.mock.MagicMock):
    def assert_not_called(_mock_self, *args, **kwargs):
        self = _mock_self
        if self.call_args is None:
            return

        expected = self._call_matcher((args, kwargs))
        if any(self._call_matcher(ca) == expected for ca in self.call_args_list):
            cause = expected if isinstance(expected, Exception) else None
            raise AssertionError(
                '%r found in call list' % (self._format_mock_call_signature(args, kwargs),)
            ) from cause

To use this class, put this decorator before your test function:

@unittest.mock.patch("unittest.mock.MagicMock", NotCalledMagicMock)

Or make your mocks using:

func_b_mock = NotCalledMagicMock()

To use the method (where func_b_mock is a mock generated by e.g. patch):

func_b_mock.assert_not_called([12], a=4)

When it fails, it raises an AssertionError like:

Traceback (most recent call last):
  File "your_test.py", line 34, in <module>
    test_a()
  File "/usr/lib/python3.4/unittest/mock.py", line 1136, in patched
    return func(*args, **keywargs)
  File "your_test.py", line 33, in test_a
    func_b_mock.assert_not_called([1])
  File "your_test.py", line 20, in assert_not_called
    ) from cause
AssertionError: 'func_b([1])' found in call list
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.