|
8 | 8 | "fmt" |
9 | 9 | "testing" |
10 | 10 |
|
| 11 | + "github.com/aws/aws-lambda-go/lambda/handlertrace" |
11 | 12 | "github.com/stretchr/testify/assert" |
12 | 13 | ) |
13 | 14 |
|
@@ -206,3 +207,64 @@ func TestInvalidJsonInput(t *testing.T) { |
206 | 207 | assert.Equal(t, "unexpected end of JSON input", err.Error()) |
207 | 208 |
|
208 | 209 | } |
| 210 | + |
| 211 | +func TestHandlerTrace(t *testing.T) { |
| 212 | + handler := NewHandler(func(ctx context.Context, x int) (int, error) { |
| 213 | + if x != 123 { |
| 214 | + t.Error(x) |
| 215 | + } |
| 216 | + return 456, nil |
| 217 | + }) |
| 218 | + requestHistory := "" |
| 219 | + responseHistory := "" |
| 220 | + checkInt := func(e interface{}, expected int) { |
| 221 | + nt, ok := e.(int) |
| 222 | + if !ok { |
| 223 | + t.Error("not int as expected", e) |
| 224 | + return |
| 225 | + } |
| 226 | + if nt != expected { |
| 227 | + t.Error("unexpected value", nt, expected) |
| 228 | + } |
| 229 | + } |
| 230 | + ctx := context.Background() |
| 231 | + ctx = handlertrace.NewContext(ctx, handlertrace.HandlerTrace{}) // empty HandlerTrace |
| 232 | + ctx = handlertrace.NewContext(ctx, handlertrace.HandlerTrace{ // with RequestEvent |
| 233 | + RequestEvent: func(c context.Context, e interface{}) { |
| 234 | + requestHistory += "A" |
| 235 | + checkInt(e, 123) |
| 236 | + }, |
| 237 | + }) |
| 238 | + ctx = handlertrace.NewContext(ctx, handlertrace.HandlerTrace{ // with ResponseEvent |
| 239 | + ResponseEvent: func(c context.Context, e interface{}) { |
| 240 | + responseHistory += "X" |
| 241 | + checkInt(e, 456) |
| 242 | + }, |
| 243 | + }) |
| 244 | + ctx = handlertrace.NewContext(ctx, handlertrace.HandlerTrace{ // with RequestEvent and ResponseEvent |
| 245 | + RequestEvent: func(c context.Context, e interface{}) { |
| 246 | + requestHistory += "B" |
| 247 | + checkInt(e, 123) |
| 248 | + }, |
| 249 | + ResponseEvent: func(c context.Context, e interface{}) { |
| 250 | + responseHistory += "Y" |
| 251 | + checkInt(e, 456) |
| 252 | + }, |
| 253 | + }) |
| 254 | + ctx = handlertrace.NewContext(ctx, handlertrace.HandlerTrace{}) // empty HandlerTrace |
| 255 | + |
| 256 | + payload := []byte(`123`) |
| 257 | + js, err := handler.Invoke(ctx, payload) |
| 258 | + if err != nil { |
| 259 | + t.Error("unexpected handler error", err) |
| 260 | + } |
| 261 | + if string(js) != "456" { |
| 262 | + t.Error("unexpected handler output", string(js)) |
| 263 | + } |
| 264 | + if requestHistory != "AB" { |
| 265 | + t.Error("request callbacks not called as expected", requestHistory) |
| 266 | + } |
| 267 | + if responseHistory != "XY" { |
| 268 | + t.Error("response callbacks not called as expected", responseHistory) |
| 269 | + } |
| 270 | +} |
0 commit comments