gpt4 book ai didi

amazon-web-services - 为 Golang Lambda 功能单元测试模拟 AWS API 网关请求和 DynamoDB

转载 作者:数据小太阳 更新时间:2023-10-29 03:20:52 26 4
gpt4 key购买 nike

设置

  • Windows 10
  • 去v1.10.3
  • aws cli v1.16.67

我想做什么

测试使用 golang 编写的 AWS Lambda 函数。该函数接受来自 API 网关 的请求,然后使用 DynamoDB 执行一些操作。以下大部分内容摘自 this文章(我是 Go 的新手)

package main

import (
"encoding/json"
"log"
"net/http"
"os"
"regexp"

"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)

var uuidRegexp = regexp.MustCompile(`\b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b`)
var errorLogger = log.New(os.Stderr, "ERROR ", log.Llongfile)

type job struct {
ID string `json:"id"`
ClientID string `json:"clientId"`
Title string `json:"title"`
Count int `json:"count"`
}

// CreateJobCommand manages interactions with DynamoDB
func CreateJobCommand(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {

if req.Headers["Content-Type"] != "application/json" {
return clientError(http.StatusNotAcceptable) //406
}

newJob := new(job)
err := json.Unmarshal([]byte(req.Body), newJob)

// Ensure request has deserialized correctly
if err != nil {
return clientError(http.StatusUnprocessableEntity) //422
}

// Validate ID and ClientID attributes match RegEx pattern
if !uuidRegexp.MatchString(newJob.ID) || !uuidRegexp.MatchString(newJob.ClientID) {
return clientError(http.StatusBadRequest)
}

// Mandatory field check
if newJob.Title == "" {
return clientError(http.StatusBadRequest)
}

// Put item in database
err = putItem(newJob) // putItem is defined in another file
if err != nil {
return serverError(err)
}

return events.APIGatewayProxyResponse{
StatusCode: 201,
}, nil
}

// Add a helper for handling errors. This logs any error to os.Stderr
// and returns a 500 Internal Server Error response that the AWS API
// Gateway understands.
func serverError(err error) (events.APIGatewayProxyResponse, error) {
errorLogger.Println(err.Error())

return events.APIGatewayProxyResponse{
StatusCode: http.StatusInternalServerError,
Body: http.StatusText(http.StatusInternalServerError),
}, nil
}

// Similarly add a helper for send responses relating to client errors.
func clientError(status int) (events.APIGatewayProxyResponse, error) {
return events.APIGatewayProxyResponse{
StatusCode: status,
Body: http.StatusText(status),
}, nil
}

func putItem(job *job) error {

// create an aws session
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String("us-east-1"),
Endpoint: aws.String("http://localhost:8000"),
}))

// create a dynamodb instance
db := dynamodb.New(sess)

// marshal the job struct into an aws attribute value object
jobAVMap, err := dynamodbattribute.MarshalMap(job)
if err != nil {
return err
}

input := &dynamodb.PutItemInput{
TableName: aws.String("TEST_TABLE"),
Item: jobAVMap,
}

_, err = db.PutItem(input)
return err
}

func main() {
lambda.Start(CreateJobCommand)
}

问题

我想写一组单元测试来测试这个功能。在我看来,我需要做的第一件事是模拟 API 网关请求和 DynamoDB 表,但我不知道该怎么做。

问题

  1. 是否有我应该使用的模拟框架?
  2. 如果有人知道任何对这个主题有帮助的文档,请指出一下好吗? (我的 Google 技能还没有显示出来)

谢谢

最佳答案

我这样做的方法是在指针接收器中传递依赖项(因为处理程序的签名是有限的)并使用接口(interface)。每个服务都有相应的接口(interface)。对于 dynamodb-dynamodbiface。所以在你的情况下 lambda 本身你需要定义一个接收器:

type myReceiver struct {
dynI dynamodbiface.DynamoDBAPI
}

将 main 更改为:

func main() {

sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String("your region")},
))

inj := myReceiver{
dyn: dynamodb.New(sess),
}
lambda.Start(inj.CreateJobCommand)

将处理程序更改为

func (inj *myReceiver) CreateJobCommand(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error)

所有对 dynamodb API 的后续调用都需要通过接口(interface):

    _, err = inj.dynI.PutItem(input)

然后在您的测试函数中您需要模拟响应:


type mockDynamo struct {
dynI dynamodbiface.DynamoDBAPI
dynResponse dynamodb.PutItemOutput

}

func (mq mockDynamo) PutItem (in *dynamodb.PutItemInput) (*dynamodb.PutItemOutput , error) {
return &dynamodv.dynResponse, nil
}


m1: = mockDynamo {

dynResponse : dynamodb.PutItemOutput{

some mocked output
}


inj := myReceiver{
dyn: m1,
}

inj.CreateJobCommand(some mocked data for APIGateway request)

关于amazon-web-services - 为 Golang Lambda 功能单元测试模拟 AWS API 网关请求和 DynamoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54214305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com