How can I test AWS Lambda functions locally?

我与影子孤独终老i 提交于 2020-01-01 02:11:26

问题


Explain to me please what is the best way to locally test the lambda function. I used sam local and this solution https://github.com/lambci/docker-lambda for testing, but for example, where I invoke one lambda from another error occurs. In general, I can't make stubs for methods since lambda runs in a container


回答1:


There are a couple of options. Following two are some popular ones.

  • Serverless framework along with the serverless-offline plugin.
  • LocalStack



回答2:


This is how I test local lambda functions without Serverless frameworks, I run an HTTP post on local (quite easy setup for Go)

  • decouple lambda logic like so:
func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    _, _ = pretty.Println("parsed:", request.Body)
    return events.APIGatewayProxyResponse{Body: "response is working", StatusCode: 200}, nil
}
  • main function then checks if it is a local instance then run local post endpoint, else start lambda
func main() {
    environment := loadEnv()
    if environment == "develop" {
        router.NewRouter()
        select {}
    } else {
        lambda.Start(lambdahandler.HandleRequest)
    }
}
  • in between you have an Adapter Pattern that converts your http request to whatever your lambda function accepts, for example:
func MapToApiGateway(w http.ResponseWriter, r *http.Request) (interface{}, error) {
    request := new(EmailResponderRequest)
    if err := json.NewDecoder(r.Body).Decode(request); err != nil {
        return err.Error(), err
    }
    apiGatewayRequest := mapHttpRequestToGatewayRequest(*request)
    events, err := lambdahandler.HandleRequest(nil, apiGatewayRequest)
    if err != nil {
        return err.Error(), err
    }
    return events, nil
}


来源:https://stackoverflow.com/questions/50099231/how-can-i-test-aws-lambda-functions-locally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!