首页 > 解决方案 > 单元测试AWS python lambda全局变量补丁不起作用

问题描述

我正在尝试对基于 Python 的 aws lambda 代码进行单元测试。我尝试使用补丁来模拟环境变量,但它会抛出错误。如何在单元测试期间处理全局变量。任何帮助表示赞赏

尝试了@mock @patch,但似乎没有任何效果。执行测试用例时,值似乎为空

[注册.py]

    import os 

    #Global Variables
    DEBUG = os.environ.get("EnableLog")
    rest_endpoint = os.environ.get('restApiEndpoint')
    db_fn_endpoint = rest_endpoint+":3000/rpc/"

    def lambda_handler(event,context):
    return "success" #to see if this works

    if __name__ == "__main__":
        lambda_handler('', '')

单元测试 [test_registration.py]

    import json
    import pytest
    import sys, os
    from mock import patch
    from businesslogic import registration

    @mock.patch.dict(os.environ,{'EnableLog':'True'})
    @mock.patch.dict(os.environ,{'restApiEndpoint':'http://localhost'})

    @patch('registration.restApiEndpoint', 'http://localhost') 


    def test_lambda_handler():
       assert lambda_handler() =="success"

当我运行 pytest test_registration.py

我得到以下异常

businesslogic\registration.py:6: in <module>
    db_fn_endpoint = rest_endpoint+":3000/rpc/"
E   TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

标签: python

解决方案


You can pass it as restApiEndpoint=http://localhost python -m pytest OR you if you are using sh file to run export before running test export restApiEndpoint=http://localhost


推荐阅读