模拟 context.Context 以测试 lambdacontext.FromContext

Mock context.Context to test lambdacontext.FromContext

我正在使用 aws-sdk-go and aws-lambda-go 构建 aws lambda,但遇到了一个小问题。

我想测试我的 lambda 处理程序。为此,我需要模拟一个有效的 context.Context containing valid attributes for lamdacontext.LambdaContext 并满足 lambdacontext.FromContext.

我似乎无法找到构建此类模拟的方法,因为 lambdacontext.FromContext 总是 return 我 _, false

这是我的主要内容,在 events.SNSEvent 事件上有一个简单的处理程序:

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
}

这是我对 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)

}

我还尝试了其他模拟,例如将带有这些参数的结构传递给它等,但我总是得到 false。例如,我也试过:

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)

    . . .

}

查看了FromContext的源码,摸不着头脑

// 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
}

当然,它 returns false 即使我只是传递一个 context.Background() 给它。

知道如何构建一个有效的 context.Context 来让 lambdacontext.FromContext return true 吗?

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

// 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
}

您无法访问此键,也无法 "reproduce" 它(您无法创建等于此 "private" 键的值)。

但有一个简单的方法,只需使用 lambdacontext.NewContext() 派生一个上下文,其中将包含此键:

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

所以解决方案:

ctx := context.Background()
// Add keys to your liking, then:
lc := new(lambdacontext.LambdaContext)
ctx = lambdacontext.NewContext(ctx, lc)