How to mock AWS Lambda context when testing lambda handler in Go? - amazon-web-services

I have an S3-triggered AWS Lambda written in Go. I've been able to successfully test all of the ancillary code, however, I'm stuck trying to test the lambda handler.
Here's the signature of my handler:
func HandleRequest(ctx context.Context, s3Event events.S3Event)
Here's the test code:
package main
import (
"context"
"encoding/json"
"testing"
"github.com/aws/aws-lambda-go/events"
"github.com/stretchr/testify/assert"
)
func TestHandleRequest(t *testing.T) {
// 1. read JSON from file
inputJSON, err := readJSONFromFile("./testdata/s3-event.json")
if err != nil {
t.Errorf("could not open test file. details: %v", err)
}
// 2. de-serialize into Go object
var inputEvent events.S3Event
if err := json.Unmarshal(inputJSON, &inputEvent); err != nil {
t.Errorf("could not unmarshal event. details: %v", err)
}
// 3. How can I mock the context.Context?
assert.NoError(t, HandleRequest(context.Context, inputEvent))
}
I have no clue how I should mock the context.Context. I couldn't find any examples online either.
Anyone know? Does my code look idiomatic for testing an S3-triggered, Go Lambda?

‘context.Context’ is designed to be an immutable value (even though it is literally an interface). So I wouldn’t be concerned with mocking it.
There are two ways to create empty contexts (‘context.Background()’ and ‘context.TODO()’). I would start with those. If you want to set something on the context, check out documentation on the context package.

Will context.TODO satisfy your needs?
https://golang.org/pkg/context/#TODO

Related

Porting a golang server app to aws lambda + api gateway

I am trying to port a server running a small golang app to AWS Lambda. I am not very familiar with golang and to deploy to a server I have just followed the instructions in the repo.
It runs a server with net/http, the main.go is as follows:
func main() {
r := new(route.Router)
r.HandleFunc("/squares", squares.Random)
// ... more Handlers
log.Println("Listening on " + os.Getenv("PORT"))
err := http.ListenAndServe(":"+os.Getenv("PORT"), r)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}
Now I have found this drop-in replacement repo on Github for ListenAndServe, apex/gateway, but I think I am missing a fundamental step in making it work.
What I've done is download and import of the library
import (
...
"github.com/apex/gateway/v2"
)
then simply replace the function in main, zip and upload to aws lambda
func main() {
r := new(route.Router)
r.HandleFunc("/squares", squares.Random)
// ... more Handlers
// log.Println("Listening on 8080")
err := gateway.ListenAndServe(":8080", r)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}
then I set up an http API Gateway and link to the lambda function.
It doesn't work. I think I'm missing something but I can't figure out what. From the example on the apex/gateway repo, I don't see what I'm missing.
The app is Tinygraphs fwiw.
Thank you
Edit:
As per Adrians comment, when I go to the api link I get
{"message":"Not Found"}
Hey User I believe you are not understanding how API Gateway and Lambda works properly
You do not need to set up a route listening on 8080 that is effectively what API Gateway is doing and then forwarding the request to your code running on the lambda. Which is normally in this format:
package main
import (
"fmt"
"context"
"github.com/aws/aws-lambda-go/lambda"
)
type MyEvent struct {
Name string `json:"name"`
}
func HandleRequest(ctx context.Context, name MyEvent) (string, error) {
return fmt.Sprintf("Hello %s!", name.Name ), nil
}
func main() {
lambda.Start(HandleRequest)
}
Was a pretty stupid mistake.
I had defined the api path as / instead of /{proxy+}, so it wasn't accepting a non-root url whereas the invoke url is like this:
https://XXXXXXXX.execute-api.us-east-1.amazonaws.com/squares/tinygraphs?theme=frogideas&numcolors=4&size=220&fmt=svg
Thank you everyone who looked at this.
(regarding the port, according to this, the port specified is just ignored by gateway.ListenAndServe)

How to mock a method of a third party package

