python-3.x - 单元测试用全局部分模拟 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()
解决方案
推荐阅读
- angular - 发送图像和字符串表
- laravel - 如何使用 musonza/groups 包查找组
- java - Java 文件而不是我下载的 java 包中的 jar 文件?
- python - 如何在 Python 中访问单个字符串?
- python - 检测和隔离图像中的线条
- google-sheets - 如何设置一个函数来突出表中存在一组两个特定值?
- c - 如何访问不相关和以前运行的进程的标准输入/标准输出?
- javascript - 使用 async / await 未按正确顺序触发的函数
- ocaml - OCaml 中的 Fizbuzz 得到错误“与类型单元不兼容”
- c# - 从 NetworkStream 读取数据