python:如何模拟助手方法?

python:如何模拟助手方法?,python,unit-testing,aws-lambda,Python,Unit Testing,Aws Lambda,你能帮我找出我做错了什么吗?我对python lambdas进行了以下单元测试 class Tests(unittest.TestCase): def setUp(self): //some setup @mock.patch('functions.tested_class.requests.get') @mock.patch('functions.helper_class.get_auth_token') def test_tested_cla

你能帮我找出我做错了什么吗?我对python lambdas进行了以下单元测试

class Tests(unittest.TestCase):
    def setUp(self):
        //some setup

    @mock.patch('functions.tested_class.requests.get')
    @mock.patch('functions.helper_class.get_auth_token')
    def test_tested_class(self, mock_auth, mock_get):

        mock_get.side_effect = [self.mock_response]
        mock_auth.return_value = "some id token"

        response = get_xml(self.event, None)

        self.assertEqual(response['statusCode'], 200)
问题是,当我运行此代码时,对于
get\u auth\u token
,我得到以下错误:

 Invalid URL '': No schema supplied. Perhaps you meant http://?
我调试了它,但看起来我没有正确地修补它。授权助手文件与测试类位于同一文件夹“functions”中

编辑: 在测试的\u类中,我导入了get\u auth\u令牌,如下所示:

from functions import helper_class
from functions.helper_class import get_auth_token
...
def get_xml(event, context):
    ...
    response_token = get_auth_token()
@mock.patch('functions.tested_class.helper_class.get_auth_token')
换成这个后,它开始工作良好

import functions.helper_class
...
def get_xml(event, context):
    ...
    response_token = functions.helper_class.get_auth_token()
我仍然不完全理解为什么

patch()通过(暂时)用另一个名称更改名称指向的对象来工作。可以有许多名称指向任何单个对象,因此为了使修补工作正常进行,必须确保修补被测系统使用的名称

基本原则是,在查找对象的位置进行修补,这不一定与定义对象的位置相同

Python文档有一个很好的例子

  • 在您的第一个场景中
tested\u class.py
中,导入
get\u auth\u令牌

from functions.helper_class import get_auth_token
补丁应该是
tested\u类中的
get\u auth\u令牌

@mock.patch('functions.tested_class.get_auth_token')
from functions import helper_class
helper_class.get_auth_token()
  • 第二种情况
使用以下用法

 response_token = functions.helper_class.get_auth_token()
唯一的修补方法就是这样

@mock.patch('functions.helper_class.get_auth_token')
  • 另类
tested\u类中使用类似的导入

@mock.patch('functions.tested_class.get_auth_token')
from functions import helper_class
helper_class.get_auth_token()
补丁可能是这样的:

from functions import helper_class
from functions.helper_class import get_auth_token
...
def get_xml(event, context):
    ...
    response_token = get_auth_token()
@mock.patch('functions.tested_class.helper_class.get_auth_token')

现在我读了你的答案,它更有意义了。谢谢你的解释!