Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock context.Context to test lambdacontext.FromContext

I'm building an aws lambda using aws-sdk-go and aws-lambda-go and I'm stuck with a little problem.

I want to test my lambda handler. To do so, I need to mock a valid context.Context containing valid attributes for lamdacontext.LambdaContext and satisfy lambdacontext.FromContext.

I cannot seem to find a way to build such mock, since lambdacontext.FromContext always returns me _, false.

Here's my main, with a simple handler on a events.SNSEvent event:

package main

import (
    "context"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
    "github.com/aws/aws-lambda-go/lambdacontext"
)

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

func handleRequest(ctx context.Context, snsEvent events.SNSEvent) error {
    lc, ok := lambdacontext.FromContext(ctx); if !ok {
        // Always false
        ...
        return someErr
    }
    . . .
    return nil
}

And here's my test for handleRequest:

package main

import (
    "context"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambdacontext"
    "github.com/stretchr/testify/assert"
    "gitlab.easy-network.it/meg/aml-rekognition/testdata"
    "testing"
)

const imgMock = `
{
  \"some_parameter\": \"some_value\"
}`

func TestHandleRequest(t *testing.T) {

    c := context.Background()

    ctxV := context.WithValue(c, "", map[string]interface{}{
        "AwsRequestID" : "some_aws_id",
        "InvokedFunctionArn" : "some_arn",
        "Identity" : lambdacontext.CognitoIdentity{},
        "ClientContext" : lambdacontext.ClientContext{},
    })

    snsEventMock := events.SNSEvent{
        Records: []events.SNSEventRecord{
            {
                SNS: events.SNSEntity{
                    Message: imgMock,
                },
            },
        },
    }

    err := handleRequest(ctxV, snsEventMock)
    assert.NoError(t, err)

}

I also tried other mocks like passing it a struct with these parameters etc, but I always get false. For instance, I tried also:

type TestMock struct {
    AwsRequestID string
    InvokedFunctionArn string
    Identity lambdacontext.CognitoIdentity
    ClientContext lambdacontext.ClientContext
}

func TestHandleRequest(t *testing.T) {

    c := context.Background()

    testMock := TestMock{
        AwsRequestID : "some_aws_id",
        InvokedFunctionArn : "some_arn",
        Identity : lambdacontext.CognitoIdentity{},
        ClientContext : lambdacontext.ClientContext{},
    }

    ctxV := context.WithValue(c, "", testMock)

    . . .

}

I checked out the source of FromContext and I've been scratching my head for a while.

// LambdaContext is the set of metadata that is passed for every Invoke.
type LambdaContext struct {
    AwsRequestID       string
    InvokedFunctionArn string
    Identity           CognitoIdentity
    ClientContext      ClientContext
}

// An unexported type to be used as the key for types in this package.
// This prevents collisions with keys defined in other packages.
type key struct{}

// The key for a LambdaContext in Contexts.
// Users of this package must use lambdacontext.NewContext and 
lambdacontext.FromContext

// instead of using this key directly.
var contextKey = &key{}

// FromContext returns the LambdaContext value stored in ctx, if any.
func FromContext(ctx context.Context) (*LambdaContext, bool) {
    lc, ok := ctx.Value(contextKey).(*LambdaContext)
    return lc, ok
}

Of course, it returns false even if I just pass a context.Background() to it.

Any idea on how should I build a valid context.Context to let lambdacontext.FromContext return true?

like image 941
AndreaM16 Avatar asked Mar 07 '23 03:03

AndreaM16


1 Answers

lambda.FromContext() checks if the passed context.Context contains a value with a "private" key hold inside the lambdacontext package:

// An unexported type to be used as the key for types in this package.
// This prevents collisions with keys defined in other packages.
type key struct{}

// The key for a LambdaContext in Contexts.
// Users of this package must use lambdacontext.NewContext and lambdacontext.FromContext
// instead of using this key directly.
var contextKey = &key{}

// FromContext returns the LambdaContext value stored in ctx, if any.
func FromContext(ctx context.Context) (*LambdaContext, bool) {
    lc, ok := ctx.Value(contextKey).(*LambdaContext)
    return lc, ok
}

You cannot access this key, and you can't "reproduce" it (you can't create a value that will be equal to this "private" key).

But there's an easy way, simply use the lambdacontext.NewContext() to derive a context which will have this key:

// NewContext returns a new Context that carries value lc.
func NewContext(parent context.Context, lc *LambdaContext) context.Context {
    return context.WithValue(parent, contextKey, lc)
}

So the solution:

ctx := context.Background()
// Add keys to your liking, then:
lc := new(lambdacontext.LambdaContext)
ctx = lambdacontext.NewContext(ctx, lc)
like image 72
icza Avatar answered Mar 09 '23 06:03

icza