簡體   English   中英

Python:使用 Click 模擬 AWS

[英]Python: Mock AWS with Click

我有一個 click cli 應用程序,我正在嘗試模擬 AWS SSM Parameter Store,但 runner.invoke 沒有返回預期結果。

這是test_demo.py

from click.testing import CliRunner

import os
import boto3
from moto import mock_ssm
import pytest


@pytest.fixture(scope='package')
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'
    os.environ['AWS_DEFAULT_REGION'] = 'us-west-2'


@pytest.fixture(scope='package')
def ssm(aws_credentials):
    with mock_ssm():
        yield boto3.client('ssm')


def test_get_mock_ssm(ssm):
    # We need to create the ssm entry first since this is all in Moto's 'virtual' AWS account
    ssm.put_parameter(
        Name='test',
        Description='name',
        Value='text',
        Type='String',
        Overwrite=True,
        Tier='Standard',
        DataType='text'
    )
    out = ssm.get_parameter(Name='test')
    print('without cli')
    print(out)
    from src.cli import entrypoint
    runner = CliRunner()
    response = runner.invoke(entrypoint, ["get", "--name", "test"])
    print('with cli')
    print(response)
    assert response.exit_code == 0

測試結果如下:

without cli
{'Parameter': {'Name': 'test', 'Type': 'String', 'Value': 'text', 'Version': 1, 'LastModifiedDate': datetime.datetime(2020, 5, 31, 9, 3, 21, 920000, tzinfo=tzlocal()), 'ARN': 'arn:aws:ssm:us-west-2:1234567890:parameter/test'}, 'ResponseMetadata': {'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'amazon.com'}, 'RetryAttempts': 0}}

with cli
<Result okay>
PASSED

我希望 cli 的輸出與無 cli 相同。

點擊代碼:

import click

import manage_secrets


@click.group()
def entrypoint():
    pass


@entrypoint.command()
@click.option('--name', required=True,
              help='Name of parameter to get value from SSM')
def get(name):
    """get secrets"""
    click.echo("getting value of: {0}" .format(name))
    print(manage_secrets.get_value_from_parameter_store(name))


if __name__ == "__main__":
    entrypoint()

manage_secrets 代碼:

import boto3

parameter_name = None


def get_value_from_parameter_store(name):
    client = boto3.client('ssm')
    try:
        parameter = client.get_parameter(Name=name, WithDecryption=True)
        return parameter
    except client.exceptions.ParameterNotFound:
        print("parameter not found")

我添加了一個返回值,它只是默認值,而不是解析,我認為 ssm.get_parameter 是一樣的。 我不確定我錯過了什么。 任何指示或建議?

我的結果還可以,我需要從測試中得到response.output

這有幫助: https://gist.github.com/lbillingham/6412cdc19f9a44901b03841e0443fbf7

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM