pytest - 我怎样才能从 boto3 模拟 ssm?

标签 pytest boto3 moto

我试过 moto,但我总是得到:

botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the GetParameter operation: The security token included in the request is invalid.

MVCE: test_example.py
import moto
import boto3


def ssm():
    boto3.setup_default_session()
    with moto.mock_ssm():
        ssm = boto3.client('ssm', region_name='us-east-1',
                           aws_access_key_id='testing',
                           aws_secret_access_key='testing')
        ssm.put_parameter(
            Name="/foo/bar",
            Description="A test parameter",
            Value="this is it!",
            Type="SecureString",
        )
        yield ssm


def get_ssm_param(ssm_parameter_name):
    session = boto3.Session()
    ssm_client = session.client("ssm")
    param = ssm_client.get_parameter(Name=ssm_parameter_name, WithDecryption=True)
    return param["Parameter"]["Value"]


def test_get_ssm_param():
    foo = get_ssm_param('/foo/bar')
    assert foo == "this is it!"

执行

pytest test_example.py

我的系统

moto==1.3.13
boto==2.49.0
boto3==1.9.201
botocore==1.12.201

最佳答案

一位同事向我展示了这个方法:

from moto import mock_ssm
import boto3


def get_ssm_param(ssm_parameter_name):
    session = boto3.Session()
    ssm_client = session.client("ssm")
    param = ssm_client.get_parameter(Name=ssm_parameter_name, WithDecryption=True)
    return param["Parameter"]["Value"]

@mock_ssm
def test_get_ssm_param():
    ssm = boto3.client('ssm')
    ssm.put_parameter(
        Name="/foo/bar",
        Description="A test parameter",
        Value="this is it!",
        Type="SecureString",
    )
    foo = get_ssm_param('/foo/bar')
    assert foo == "this is it!"

但是当您将凭据添加到 boto3.client 时它会中断。

关于pytest - 我怎样才能从 boto3 模拟 ssm?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57378788/

相关文章:

Python Lambda没有找到这样的文件或目录运行时问题

python - 如何导入 boto3 ssm ParameterNotFound 异常?

Python 测试 : Simulate ImportError

python - 使 pytest 仅在完整测试套件运行时才需要代码覆盖

python - requests.get() 在 aws lambda 中抛出异常

amazon-web-services - 尝试使用 moto 模拟 s3 时出现 NoSuchBucket 错误

android - 打开/sys/class/power_supply/bms/resistance 时出错

python - Pytest 模拟补丁 - 如何排除故障?

python - self.locals SyntaxError : Missing parentheses in call to 'exec' 中的 pytest 执行代码

amazon-web-services - 解析参数 '--targets' : Expected: '=' , 时出错: '' ' 对于输入: '[Key:InstanceIds]'