Gerard Gerard - 1 month ago 9x
Python Question

Assert a function/method was not called using Mock

I'm using the Mock library to test my application, but I want to assert that some function was not called. Mock docs talk about methods like

, but I didn't find anything like
or something related to verify mock was NOT called.

I could go with something like the following, though it doesn't seem cool nor pythonic:

def test_something:
# some actions
with patch('something') as my_var:
# args are not important. func should never be called in this test
my_var.assert_called_with(some, args)
except AssertionError:
pass # this error being raised means it's ok
# other stuff

Any ideas how to accomplish this?

Thanks for any help :)


This should work for your case;

assert not my_var.called, 'method should not have been called'


>>> mock=Mock()
>>> mock.a()
<Mock name='mock.a()' id='4349129872'>
>>> assert not mock.b.called, 'b was called and should not have been'
>>> assert not mock.a.called, 'a was called and should not have been'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: a was called and should not have been