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 mock.assert_called_with
and mock.assert_called_once_with
, but I didn't find anything like mock.assert_not_called
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:
try:
# 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 :)
Though an old question, I would like to add that currently
mock
library (backport of unittest.mock) supportsassert_not_called
method.Just upgrade yours;
pip install mock --upgrade
Judging from other answers, no one except @rob-kennedy talked about the
call_args_list
.It's a powerful tool for that you can implement the exact contrary of
MagicMock.assert_called_with()
call_args_list
is a list ofcall
objects. Eachcall
object represents a call made on a mocked callable.Consuming a
call
object is easy, since you can compare it with a tuple of length 2 where the first component is a tuple containing all the positional arguments of the related call, while the second component is a dictionary of the keyword arguments.So, a way to address the specific problem of the OP is
Note that this way, instead of just checking if a mocked callable has been called, via
MagicMock.called
, you can now check if it has been called with a specific set of arguments.That's useful. Say you want to test a function that takes a list and call another function,
compute()
, for each of the value of the list only if they satisfy a specific condition.You can now mock
compute
, and test if it has been called on some value but not on others.With
python >= 3.5
you can usemock_object.assert_not_called()
.You can check the
called
attribute, but if your assertion fails, the next thing you'll want to know is something about the unexpected call, so you may as well arrange for that information to be displayed from the start. Usingunittest
, you can check the contents ofcall_args_list
instead:When it fails, it gives a message like this:
When you test using class inherits unittest.TestCase you can simply use methods like:
and similar (in python documentation you find the rest).
In your example we can simply assert if mock_method.called property is False, which means that method was not called.
This should work for your case;
Sample;