2017年8月25日 星期五

[ Python 常見問題 ] Python Mocking a function from an imported module

Source From Here 
Question 
I want to understand how to @patch a function from an imported module. This is where I am so far. 
- app/mocking.py 
  1. from app.my_module import get_user_name  
  2.   
  3. def test_method():  
  4.     return get_user_name()  
  5.   
  6. if __name__ == "__main__":  
  7.     print("Starting Program...")  
  8.     test_method()  
- app/my_module/__init__.py 
  1. def get_user_name():  
  2.     return "Unmocked User"  
- test/mock_test.py 
  1. import unittest  
  2. from unittest.mock import patch  
  3. from app.mocking import test_method  
  4.   
  5.   
  6. class MockingTestTestCase(unittest.TestCase):  
  7.   
  8.     @patch('app.my_module.get_user_name')  
  9.     def test_mock_stubs(self, mock_method):  
  10.         mock_method.return_value = 'Mocked This Silly'  
  11.         ret = test_method()  
  12.         self.assertEqual(ret, 'Mocked This Silly')  
Execution output: 
# pytest test/mock_test.py
...
@patch('app.my_module.get_user_name')
def test_mock_stubs(self, mock_method):
mock_method.return_value = 'Mocked This Silly'
ret = test_method()

> self.assertEqual(ret, 'Mocked This Silly')
E AssertionError: 'Unmocked User' != 'Mocked This Silly'
E - Unmocked User
E + Mocked This Silly

How-To 
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: 
  1. import unittest  
  2. from unittest.mock import patch  
  3. from app.mocking import test_method  
  4.   
  5.   
  6. class MockingTestTestCase(unittest.TestCase):  
  7.   
  8.     @patch('app.mocking.get_user_name')  
  9.     def test_mock_stubs(self, mock_method):  
  10.         mock_method.return_value = 'Mocked This Silly'  
  11.         ret = test_method()  
  12.         self.assertEqual(ret, 'Mocked This Silly')  
Changing patch target from ''app.my_module.get_user_name'' to 'app.mocking.get_user_name'. The standard library documentation includes a useful section describing this.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...