I had a simple function which connects to mongoDB and create a new document.
Now how do I mock the methods of the imported mongo package while unit testing.
Ive tried to mock GinContext by monkeypatching.
But unable to proceed with mocking the actual mongoClient as the package is imported.
func CreateUser(c GinContext) {
var userdetail UserDetails
binderr := c.ShouldBindJSON(&userdetail)
fmt.Println(binderr)
if binderr != nil {
c.JSON(500, gin.H{
"message": "Input payload not matching",
"error": binderr,
})
return
}
//-- Client if of type *mongo.Client.
//-- How do I mock the Client.Database, Client.Database.Connection
collection := Client.Database("demo").Collection("users")
ctx, err1 := context.WithTimeout(context.Background(), 10*time.Second)
if err1 != nil {
}
response, err2 := collection.InsertOne(ctx, userdetail)
if err2 != nil {
log.Println("Some error inserting the document")
}
fmt.Println(response.InsertedID)
c.JSON(200, gin.H{
"message": "User created successfully",
})
}
Expected: I should be able to mock or stub Client and provide dummy functionality. Just like in nodeJS we do
spyOn(Client,'Database').and.return(Something)
Every time I'm wondering "how to mock a method", this is mostly related to my code architecture. Not being able to test easily some code means, most of time, that the code is poorly designed and/or too coupled to the used libraries/frameworks. Here, you want to mock Mongo connection only because your code is too tightly related to Mongo (in the CreateUser function). Refactoring could help you to test your code (without any Mongo connection).
I've experienced that using interfaces and dependency injection simplifies
the testing process in Go, and clarifies the architecture. Here is my attempt to help you test your application.
Code refactoring
First, define what you want to do with an interface. Here, you're inserting users, so let's do a UserInserter interface, with a single method for now (Insert, to insert a single user) :
type UserInserter interface {
Insert(ctx context.Context, userDetails UserDetails) (insertedID interface{}, err error)
}
In the code you have provided, you are only using the insertedID, so you probably only need it as output of this Insert method (and an optional error if something gone wrong). insertedID is defined as an interface{} here, but feel free to change to whatever you want.
Then, let's modify your CreateUser method and inject this UserInserter as a parameter :
func CreateUser(c *gin.Context, userInserter UserInserter) {
var userdetail UserDetails
binderr := c.ShouldBindJSON(&userdetail)
fmt.Println(binderr)
if binderr != nil {
c.JSON(500, gin.H{
"message": "Input payload not matching",
"error": binderr,
})
return
}
// this is the modified part
insertedID, err2 := userInserter.Insert(c, userdetail)
if err2 != nil {
log.Println("Some error inserting the document")
}
fmt.Println(insertedID)
c.JSON(200, gin.H{
"message": fmt.Sprintf("User %s created successfully", insertedID),
})
}
This method could be refactored but, to avoid any confusion, I will not touch it.
userInserter.Insert(c, userdetail) replaces here the Mongo dependency in this method by injecting userInserter.
You can now implement your UserInserter interface with the backend of your choice (Mongo in your case). Insertion into Mongo needs a Collection object (the collection we are inserting the user in), so let's add this as an attribute :
type MongoUserInserter struct {
collection *mongo.Collection
}
Implementation of Insert method follows (call InsertOne method on *mongo.Collection) :
func (i MongoUserInserter) Insert(ctx context.Context, userDetails UserDetails) (insertedID interface{}, err error) {
response, err := i.collection.InsertOne(ctx, userDetails)
return response.InsertedID, err
}
This implementation could be in a separated package and should be tested separately.
Once implemented, you can use MongoUserInserter in your main application, where Mongo is the backend. MongoUserInserter is initialized in the main function, and injected in the CreateUser method. Router setup have been separated (also for testing purpose) :
func setupRouter(userInserter UserInserter) *gin.Engine {
router := gin.Default()
router.POST("/createUser", func(c *gin.Context) {
CreateUser(c, userInserter)
})
return router
}
func main() {
client, _ := mongo.NewClient()
collection := client.Database("demo").Collection("users")
userInserter := MongoUserInserter{collection: collection}
router := setupRouter(userInserter)
router.Run(":8080")
}
Note that if some day you want to change the backend, you will only
need to change the userInserter in the main function!
Tests
From a tests perspective, it is now easier to test because we can create a fake UserInserter, like :
type FakeUserInserter struct{}
func (_ FakeUserInserter) Insert(ctx context.Context, userDetails UserDetails) (insertedID interface{}, err error) {
return userDetails.Name, nil
}
(I supposed here UserDetails have an attribute Name).
If you really want to mock this interface, you can take a look at GoMock. In this case though, I'm not sure using a mock framework is required.
And now we can test our CreateUser method with a simple HTTP testing framework (see https://github.com/gin-gonic/gin#testing), without needing a Mongo connection or mocking it.
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCreateUser(t *testing.T) {
userInserter := FakeUserInserter{}
router := setupRouter(userInserter)
w := httptest.NewRecorder()
body := []byte(`{"name": "toto"}`)
req, _ := http.NewRequest("POST", "/createUser", bytes.NewBuffer(body))
router.ServeHTTP(w, req)
assert.Equal(t, 200, w.Code)
assert.Equal(t, `{"message":"User toto created successfully"}`, w.Body.String())
}
Note that this does not exempt to also test Insert method of MongoUserInserter, but separately : here, this test covers CreateUser, not the Insert method.

API Gateway HTTP client request with IAM auth with Go

Hello StackOverflow AWS Gophers,
I'm implementing a CLI with the excellent cobra/viper packages from spf13. We have an Athena database fronted by an API Gateway endpoint, which authenticates with IAM.
That is, in order to interact with its endpoints by using Postman, I have to define AWS Signature as Authorization method, define the corresponding AWS id/secret and then in the Headers there will be X-Amz-Security-Token and others. Nothing unusual, works as expected.
Since I'm new to Go, I was a bit shocked to see that there are no examples to do this simple HTTP GET request with the aws-sdk-go itself... I'm trying to use the shared credentials provider (~/.aws/credentials), as demonstrated for the S3 client Go code snippets from re:Invent 2015:
req := request.New(nil)
How can I accomplish this seemingly easy feat in 2019 without having to resort to self-cooked net/http and therefore having to manually read ~/.aws/credentials or worse, go with os.Getenv and other ugly hacks?
Any Go code samples interacting as client would be super helpful. No Golang Lambda/server examples, please, there's plenty of those out there.
Unfortunately, it seems that the library has been updated since the accepted answer was written and the solution no longer is the same. After some trial and error, this appears to be the more current method of handling the signing (using https://pkg.go.dev/github.com/aws/aws-sdk-go-v2):
import (
"context"
"net/http"
"time"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
)
func main() {
// Context is not being used in this example.
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
// Handle error.
}
credentials, err := cfg.Credentials.Retrieve(context.TODO())
if err != nil {
// Handle error.
}
// The signer requires a payload hash. This hash is for an empty payload.
hash := "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
req, _ := http.NewRequest(http.MethodGet, "api-gw-url", nil)
signer := v4.NewSigner()
err = signer.SignHTTP(context.TODO(), credentials, req, hash, "execute-api", cfg.Region, time.Now())
if err != nil {
// Handle error.
}
// Use `req`
}
The solution below uses aws-sdk-go-v2
https://github.com/aws/aws-sdk-go-v2
// A AWS SDK session is created because the HTTP API is secured using a
// IAM authorizer. As such, we need AWS client credentials and a
// session to properly sign the request.
cfg, err := external.LoadDefaultAWSConfig(
external.WithSharedConfigProfile(profile),
)
if err != nil {
fmt.Println("unable to create an AWS session for the provided profile")
return
}
req, _ := http.NewRequest(http.MethodGet, "", nil)
req = req.WithContext(ctx)
signer := v4.NewSigner(cfg.Credentials)
_, err = signer.Sign(req, nil, "execute-api", cfg.Region, time.Now())
if err != nil {
fmt.Printf("failed to sign request: (%v)\n", err)
return
}
res, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Printf("failed to call remote service: (%v)\n", err)
return
}
defer res.Body.Close()
if res.StatusCode != 200 {
fmt.Printf("service returned a status not 200: (%d)\n", res.StatusCode)
return
}
The first argument to request.New is aws.Config, where you can send credentials.
https://github.com/aws/aws-sdk-go/blob/master/aws/request/request.go#L99
https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
There are multiple ways to create credentials object: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html
For example using static values:
creds:= credentials.NewStaticCredentials("AKID", "SECRET_KEY", "TOKEN")
req := request.New(aws.Config{Credentials: creds}, ...)
I'm pretty new to go myself (3rd day learning go) but from watching the video you posted with the S3 example and reading through the source code (for the s3 service and request module) here is my understanding (which I'm hoping helps).
If you look at the code for the s3.New() function aws-sdk-go/service/s3/service.go
func New(p client.ConfigProvider, cfgs ...*aws.Config) *S3 {
c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, .SigningName) }
As opposed to request.New() function aws-sdk-go/aws/request/request.go
func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers,
retryer Retryer, operation *Operation, params interface{}, data interface{}) *Request { ...
As you can see in the s3 scenario the *aws.Config struct is a pointer, and so is probably initialized / populated elsewhere. As opposed to the request function where the aws.Config is a parameter. So I am guessing the request module is probably a very low level module which doesn't get the shared credentials automatically.
Now, seeing as you will be interacting with API gateway I had a look at that service specifically to see if there was something similar. I looked at aws-sdk-go/service/apigateway/service.go
func New(p client.ConfigProvider, cfgs ...*aws.Config) *APIGateway {
c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) }...
Which looks pretty much the same as the s3 client, so perhaps try using that and see how you go?

How to create an authentication middleware inside an AWS Lambda

I'm using AWS Cognito to authenticate my users, and once authenticated, they can call my API (API Gateway + Lambda). I'm doing all that using the Serverless Framework.
Once authenticated, when they call an endpoint that requires this authentication, my lambda will receive the user attributes through the request.RequestContext.Authorizer["claims"]. I had the idea of creating an authentication middleware to inject the current user into the context. But I'm certain that I'm doing something wrong (or can be improved).
How it works:
my-lambda.go:
package main
import (
"context"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/company/api/middlewares"
)
func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
fmt.Println(ctx.user)
return events.APIGatewayProxyResponse{}, nil
}
func main() {
lambda.Start(
middlewares.Authentication(Handler),
)
}
middlewares/authentication.go
package middlewares
import (
"context"
"github.com/aws/aws-lambda-go/events"
"github.com/company/api/models"
)
func Authentication(next func(context.Context, events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error)) func(context.Context, events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
var user models.User
return func(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
claims := request.RequestContext.Authorizer["claims"]
// Find user by claims properties.
if err := user.Current(claims); err != nil {
return events.APIGatewayProxyResponse{}, err
}
ctx.user = user
return next(ctx, request)
}
}
models/user.go:
package models
import (
"github.com/jinzhu/gorm"
"github.com/mitchellh/mapstructure"
)
type User struct {
gorm.Model
// Override ID cause we are using cognito.
Email string `gorm:"primary_key,not null"`
Site Site
}
func (u *User) Current(claims interface{}) error {
if err := mapstructure.Decode(claims, u); err != nil {
panic(err)
}
if err := Database.Find(u).Error; err != nil {
return err
}
return nil
}
I have 2 questions:
Is this the right way to define a function (Authentication function) that receives a function and returns another function? Because it is too verbose, I am feeling this is wrong.
Is there a way to augment the ctx with an user attribute? The way that I'm trying, I see the error ctx.user undefined (type context.Context has no field or method user).
1st question about using the middleware:
There is certainly nothing wrong with the approach. Maybe the function will look a little better if you define the function type and use the defined name. net/http does the same thing with the HandlerFunc:
type HandlerFunc func(ResponseWriter, *Request)
Which will make the signature of a middleware more reasonable:
func AuthMiddleware(nextHop HandlerFunc) HandlerFunc
EDIT: doesn't the lambda library define such a type for the function signature? I would expect one to exist.
Also I don't know if the suffix Middleware makes sense in your case, but I think some suffix should make sense for you to give a little more context to the name of the function and make it more understandable. AuthenticationMiddleware could be an example.
EDIT: just saw the package name. LGTM really.
2nd question:
See this for the correct use of context. There's also a common pitfal: context.WithValue returns a new context to use. Therefore you should not expect the passed parameter context to be mutated and should use the new one that is returned.

