Home > Blockchain >  patching a function if that function is imported using the from statement
patching a function if that function is imported using the from statement

Time:12-02

I have a case similar to the following code where I am trying to patch a fucntion that is imported using the from statement:

from module1 import function1

def function2():
    function1_result = function1()
    return 2*function1_result

and then the testing code is:

from unittest import patch
def test_function2():
    func1_value = 5
    with patch("module1.function1", return_value=func1_value) as patched_func1:
        function2_value = function2()
    assert function2_value==2*func1_value

However the code runs but it doesn't use the patched function 1 and actually calls the function. However, if I change the import statement to just import module1 then the test runs fine.

CodePudding user response:

See Where to patch doc, the examples in the documentation are very clear.

module1.py:

def function1():
    return 1

module2.py:

from module1 import function1


def function2():
    function1_result = function1()
    return 2*function1_result

test_module2.py:

from unittest import TestCase
from unittest.mock import patch
import unittest
from module2 import function2


class TestModule2(TestCase):
    def test_function2(self):
        func1_value = 5
        with patch("module2.function1", return_value=func1_value) as patched_func1:
            function2_value = function2()
        assert function2_value == 2*func1_value


if __name__ == '__main__':
    unittest.main()

Test result:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
  • Related