2

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.

2
  • how about adding a global counter to the function (e.g. for each execution of the function it is incremented by 1). test its value before and after the test - if it differs, it was called; if its the same it wasnt [workaround type of thing I guess....) Commented Mar 3, 2017 at 7:41
  • Mock reset function so it does nothing. Commented Mar 3, 2017 at 7:44

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.