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 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题