Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django mocks not working as expected

I'm struggling with django mock; I have even simplified an unit test but the test is still failing. I want to verify that a method is called (even with any parameter), but the "assert_called_once_with" always returns False. Currently I'm trying:

@patch('utils.make_reset_password')
def test_shouldHaveCalledMakeResetToken(self, mocked):
    user = User.get(...)
    make_reset_password(user)
    mocked.assert_called_once_with(user)

Even this simple example is failing with:

AssertionError: Expected 'make_reset_password' to be called once. Called 0 times

How this is possible? What am I doing wrong?

Thanks in advance

like image 292
FVod Avatar asked Nov 26 '25 12:11

FVod


1 Answers

You have to use full path to utils, e.g. @patch('my_app.utils.make_reset_password') and then in the test call a function that calls make_reset_password.

@patch('my_app.utils.make_reset_password')
def test_shouldHaveCalledMakeResetToken(self, mock_make_reset_password):
    user = User.get(...)
    function_under_test(user)
    mock_make_reset_password.assert_called_once_with(user)

EDIT

The other thing that comes to my mind is you are not mocking the correct function. If make_reset_password is imported from utils in another module then you need to change the path in the @patch decorator.

For example

# my_module.py
from my_app.utils import make_reset_password

def run_make_reset_password(user):
    make_reset_password(user)


# tests.py
@patch('my_app.my_module.make_reset_password')
def test_shouldHaveCalledMakeResetToken(self, mock_make_reset_password):
    user = User.get(...)
    run_make_reset_password(user)
    mock_make_reset_password.assert_called_once_with(user)
like image 93
Dušan Maďar Avatar answered Nov 28 '25 02:11

Dušan Maďar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!