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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • drexlz0623 2018-09-26 23:35
    关注

    Will context.TODO satisfy your needs?

    https://golang.org/pkg/context/#TODO

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C语言快速排序函数纠错
  • ¥15 C#的一个应用程序书写
  • ¥65 页面调接口时加载卡住不响应
  • ¥35 用C语言解决编程问题
  • ¥15 unity硬件连接与使用
  • ¥15 鱼缸加热棒的数据分析或者实际案例也行
  • ¥15 postgresql11安装完成后,pgadmin无法启动
  • ¥15 (标签-无人机|关键词-Matlab代码)
  • ¥15 执行shell脚本提示参数太多
  • ¥15 困扰好久了,电脑的串口调试助手向单片机发送一个字符(如:字符‘1’到‘8’),单片机点亮对应的灯(如发送字符‘2’则点亮第2个灯)并给电脑回复信息:已点亮第x个灯(其中 x 要替换成对应的数字)