带有全局部分的Python的单元测试模拟AWS Lambda函数

时间:2019-06-05 01:31:34

标签: python-3.x amazon-web-services function aws-lambda mocking

我正在写一个带有初始化到lambda全局部分中的外部服务的python lambda。在创建类时如何初始化外部依赖关系?

data_load.py

from elasticsearch import Elasticsearch,

# Global section - executed once for the life time of the container
def get_elastic_search_connection():
    try:
        client = Elasticsearch(
            hosts=[{'host': "host", 'port': 9191}],
            use_ssl="true",
            verify_certs="true",
            connection_class=RequestsHttpConnection)
        return client
    except Exception as e:
        LOGGER.error("Unable to connect to ES")
        exit(1)

es_client = get_elastic_search_connection()


# handler section - executed once per function invocation
def lambda_handler(event, context):
    es_client.bulk(body="body", index="index", doc_type="doc", _source=False)

在我的测试中,当import语句导入data_load.py时,它将尝试初始化lambda的全局部分,该部分试图建立与主机地址的http连接。如何创建data_loay.py的部分模拟,以便可以测试lambda_handler方法? es_client必须在全局部分中初始化。如何将模拟项注入全局部分?

test_data_load.py

import unittest
import search_lambda.data_load.data_load


class TestDatLoad(unittest.TestCase):

    def test_data_load(self):
        print("Hello")


if __name__ == '__main__':
    unittest.main()

0 个答案:

没有答案