首页 > 解决方案 > python:如何模拟辅助方法?

问题描述

你能帮我弄清楚我做错了什么吗?我对 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_auth_token

 Invalid URL '': No schema supplied. Perhaps you meant http://?

我调试了它,它看起来不像我正确修补它。授权帮助文件与测试类位于同一文件夹“functions”中。

编辑:在tested_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()

改成这个后,它开始正常工作

import functions.helper_class
...
def get_xml(event, context):
    ...
    response_token = functions.helper_class.get_auth_token()

我仍然不完全明白为什么

标签: pythonunit-testingaws-lambda

解决方案


  • 在您的第一个场景中

tested_class.py,get_auth_token被导入

from functions.helper_class import get_auth_token

补丁应该正好是get_auth_tokenattested_class

@mock.patch('functions.tested_class.get_auth_token')
  • 第二种情况

具有以下用法

 response_token = functions.helper_class.get_auth_token()

修补的唯一方法是这个

@mock.patch('functions.helper_class.get_auth_token')
  • 选择

像这样导入tested_class

from functions import helper_class
helper_class.get_auth_token()

补丁可能是这样的:

@mock.patch('functions.tested_class.helper_class.get_auth_token')

推荐阅读