python – Assert a function/method was not called using Mock
python – Assert a function/method was not called using Mock
This should work for your case;
assert not my_var.called, method should not have been called
Sample;
>>> 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
Though an old question, I would like to add that currently mock
library (backport of unittest.mock) supports assert_not_called
method.
Just upgrade yours;
pip install mock --upgrade
python – Assert a function/method was not called using Mock
You can check the called
attribute, but if your assertion fails, the next thing youll want to know is something about the unexpected call, so you may as well arrange for that information to be displayed from the start. Using unittest
, you can check the contents of call_args_list
instead:
self.assertItemsEqual(my_var.call_args_list, [])
When it fails, it gives a message like this:
AssertionError: Element counts were not equal: First has 0, Second has 1: call(first argument, 4)