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 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错
  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出
  • ¥100 matlab2009 32位一直初始化
  • ¥15 Expected type 'str | PathLike[str]…… bytes' instead
  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数