Skip to content

Docs: Testing your code - API Gateway HTTP API #1686

Closed
@bnsouza

Description

@bnsouza

What were you searching in the docs?

I was looking for an example to test my new lambda function that I used API Gateway HTTP API and the exampled provided was not working.

The example in docs is this:

@pytest.fixture
def lambda_context():
    @dataclass
    class LambdaContext:
        function_name: str = "test"
        memory_limit_in_mb: int = 128
        invoked_function_arn: str = "arn:aws:lambda:sa-east-1:123456789012:function:test"
        aws_request_id: str = "cdf446432739-2ce8-b7e4-f6d2-3db856ad"

    return LambdaContext()


def test_lambda_handler(lambda_context):
    minimal_event = {
        "path": "/todos",
        "httpMethod": "GET",
        "requestContext": {"requestId": "227b78aa-779d-47d4-a48e-ce62120393b8"},  # correlation ID
    }

    ret = assert_http_response_module.lambda_handler(minimal_event, lambda_context)
    assert ret["statusCode"] == 200
    assert ret["body"] != ""

And this was the result:

======================================= test session starts =======================================
platform darwin -- Python 3.8.12, pytest-7.2.0, pluggy-1.0.0
rootdir: /Volumes/HD/Whatever, configfile: pyproject.toml, testpaths: backend/tests
plugins: typeguard-2.13.3, anyio-3.6.2
collected 1 item

backend/tests/microservices/cobranca_clientes/test_index.py F                               [100%]

============================================ FAILURES =============================================
___________________________________ test_handler_auth_redirect ____________________________________

lambda_context = lambda_context.<locals>.LambdaContext(function_name='test', 
memory_limit_in_mb=128, invoked_function_arn='arn:aws:lambda:sa-east-1:123456789012:function:test', 
aws_request_id='cdf446432739-2ce8-b7e4-f6d2-3db856ad')

    def test_handler_auth_redirect(lambda_context):
        minimal_event = {
            "path": "/auth",
            "httpMethod": "GET",
            "requestContext": {"requestId": "227b78aa-779d-47d4-a48e-ce62120393b8"}, #correlationID
        }

>       ret = handler(minimal_event, lambda_context)

backend/tests/microservices/cobranca_clientes/test_index.py:40:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
...aws_lambda_powertools/logging/logger.py:402: in decorate
    return lambda_handler(event, context, *args, **kwargs)
backend/microservices/cobranca_clientes/index.py:93: in handler
    return app.resolve(event, context)
...aws_lambda_powertools/event_handler/api_gateway.py:540: in resolve
    response = self._resolve().build(self.current_event, self._cors)
...aws_lambda_powertools/event_handler/api_gateway.py:604: in _resolve
    method = self.current_event.http_method.upper()
...aws_lambda_powertools/utilities/data_classes/api_gateway_proxy_event.py:260: in http_method
    return self.request_context.http.method
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <aws_lambda_powertools.utilities.data_classes.common.RequestContextV2Http object 
    at 0x1111b0b50>

    @property
    def method(self) -> str:
>       return self["requestContext"]["http"]["method"]
E       KeyError: 'http'

...aws_lambda_powertools/utilities/data_classes/common.py:336: KeyError
===================================== short test summary info =====================================
FAILED backend/tests/microservices/cobranca_clientes/test_index.py::test_handler_auth_redirect - 
KeyError: 'http'
======================================== 1 failed in 0.31s ========================================

Is this related to an existing documentation section?

https://awslabs.github.io/aws-lambda-powertools-python/2.1.0/core/event_handler/api_gateway/#testing-your-code

How can we improve?

What I made was debuging the errors and made a new `minimal_event` dict. What I cannot do for now (because of time - and two kids) is to find if it was a Documentation error or a code error.

Got a suggestion in mind?

What I do to resolve the problem is to change the minimal_event dict to this:

    minimal_event = {
        "rawPath": "/todos",
        "requestContext": {
            "http": {
                "method": "GET",
            },
            "stage": "$default",
        },
    }

And the result now was this:

======================================= test session starts =======================================
platform darwin -- Python 3.8.12, pytest-7.2.0, pluggy-1.0.0
rootdir: /Volumes/HD/Whatever, configfile: pyproject.toml, testpaths: backend/tests
plugins: typeguard-2.13.3, anyio-3.6.2
collected 1 item

backend/tests/microservices/cobranca_clientes/test_index.py .                               [100%]

======================================== 1 passed in 0.17s ========================================

Acknowledgment

  • I understand the final update might be different from my proposed suggestion, or refused.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions