我已经编写了一个代码,它将为我获取SSM参数。
import boto3
client = boto3.client('ssm')
def lambda_handler(event, context):
return client.get_parameter(Name=event["param"], WithDecryption=True)
if __name__ == '__main__':
print(lambda_handler({"param": "/mypath/password"}, ""))但是,我无法编写测试用例,因为我尝试过使用moto,但出于某种原因,它仍然给出了SSM存储的实际值。
import os
import boto3
from moto import mock_ssm
import pytest
from handler import lambda_handler
@pytest.fixture
def aws_credentials():
os.environ["AWS_ACCESS_KEY_ID"] = "testing"
os.environ["AWS_SECRET_ACCESS_KEY"] = "testing"
os.environ["AWS_SECURITY_TOKEN"] = "testing"
os.environ["AWS_SESSION_TOKEN"] = "testing"
@mock_ssm
def test_ssm():
ssm = boto3.client('ssm')
ssm.put_parameter(
Name="/mypath/password",
Description="A test parameter",
Value="this is it!",
Type="SecureString"
)
resp = lambda_handler({"param": "/mypath/password"}, "")
assert resp["Parameter"]["Value"] == "this is it!"我是不是无意中遗漏了一些东西,我应该做些什么来使它工作,还是有一种替代方法来模拟python中的SSM。
发布于 2021-09-07 05:55:27
当您通过ssm对@mock_ssm进行修补时,您已经将handler.py中的变量handler.client实例化为boto3客户端的实际实例,因此它不是修补版本。
解决方案1:
仅在lambda处理程序期间初始化客户端,以便在创建修补程序时已经生效。
handler.py
import boto3
# client = boto3.client('ssm') # Remove this instantiation
def lambda_handler(event, context):
client = boto3.client('ssm') # Move it here
return client.get_parameter(Name=event["param"], WithDecryption=True)
if __name__ == '__main__':
print(lambda_handler({"param": "/mypath/password"}, ""))解决方案2:
只有在修补程序生效后才导入/执行handler.py文件。
test_handler.py
...
# from handler import lambda_handler # Remove this import
...
@mock_ssm
def test_ssm():
from handler import lambda_handler # Move it here
...
...解决方案3
修补程序生效后重新加载handler.py。
...
@mock_ssm
def test_ssm():
from importlib import reload
import sys
reload(sys.modules['handler'])
...
...输出
$ pytest -q -rP
============================================================================================ PASSES ============================================================================================
1 passed in 1.35shttps://stackoverflow.com/questions/69082090
复制相似问题