Reputation: 823
I am using Django for my web development framework. And now I am writing unittest. How can I assert that a function is not executed in my test code?
For example, this is the use case: My test code is testing a user is typing a wrong password while signing in. I want to make sure that reset password function is not executed in this use case.
Well, this doesn't really reflect the real situation but I hope you get my point.
Upvotes: 2
Views: 4798
Reputation: 337
use mock.patch.object
and assert_not_called
or call_count
to do this.
assume you function define in mymodule.py
:
def function_can_not_be_called():
pass
def func(call):
if call:
function_can_not_be_called()
test code in test_mymodule.py
import mymodule
import unittest
from mock import patch
class CTest(unittest.TestCase):
@patch.object(mymodule, "function_can_not_be_called")
def test_MockFunc(self, mock_func):
mymodule.func(0)
mock_func.assert_not_called()
mymodule.func(1)
mock_func.assert_called_once()
if __name__ == "__main__":
unittest.main()
Upvotes: 0
Reputation: 483
What I would do is to use mock. Mock the function and assert that mock_function.call_count==0
.
You can read more about mock here:
https://docs.python.org/3/library/unittest.mock.html
Upvotes: 7
Reputation: 823
I'd like to answer my own question. So far my solution is using Mock.call
. Example this is where reset password function located: utils/password.py
class Password(object):
def reset(self):
...
So I need to mock this object at my test code test/login.py
@patch('utils.password.Password.reset')
def test_wrong_password(self, mocked_password_reset):
...
assert mocked_password_reset.called == False
Upvotes: 1