Assert A Function/method Was Not Called Using Mock


Answer :

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


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. 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) 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?