Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to mock a function in Python (Django)

I'm trying to mock a function used within the function I'm testing, but for some reason I'm not seeing the original function always runs, not the one I created as a mock.

The code I'm testing has this type of setup:

def function_being_tested(foo):
    ...
    function_i_want_to_mock(bar)
    ...

def function_i_want_to_mock(bar)
    print("Inside original function")
    ...

I've installed Mock and I've tried using unittest.mock patch

Currently the test file uses this setup:

import mock
from django.test import TestCase


def mock_function_i_want_to_mock(bar):
    print(bar)
    return True


class SupportFunctionsTestCases(TestCase):

    @mock.patch("path.to.function.function_i_want_to_mock", mock_function_i_want_to_mock)
    def test_function_being_tested(self):
        # setup
        result = function_being_tested(test_foo)
        self.assertEqual(result, expected_result)

What then happens is when I run the test, I always get: "Inside original function", not the parameter printed so it's always running the original function.

I've used this exact setup before and it has worked so I'm not sure what's causing this. Probably some wrong setup...

If anyone has a different way of doing this or spots some error, it would be appreciated.

like image 454
steinarey Avatar asked Jun 12 '26 03:06

steinarey


1 Answers

"path.to.function.function_i_want_to_mock" should be a path to where the function is used, not defined.

So if function_i_want_to_mock is defined in module_A.py but imported and used in module_B.py, which you are testing, then you should use @mock.patch("path.to.module_B.function_i_want_to_mock", ...).

like image 67
Dušan Maďar Avatar answered Jun 14 '26 18:06

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!