单元测试AWS python lambda全局变量补丁不起作用

时间:2019-07-19 18:13:16

标签: python

我正在尝试对基于Python的AWS Lambda代码进行单元测试。我试图使用补丁来模拟环境变量,但会引发错误。如何在单元测试期间处理全局变量。感谢您的帮助

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

[registration.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'

1 个答案:

答案 0 :(得分:-2)

您可以将其作为restApiEndpoint=http://localhost python -m pytest传递 要么 您是否使用sh文件在运行测试之前运行导出 export restApiEndpoint=http://localhost