1

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

botocore.exceptions.ClientError:调用GetParameter操作时发生错误(UnrecognizedClientException):请求中包含的安全令牌无效。

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
4

2 回答 2

5

一位同事向我展示了这行得通:

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.

于 2019-08-07T07:38:19.473 回答
2

要解决凭据问题,请添加一个定义假凭据的装置。

@pytest.fixture
def aws_credentials():
    """Mocked AWS Credentials for moto."""
    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"


@pytest.fixture
def ssm_mock(aws_credentials):
    with mock_ssm():
        client = boto3.client("ssm")
        client.put_parameter(
            Name="/foo/bar",
            Description="A test parameter",
            Value="this is it!",
            Type="SecureString",
        )
        yield
于 2021-08-24T00:42:29.187 回答