Python Mocking a function from an imported module

I want to understand how to @patch a function from an imported module.

This is where I am so far.


from app.my_module import get_user_name

def test_method():
  return get_user_name()

if __name__ == "__main__":
  print "Starting Program..."


def get_user_name():
  return "Unmocked User"


import unittest
from app.mocking import test_method 

def mock_get_user():
  return "Mocked This Silly"

class MockingTestTestCase(unittest.TestCase):

  def test_mock_stubs(self, mock_method):
    mock_method.return_value = 'Mocked This Silly')
    ret = test_method()
    self.assertEqual(ret, 'Mocked This Silly')

if __name__ == '__main__':

This does not work as I would expect. The “patched” module simply returns the unmocked value of get_user_name. How do I mock methods from other packages that I am importing into a namespace under test?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

When you are using the patch decorator from the unittest.mock package you are patching it in the namespace that is under test (in this case app.mocking.get_user_name), not the namespace the function is imported from (in this case app.my_module.get_user_name).

To do what you describe with @patch try something like the below:

from mock import patch
from app.mocking import test_method 

class MockingTestTestCase(unittest.TestCase):
    def test_mock_stubs(self, test_patch):
        test_patch.return_value = 'Mocked This Silly'
        ret = test_method()
        self.assertEqual(ret, 'Mocked This Silly')

The standard library documentation includes a useful section describing this.

Solution 2

While Matti John’s answer solves your issue (and helped me too, thanks!), I would, however, suggest localizing the replacement of the original ‘get_user_name’ function with the mocked one. This will allow you to control when the function is replaced and when it isn’t. Also, this will allow you to make several replacements in the same test. In order to do so, use the ‘with’ statment in a pretty simillar manner:

from mock import patch

class MockingTestTestCase(unittest.TestCase):

    def test_mock_stubs(self):
        with patch('app.mocking.get_user_name', return_value = 'Mocked This Silly'):
            ret = test_method()
            self.assertEqual(ret, 'Mocked This Silly')

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply