Gre*_*uff 4 unit-testing go amazon-web-services
设置
我想做什么
测试使用golang. 该函数接受来自 的请求API Gateway,然后使用DynamoDB. 大多数的下方已经从采取这个文章(我一起去一个新手)
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)
}
Run Code Online (Sandbox Code Playgroud)
问题
我想写一组单元测试来测试这个功能。在我看来,我需要做的第一件事是模拟 API 网关请求和 DynamoDB 表,但我不知道如何做到这一点。
问题
谢谢
我这样做的方法是在指针接收器中传递依赖项(因为处理程序的签名是有限的)并使用接口。每个服务都有对应的接口。对于 dynamodb-dynamodbiface。因此,在 lambda 本身的情况下,您需要定义一个接收器:
type myReceiver struct {
dynI dynamodbiface.DynamoDBAPI
}
Run Code Online (Sandbox Code Playgroud)
将主要更改为:
func main() {
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String("your region")},
))
inj := myReceiver{
dyn: dynamodb.New(sess),
}
lambda.Start(inj.CreateJobCommand)
Run Code Online (Sandbox Code Playgroud)
将处理程序更改为
func (inj *myReceiver) CreateJobCommand(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error)
Run Code Online (Sandbox Code Playgroud)
并且所有对 dynamodb API 的后续调用都需要通过接口:
_, err = inj.dynI.PutItem(input)
Run Code Online (Sandbox Code Playgroud)
然后在您的测试功能中,您需要模拟响应:
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)
Run Code Online (Sandbox Code Playgroud)