要修补哪个模块

Which module to patch

我有以下目录

/root
  /app
      /api
          my_api.py
      /service
          my_service.py
  /tests
     test_api.py

my_api.py

import app
def run_service():
     app.service.my_service.service_function()

test_api.py

@patch('app.service.my_service.service_function')
test_run_service(self,mock_service):
     mock_service.return_value = 'Mock'
     response = self.client.get(url_for('api.run_service')
     self.assertTrue(response == expected_responce)

以上作品。我想不通的是我需要修补哪个模块,以防我想像这样在 my_apy.py 中导入 service_function

from app.service.my_service import service_function

如果我像上面那样进行导入,mock 将停止工作。

您需要修补 app.api.my_api.service_function,因为这是已绑定到导入对象的全局名称:

@patch('app.api.my_api.service_function')
test_run_service(self, mock_service):
     mock_service.return_value = 'Mock'
     response = self.client.get(url_for('api.run_service')
     self.assertTrue(response == expected_responce)

参见 Where to patch section:

The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined.