-
Notifications
You must be signed in to change notification settings - Fork 5
/
parser_test.go
75 lines (68 loc) · 2.07 KB
/
parser_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package vesper
import (
"context"
"encoding/json"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
func TestParserMiddleware(t *testing.T) {
t.Run("no unmarshaler", func(t *testing.T) {
nextFunc := func(ctx context.Context, in interface{}) (interface{}, error) {
t.Errorf("unexpected call to next func")
return nil, nil
}
middleware := ParserMiddleware(nil)(nextFunc)
_, err := middleware(context.Background(), []byte("{}"))
assert.Error(t, err)
})
t.Run("no TIn", func(t *testing.T) {
called := false
nextFunc := func(ctx context.Context, in interface{}) (interface{}, error) {
called = true
return nil, nil
}
middleware := ParserMiddleware(json.Unmarshal)(nextFunc)
payload := []byte("{}")
ctx := context.Background()
ctx = context.WithValue(ctx, ctxKeyPayload, payload)
_, err := middleware(ctx, payload)
assert.NoError(t, err)
assert.True(t, called)
})
t.Run("TIn is a primitive", func(t *testing.T) {
called := false
nextFunc := func(ctx context.Context, in interface{}) (interface{}, error) {
called = true
assert.Equal(t, 123, in)
return nil, nil
}
middleware := ParserMiddleware(json.Unmarshal)(nextFunc)
payload := []byte("123")
ctx := context.Background()
ctx = context.WithValue(ctx, ctxKeyTIn, reflect.TypeOf(int(0)))
ctx = context.WithValue(ctx, ctxKeyPayload, payload)
_, err := middleware(ctx, payload)
assert.NoError(t, err)
assert.True(t, called)
})
t.Run("TIn is an object", func(t *testing.T) {
called := false
type req struct {
Message string `json:"message"`
}
nextFunc := func(ctx context.Context, in interface{}) (interface{}, error) {
called = true
assert.Equal(t, req{Message: "hello world"}, in)
return nil, nil
}
middleware := ParserMiddleware(json.Unmarshal)(nextFunc)
payload := []byte(`{"message": "hello world"}`)
ctx := context.Background()
ctx = context.WithValue(ctx, ctxKeyTIn, reflect.TypeOf(req{}))
ctx = context.WithValue(ctx, ctxKeyPayload, payload)
_, err := middleware(ctx, payload)
assert.NoError(t, err)
assert.True(t, called)
})
}