Sub topic 13
Testing locally and debugging failures
This chapter assumes you have the handler and SAM template from the earlier chapters, Python 3 with pytest, and the AWS SAM CLI. Docker is needed only for the sam local commands.
Test the handler without AWS
A Lambda handler is a plain function that takes a dict. You can call it directly in a unit test. Build only the event fields your handler reads.
import json
from app import handler
def make_event(route, path_params=None, body=None):
return {
"version": "2.0",
"requestContext": {"routeKey": route},
"pathParameters": path_params,
"body": body,
}
def test_get_item():
response = handler(make_event("GET /items/{id}", {"id": "42"}), None)
assert response["statusCode"] == 200
assert json.loads(response["body"]) == {"id": "42"}
def test_post_rejects_bad_json():
response = handler(make_event("POST /items", body="{oops"), None)
assert response["statusCode"] == 400
def test_unknown_route():
response = handler(make_event("DELETE /items/{id}"), None)
assert response["statusCode"] == 404Run it from the project root with PYTHONPATH=src pytest.
Run it through SAM locally
Unit tests skip the packaging, runtime and template. To check those, save a sample event as events/get_item.json:
{
"version": "2.0",
"routeKey": "GET /items/{id}",
"rawPath": "/items/42",
"headers": {"content-type": "application/json"},
"pathParameters": {"id": "42"},
"requestContext": {"routeKey": "GET /items/{id}"},
"isBase64Encoded": false
}sam build
sam local invoke ItemsFunction --event events/get_item.json
sam local start-api
curl -i http://127.0.0.1:3000/items/42invoke runs the function once with your event. start-api serves your routes on localhost, so the same curl calls work as after deployment.
Read the status code first
A failing request usually tells you where to look. The status code narrows the cause before you open any logs.
| Status | Typical cause |
|---|---|
| 404 `Not Found` | No route matches the method and path, and there is no `$default` route. This message comes from API Gateway, not your code. |
| 401 / 403 | The authorizer rejected the request. Your function never ran. |
| 500 | An unhandled exception, a function timeout, or a missing invoke permission. |
| 504 | The integration timeout expired. The HTTP API maximum is 30 seconds. |
Find the error in the logs
Your code returns a 404 only when it chooses to. A 404 whose body is {"message":"Not Found"} therefore came from API Gateway. Compare your request against the route key exactly, including the HTTP method.
For a 500, the cause is in the function's log group. Tail it while you repeat the request:
sam logs --stack-name items-api --name ItemsFunction --tailLook for a Python traceback or a line starting Task timed out. If the log group has no new entries, the function was never invoked. In that case, check the integration and the Lambda resource permission.
Exercise
A client calls GET /item/42, but your route is GET /items/{id}. The response is {"message":"Not Found"} and the function's log group shows no new entries. Why, and what do you fix?
Show answer
The path does not match any route, so API Gateway answers with a 404 before invoking Lambda. That is why the log group is empty. Fix the client to call /items/42, or add a route that matches the path you want.