Python patch a function from an import module

Viewed 65

I am trying to create a unit test that uses Python patch but I cannot get it to work. I've tried all kinds of ways to patch but no success.

File to be tested: test_me.py imports another_file.py which contains 2 functions (among many others), func1 and func2, that are needed here.

in test_me.py:

import another_file.py as another_file_alias

# Make use of the 2 functions

another_file_alias.func1()
another_file_alias.func2()

in the actual unit test, test.py, I have 2 mocked functions and need to patch the functions as well.

in test.py:

def func1_mock():
   ...

def func2_mock():
   ...

class TestClass(unittest.TestCase):
   
   def setUp(self):
      with patch("another_file.func1", side_effect=func1_mock):
         with patch("another_file.func2", side_effect=func2_mock):

   def test_1(self):
      ...

1 Answers

You need to include the module name in the patch target and then the alias of the import, e.g.:

   def setUp(self):
      with patch("test_me.another_file_alias.func1", side_effect=func1_mock):
         with patch("test_me.another_file_alias.func2", side_effect=func2_mock):
Related