question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Docs: Testing your code - API Gateway HTTP API

See original GitHub issue

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.

Issue Analytics

  • State:closed
  • Created 10 months ago
  • Comments:9 (7 by maintainers)

github_iconTop GitHub Comments

1reaction
heitorlessacommented, Nov 9, 2022

Just rebuilt the latest docs - https://awslabs.github.io/aws-lambda-powertools-python/2.2.0/core/event_handler/api_gateway/#testing-your-code

Available now and thank you again for the contribution ❤️

image
1reaction
bnsouzacommented, Nov 8, 2022

Ohhh… i get it! I remembered another issue i get to make the PR: the pyproject.toml is broken because of Poetry version and the new group parameter… so to make the PR I have to do here on Github, because I the pre-commit hooks are getting errors… If you need something, just let me know!

Abraço!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Use the API Gateway console to test a REST API method
Test a method with the API Gateway console ; Request is the resource's path that was called for the method. ; Status is...
Read more >
amazon-api-gateway-developer-guide/how-to-test-method.md ...
Test a method with the API Gateway console · Request is the resource's path that was called for the method. · Status is...
Read more >
Test and monitor your API Gateway endpoints with Assertible
In this post, I'll walk through creating a basic API Gateway example in AWS and setting up API testing, monitoring, and alerts in...
Read more >
API Gateway Test - IBM
API Gateway Test · HTTP 401 response code. Check API configuration and ensure that the username and password provided are correct. · Invalid...
Read more >
REST API (API Gateway v1) - Serverless Framework
This guide documents using API Gateway v1 REST API via the http event. ... response (headers, status code, body) in the code of...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found