Python Mocking a function from an imported module

前端 未结 2 2166
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 05:51

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

This is where I am so far.

app/mocking.py:



        
相关标签:
2条回答
  • 2020-12-02 06:14

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

    To do the above with Mock try something like the below:

    from mock import patch
    from app.mocking import test_method 
    
    class MockingTestTestCase(unittest.TestCase):
    
        @patch('app.mocking.get_user_name')
        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.

    0 讨论(0)
  • 2020-12-02 06:27

    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')
    
    0 讨论(0)
提交回复
热议问题