Skip to content

New testing utility #1169

@heitorlessa

Description

@heitorlessa

Original author: @beanaroo

Runtime: Python

Is your feature request related to a problem? Please describe

As per this discussion, creating test events for Lambda event sources is a laborious process.

Finding the correct event with default values tend to be 1/ invoking a Lambda function, 2/ logging the event, 3/ extracting the log event from CloudWatch, 4/ serializing back to native Python object, 5/ creating a Pytest fixture that can be used across tests.

NOTE: When the event source is supported by SAM CLI, this cycle can be shortened with sam local generate-event sub-command

This cycle repeats when you're trying to mock Lambda Context for libraries and middlewares that make use of it.

Describe the solution you'd like

Make tests events available in the project as Dataclasses that can be initialized with default values and changed as we see please.

from aws_lambda_powertools.utilities.testing import LambdaContext, ApiGatewayProxyEvent

import app

def test_handler():
    app.handler(event=ApiGatewayProxyEvent(), context=LambdaContext())

Describe alternatives you've considered

Create my own default Lambda Context using LambdaContext typing

import pytest
from aws_lambda_powertools.utilities.typing import LambdaContext


class MockLambdaContext(LambdaContext):

    def __init__(self):
        self._function_name = 'test-fn'
        self._memory_limit_in_mb = 128
        self._invoked_function_arn = 'arn:aws:lambda:us-east-1:12345678:function:test-fn'
        self._aws_request_id = '52fdfc07-2182-154f-163f-5f0f9a621d72'


@pytest.fixture
def lambda_context() -> LambdaContext:
    return MockLambdaContext()


def test_handler(lambda_context):
    app.handler(event={}, context=lambda_context)

If you provide guidance, is this something you'd like to contribute?

Additional context

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Closed

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions