GC30
GC30

Reputation: 45

AWS golang lambdaiface usage for testing lambda

I'm trying to unit test a lambda function. Looking at the docs (https://docs.aws.amazon.com/sdk-for-go/api/service/lambda/lambdaiface) I'm not sure how to achieve it. The example given is non working and I cannot see any other usage of it. Particularly confusing to me is

func myFunc(svc lambdaiface.LambdaAPI) bool {
    // Make svc.AddLayerVersionPermission request
}

as AddLayerVersionPermission does not return a bool so again I'm confused with expected usage. I'm also unsure if I'm meant to mock out every function individually which would be tedious. Can anyone give me any pointers or working examples? Ultimately I only want to mock out Invoke()

Thanks

I tried reading the documentation but it was unclear to me.

Upvotes: 1

Views: 862

Answers (1)

GC30
GC30

Reputation: 45

That the documentations has a unneccessary boolean return from myFunc() threw me on how this worked. A colleague https://stackoverflow.com/users/966860/nathj07 got me through this. This is the full solution he helped me get

package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/service/lambda"
    "github.com/aws/aws-sdk-go/service/lambda/lambdaiface"
    "github.com/stretchr/testify/mock"
)

type MockLambdaClient struct {
    mock.Mock
    lambdaiface.LambdaAPI
}

func (mlc *MockLambdaClient) Invoke(input *lambda.InvokeInput) (*lambda.InvokeOutput, error) {
    args := mlc.Called(input)
    return args.Get(0).(*lambda.InvokeOutput), args.Error(1)
}

type app struct {
    lambdaClient lambdaiface.LambdaAPI
}

func (a *app) invokeTest() {
    _, err := a.lambdaClient.Invoke(&lambda.InvokeInput{
        FunctionName: aws.String("a func name"),
        Payload:      []byte("the bytes"),
    })
    if err != nil {
        panic(err)
    }
}

func main() {

}

and the tests

package main

import (
    "testing"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/service/lambda"
)

func TestExample(t *testing.T) {
    mockLambda := &MockLambdaClient{}
    defer mockLambda.AssertExpectations(t)

    expInput := &lambda.InvokeInput{
        FunctionName: aws.String("a func name"),
        Payload:      []byte("the bytes"),
    }
    mockLambda.On("Invoke", expInput).Return(&lambda.InvokeOutput{}, nil).Times(1)

    a := app{}
    a.lambdaClient = mockLambda
    a.invokeTest()
}

Upvotes: 1

Related Questions