哪个模块要修补

2024-05-08 17:05:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下目录

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

我的api.py

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

测试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)

以上工作。我搞不清楚的是,我需要修补哪个模块,以防我想像这样在我的apy.py中导入service_function

from app.service.my_service import service_function

如果我像上面那样导入,mock就会停止工作


Tags: runpytestimportself目录apiapp
1条回答
网友
1楼 · 发布于 2024-05-08 17:05:02

您需要修补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.

相关问题 更多 >