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'
The AWS Lambda context object is not a dictionary. aws_request_id is not a dictionary key, it's an attribute of the context object. Modifying your mock to be a dictionary will lead to your code breaking when being run as an actual Lambda function. The correct way to solve this is to ensure that your mock object is an authentic reproduction of the actual Lambda context object.
You could write a simple class and set the aws_request_id attribute on it as follows:
class LambdaContext:
aws_request_id = 'abcdef'
# ...
context = LambdaContext()
aws_request_id = context.aws_request_id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With