Mocking remote api calls in golang

I'm trying to get better at writing mocked golang tests that call a remote api
I can similate a single call pretty easily with the httptest library but am a
bit stuck handling other functions that call single endpoint calls multiple times.
For example given a simple create function
func createItem(url string, product Product) (int, error) {
// make request
return createdId, nil
}
I can write some tests that look like this
func TestCreateItem(t *testing.T) {
mock_ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`37`))
}))
prod := Product{...}
_, err := createItem(mock_ts.URL, 1, prod)
if err != nil {
t.Errorf("Error saving item: %v", err)
}
}
Now if I have this other wrapper function I won't be able to pass in the
mock test server url.
func someFunctionThatMakesManyItems(...) {
url = "http://www.realapiendpoint.com" // or some func that gets api url
// this function might generate a list of items
for _, item := range items {
createItem(url, item)
}
}
I could need to pass in the url to the someFunctionThatMakesManyItems and any
functions that rely on api functions and that just seems like the wrong approach.
Any advice on how to model this better to help with my tests?
Make the endpoint URL configurable instead of hard-coding it - make it a function parameter, or a field of some configuration struct, or returned from an internal configuration service, something like that. Designing for testability is all about avoiding hard-coded configuration and dependencies: code should receive its configuration values and its dependencies from the caller rather than setting or creating them itself.