Search code examples
pythonamazon-web-servicesaws-lambdapytestboto3

Lambda handler Context aws_request_id using pytest setup


I can mock event in pytest to test lambda_handler(event, context) but not able to test context and only aws_request_id is used from context. I am trying following.

context = {
            'aws_request_id': 'abcdef',
            'log_stream_name': '1f73402ad',
            'invoked_function_arn': 'arn:aws:lambda:region:1000:function:TestCFStackNam-TestLambdaFunctionResourceName-ABC-1234F',
            'client_context': None,
            'log_group_name': '/aws/lambda/TestCFStackName-TestLambdaFunctionResourceName-ABC-1234F',
            'function_name': 'TestCloudFormationStackName-TestLambdaFunctionResourceName--ABC-1234F',
            'function_version': '$LATEST',
            'identity': '<__main__.CognitoIdentity object at 0x1fb81abc00>',
            'memory_limit_in_mb': '128'
}


lambda_handler(event, context)
aws_request_id = context.aws_request_id

Error - 

  AttributeError: 'dict' object has no attribute 'aws_request_id'

Solution

  • This

    aws_request_id = context.aws_request_id
    

    is not how you access values stored in dictionary in Python. Change it to

    aws_request_id = context['aws_request_id']