dpikoto468637 2018-09-26 20:51
浏览 73
已采纳

在Go中测试Lambda处理程序时如何模拟AWS Lambda上下文?

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?

  • 写回答

2条回答 默认 最新

  • dtcrw26206 2018-09-27 02:04
    关注

    ‘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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置