Skip to content

Commit

Permalink
updated tests to test output.
Browse files Browse the repository at this point in the history
  • Loading branch information
j-d-ha committed Dec 17, 2024
1 parent 9421d5a commit ab6bbc3
Show file tree
Hide file tree
Showing 7 changed files with 180 additions and 43 deletions.
5 changes: 5 additions & 0 deletions .idea/dictionaries/jonasha.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions .idea/watcherTasks.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

201 changes: 163 additions & 38 deletions event_test.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package main

import (
"bytes"
"context"
"errors"
"fmt"
"log/slog"
"os"
"strings"
"testing"

"github.com/aws/aws-lambda-go/lambda/messages"
"github.com/lithammer/dedent"
"github.com/lmittmann/tint"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
Expand All @@ -23,73 +27,194 @@ func (m *MockLambdaCaller) Invoke(data []byte) (messages.InvokeResponse, error)
return args.Get(0).(messages.InvokeResponse), args.Error(1) //nolint:wrapcheck,forcetypeassert
}

func TestRunLambdaEvent(t *testing.T) {
t.Parallel()

func TestRunLambdaEvent(t *testing.T) { //nolint:funlen
tests := map[string]struct {
event string
parseJSON bool
invokeResp messages.InvokeResponse
invokeErr error
expectedErr string
event string
parseJSON bool
invokeResp messages.InvokeResponse
invokeErr error
expectedOutput string
expectedErr error
}{
"successful invocation without JSON parsing": {
event: `{"key": "value"}`,
parseJSON: false,
invokeResp: messages.InvokeResponse{
Payload: []byte(`{"response": "success"}`),
},
invokeErr: nil,
expectedErr: "",
invokeErr: nil,
expectedOutput: `
---------------------------------------------------------------------------
0 INF Starting local Lambda invocation with Event
0 DBG Invoking lambda event
0 DBG Handling lambda event response
0 INF Lambda returned JSON payload:
{
"response": "success"
}
0 INF Lambda invocation complete, Exiting...
---------------------------------------------------------------------------
`,
expectedErr: nil,
},
"successful invocation with JSON parsing": {
event: `{"key": "value"}`,
parseJSON: true,
invokeResp: messages.InvokeResponse{
Payload: []byte(`{"response": "{\"innerKey\": \"innerValue\"}"}`),
},
invokeErr: nil,
expectedErr: "",
invokeErr: nil,
expectedOutput: `
---------------------------------------------------------------------------
0 INF Starting local Lambda invocation with Event
0 DBG Invoking lambda event
0 DBG Handling lambda event response
0 INF Lambda returned JSON payload:
{
"response": {
"innerKey": "innerValue"
}
}
0 INF Lambda invocation complete, Exiting...
---------------------------------------------------------------------------
`,
expectedErr: nil,
},
"invoke error": {
event: `{"key": "value"}`,
parseJSON: false,
invokeResp: messages.InvokeResponse{},
invokeErr: errors.New("invoke error"),
expectedErr: "invoke failed: invoke error",
event: `{"key": "value"}`,
parseJSON: false,
invokeResp: messages.InvokeResponse{},
invokeErr: errors.New("invoke error"),
expectedOutput: `
---------------------------------------------------------------------------
0 INF Starting local Lambda invocation with Event
0 DBG Invoking lambda event
`,
expectedErr: fmt.Errorf("[in lambdalocal.RunLambdaEvent] invoke failed: %w", errors.New("invoke error")),
},
"unmarshal error": {
"lambda returned error - valid JSON body": {
event: `{"key": "value"}`,
parseJSON: false,
invokeResp: messages.InvokeResponse{
Payload: []byte(`invalid json`),
Payload: []byte(`{"error": "test error"}`),
Error: &messages.InvokeResponse_Error{
Message: "test error",
Type: "",
StackTrace: []*messages.InvokeResponse_Error_StackFrame{
{
Path: "path1",
Line: 1,
Label: "part_1",
},
{
Path: "path2",
Line: 2,
Label: "part_2",
},
},
ShouldExit: false,
},
},
invokeErr: nil,
expectedErr: "unmarshal response failed: invalid character 'i' looking for beginning of value",
invokeErr: nil,
expectedOutput: `
---------------------------------------------------------------------------
0 INF Starting local Lambda invocation with Event
0 DBG Invoking lambda event
0 DBG Handling lambda event response
0 ERR Lambda returned error:
Returned error: test error
Stack trace:
path1:1 - part_1
path2:2 - part_2
0 INF Lambda returned JSON payload:
{
"error": "test error"
}
0 INF Lambda invocation complete, Exiting...
---------------------------------------------------------------------------
`,
expectedErr: nil,
},
"lambda returned error - invalid JSON body": {
event: `{"key": "value"}`,
parseJSON: false,
invokeResp: messages.InvokeResponse{
Payload: []byte(`invalid JSON`),
Error: &messages.InvokeResponse_Error{
Message: "test error",
Type: "",
StackTrace: []*messages.InvokeResponse_Error_StackFrame{
{
Path: "path1",
Line: 1,
Label: "part_1",
},
{
Path: "path2",
Line: 2,
Label: "part_2",
},
},
ShouldExit: false,
},
},
invokeErr: nil,
expectedOutput: `
---------------------------------------------------------------------------
0 INF Starting local Lambda invocation with Event
0 DBG Invoking lambda event
0 DBG Handling lambda event response
0 ERR Lambda returned error:
Returned error: test error
Stack trace:
path1:1 - part_1
path2:2 - part_2
0 INF Lambda returned non-JSON payload:
invalid JSON
0 INF Lambda invocation complete, Exiting...
---------------------------------------------------------------------------
`,
expectedErr: nil,
},
}

for name, tc := range tests {
t.Run(
name, func(t *testing.T) {
t.Parallel()
t.Run(name, func(t *testing.T) {
mockLambdaRPC := new(MockLambdaCaller)

mockLambdaRPC := new(MockLambdaCaller)
logger := slog.Default()
var buf bytes.Buffer

mockLambdaRPC.On("Invoke", []byte(tc.event)).Return(tc.invokeResp, tc.invokeErr)
logger := slog.New(
tint.NewHandler(
&buf, &tint.Options{
Level: slog.LevelDebug,
TimeFormat: "0",
NoColor: true,
},
),
)

err := RunLambdaEvent(context.Background(), os.Stdout, mockLambdaRPC, tc.event, tc.parseJSON, logger)
mockLambdaRPC.On("Invoke", []byte(tc.event)).Return(tc.invokeResp, tc.invokeErr)

if tc.expectedErr == "" {
require.NoError(t, err)
} else {
require.Error(t, err)
assert.Contains(t, err.Error(), tc.expectedErr)
}
err := RunLambdaEvent(context.Background(), &buf, mockLambdaRPC, tc.event, tc.parseJSON, logger)

mockLambdaRPC.AssertExpectations(t)
},
)
if tc.expectedErr == nil {
require.NoError(t, err)
} else {
assert.Equal(t, tc.expectedErr, err)
}

output := strings.TrimSpace(buf.String())

// fmt.Println(output)

assert.Equal(t, strings.TrimSpace(dedent.Dedent(tc.expectedOutput)), output)

mockLambdaRPC.AssertExpectations(t)
})
}
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ require (

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/lithammer/dedent v1.1.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/lithammer/dedent v1.1.0 h1:VNzHMVCBNG1j0fh3OrsFRkVUwStdDArbgBWoPAffktY=
github.com/lithammer/dedent v1.1.0/go.mod h1:jrXYCQtgg0nJiN+StA2KgR7w6CiQNv9Fd/Z9BP0jIOc=
github.com/lmittmann/tint v1.0.5 h1:NQclAutOfYsqs2F1Lenue6OoWCajs5wJcP3DfWVpePw=
github.com/lmittmann/tint v1.0.5/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
Expand Down
12 changes: 8 additions & 4 deletions print_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"encoding/json"
"fmt"
"log/slog"
"os"
"strings"

"github.com/aws/aws-lambda-go/lambda/messages"
)
Expand All @@ -17,12 +17,16 @@ func printResponse(
logger.Debug("Handling lambda event response")

if invokeResponse.Error != nil {
logger.Error("Lambda returned error")
_, _ = fmt.Fprintln(os.Stdout, invokeResponse.Error.Message)
var builder strings.Builder

builder.WriteString(fmt.Sprintf("Returned error: %s\n", invokeResponse.Error.Message))
builder.WriteString("\nStack trace:\n")

for _, detail := range invokeResponse.Error.StackTrace {
_, _ = fmt.Fprintf(os.Stdout, "\t%s:%d - %s\n", detail.Path, detail.Line, detail.Label)
builder.WriteString(fmt.Sprintf("%s:%d - %s\n", detail.Path, detail.Line, detail.Label))
}

logger.Error("Lambda returned error:\n" + builder.String())
}

if invokeResponse.Payload == nil {
Expand Down
1 change: 0 additions & 1 deletion parse_json_test.go → print_response_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
//nolint:cyclop
package main

import (
Expand Down

0 comments on commit ab6bbc3

Please sign in to comment.