pytest json.decoder.JSONDecodeError

Viewed 240
  • List item

Hi,

I need to pytest this function

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

But it failed by json error

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)
1 Answers

Function loads() deserializes JSON from string. You trying to decode "Message" field value as JSON.

lambda_handler function's first argument is a JSON-formatted string, according to AWS documentation.

You need to pass an serialized data to lambda_handler function:

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

In function lambda_handler() you need to deserialize data first, and then get field value:

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