如何从DynamoDB获取项目并存储要用于Pytest的元素?

问题描述

如何从DynamoDB中获取项目并在Pytest中使用环境(元素)?我的函数使用boto3获取环境,并将环境存储在名为env[]的列表中。

def get_environment():
    """
    Retrieves environment from DynamoDB
    :param ssm_client:
    :return:
    """
    env = []
    try:
        response = dynamodb_client.scan(
            TableName='accounts',AttributesToGet=['account_id','environment'],)
        env =  [ s['environment'] for s in response['Items'] ]
        return env
    except Exception as e:
        print("[ERROR] Failed")

响应:

[{'environment': {'S': 'sandBox'},'account_id': {'S': '409XX'}},{'environment': {'S': 'services'},'account_id': {'S': '3228XX'}},{'environment': {'S': 'non-production'},'account_id': {'S': '1145XX'}},{'environment': {'S': 'production'},'account_id': {'S': '37988XX'}},'account_id': {'S': '38856XXX'}},'account_id': {'S': '10819XXXX'}}]

当我尝试打印环境名称时,它会引发错误

def print_environment():
    response = get_environment()
    environment =  [ item['environment'] for item in response ]
    print(environment)

  File "app.py",line 250,in print_environment
    environment =  [ item['environment'] for item in response ]
  File "app.py",in <listcomp>
    environment =  [ item['environment'] for item in response ]
KeyError: 'environment'

我只想获取特定帐户ID的环境,并将其存储在environment中,然后在pytest中使用它。例子

 def test_environment():
    environment = get_environment()
    account_id = get_account_ids()
    for accounts in account_id:     
        if (environment = 'production') then assert something .....

解决方法

您的词典列表不包含“环境”作为键。

它包含“环境”所指向的值。

此类值的示例是{'S': 'sandbox'},'account_id': {'S': '409XX'}}