【问题标题】:pytest json.decoder.JSONDecodeErrorpytest json.decoder.JSONDecodeError
【发布时间】:2021-12-20 22:02:56
【问题描述】:
  • 列表项

嗨,

我需要 pytest 这个函数

def lambda_handler(event, context):
 message = json.loads(event['Records'][0]['Sns']['Message'])

但由于 json 错误而失败

def test_lambda_handler():
    event = {
    "Records": [
        {
            "Sns" : { "Message" : "test" }
        }
    ]
    }
    response = fw_init.lambda_handler( event,"")    
JSONDecodeError("Expecting value", s, err.value) from None
E           json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

【问题讨论】:

    标签: aws-lambda pytest boto3 amazon-sns botocore


    【解决方案1】:

    函数loads() 从字符串反序列化 JSON。您试图将“消息”字段值解码为 JSON。

    lambda_handler 函数的第一个参数是 JSON 格式的字符串,根据 AWS 文档。

    你需要将一个序列化的数据传递给lambda_handler函数:

    response = fw_init.lambda_handler(json.dumps(event) ,"")
    

    函数lambda_handler()需要先反序列化数据,然后获取字段值:

    def lambda_handler(event, context):
        data = json.loads(event)
        message = data['Records'][0]['Sns']['Message']
    

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-27
      • 1970-01-01
      • 2021-09-20
      • 2022-01-24
      • 2019-01-04
      相关资源
      最近更新 更多