首页 > 解决方案 > 单元测试用全局部分模拟 AWS Lambda 函数,Python

问题描述

我正在编写一个 python lambda,并在 lambda 的全局部分对外部服务进行了初始化。我如何模拟这个外部依赖项,因为它是在创建我的类时初始化的?

数据加载.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()

标签: python-3.xamazon-web-servicesfunctionaws-lambdamocking

解决方案


推荐阅读