Skip to content

Feature request: Utilities for creating events (ALB, APIGateway) for testing #7951

@chriselion

Description

@chriselion

Use case

In the "Testing your code" section of the documentation, the example uses a dictionary for an event to pass to the handler function, and there's an additional link to the test event json files.

Neither of those are great for testing event handlers in user code though - building a dictionary is tedious and error prone, and the test events aren't distributed with package and would require changing a lot of fields. In either case, it's not possible to run type checking on the events, and it's easy to make a typo in a field name.

Solution/User Experience

Add utility functions for creating event dictionaries. As an example, something like

def build_alb_event(
    *,
    path: str,
    method: str,
    body: BaseModel | dict | None = None,
    query_params: dict[str, str] | None = None,
    headers: Mapping[str, str | bytes | None] | None = None,
) -> dict[str, Any]:
    event: dict[str, Any] = {
        "httpMethod": method,
        "path": path,
        "requestId": "some_request_id",
        "requestContext": {"elb": {"targetGroupArn": ":target:"}},
    }
    if body is not None:
        if isinstance(body, BaseModel):
            event["body"] = body.model_dump_json()
        else:
            event["body"] = json.dumps(body)

    if query_params is not None:
        event["queryStringParameters"] = query_params

    if headers:
        event["headers"] = headers

    return event

(This is missing some things like multiValueQueryStringParameters, but hopefully it gets the idea across)

Alternative solutions

Another approach would be to make new Pydantic models, then you could call `.model_dump()` on the end. The existing event classes that inherit from BaseProxyEvent (e.g. ALBEvent) aren't suitable for this, though.

Acknowledgment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature-requestfeature requesttriagePending triage from maintainers

    Type

    No type

    Projects

    Status

    Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions