-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler_test.go
317 lines (250 loc) · 8.94 KB
/
handler_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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package kcd_test
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/alexisvisco/kcd/pkg/errors"
"github.com/gavv/httpexpect"
"github.com/go-chi/chi"
"github.com/stretchr/testify/assert"
"github.com/alexisvisco/kcd"
)
const (
ValString = "name"
)
type hookBindStruct struct {
Uint uint `path:"uint"`
JSONName string `json:"name"`
QueryString string `query:"query_string"`
QueryFloat float32 `query:"query_float"`
QueryBool bool `query:"query_bool"`
QueryInt int `query:"query_int"`
QueryIntPtr *int `query:"query_int"`
QueryListUint []uint `query:"query_list_uint"`
Default string `default:"default_value"`
AnonymousStruct struct {
AnonymousField string `header:"header_anonymous_struct"`
}
Embedded
*EmbeddedPtr
*EmbeddedPtrNil
FilledStruct *StructOne
StructWithTextUnmarshaller *StructWithTextUnmarshaller `query:"struct_with_text_unmarshaller"`
SliceStructWithTextUnmarshaller []*StructWithTextUnmarshaller `query:"slice_struct_with_text_unmarshaller"`
Duration time.Duration `query:"duration"`
SliceDuration []time.Duration `query:"slice_duration"`
SlicePointer *[]string `query:"slice_pointer"`
ArrayDuration [2]time.Duration `query:"array_duration"`
ArrayInt *[3]int `query:"array_int"`
StructWithJSONUnmarshaller *StructWithJSONUnmarshaller `query:"struct_with_json_unmarshaller"`
StructWithBinaryUnmarshaller *StructWithBinaryUnmarshaller `query:"struct_with_binary_unmarshaller"`
SlicePtrString []*string `query:"slice_ptr_string"`
SliceInt []int `query:"slice_int"`
SliceWithUnmarshal *SliceWithUnmarshal `query:"slice_with_unmarshal"`
}
type Embedded struct {
EmbeddedString string `query:"embedded_string"`
}
type EmbeddedPtr struct {
EmbeddedStringPtr string `query:"embedded_string_ptr"`
}
type EmbeddedPtrNil struct {
EmbeddedStringPtrNil string `query:"embedded_string_ptr_nil"`
}
type StructOne struct {
Inner *StructTwo
}
type StructTwo struct {
FilledField string `query:"filled_field"`
}
type StructWithTextUnmarshaller struct {
Value string
}
func (s *StructWithTextUnmarshaller) UnmarshalText(text []byte) error {
s.Value = strings.ToUpper(string(text))
return nil
}
func hookBindHandler(bindStruct *hookBindStruct) (hookBindStruct, error) {
return *bindStruct, nil
}
type StructWithJSONUnmarshaller struct {
Value string
}
func (s *StructWithJSONUnmarshaller) UnmarshalJSON(bytes []byte) error {
s.Value = string(bytes)
return nil
}
type StructWithBinaryUnmarshaller struct {
Value string
}
func (s *StructWithBinaryUnmarshaller) UnmarshalBinary(data []byte) error {
s.Value = string(data)
return nil
}
type SliceWithUnmarshal [2]byte
func (s *SliceWithUnmarshal) UnmarshalText(text []byte) error {
if len(text) >= 2 {
s[0] = text[0]
s[1] = text[1]
} else {
s[0] = 'a'
s[1] = 'b'
}
return nil
}
func std(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("ok"))
}
type ErrImpl struct{}
func (t *ErrImpl) Error() string {
return "aaaa"
}
func testCustomErrNil() *ErrImpl {
return nil
}
type NormalInput struct {
Username string `query:"username"`
}
type NormalOutput struct {
Username string `query:"username"`
}
func normalHandler(in *NormalInput) (*NormalOutput, error) {
if in.Username == "error" {
return nil, errors.NewWithKind(errors.KindInternal, "error")
}
return &NormalOutput{
Username: in.Username,
}, nil
}
func TestBind(t *testing.T) {
r := chi.NewRouter()
r.Get("/hello", kcd.Handler(std, 200))
r.Get("/testerrimpl", kcd.Handler(testCustomErrNil, 200))
r.Get("/normalhandler", kcd.Handler(normalHandler, 200))
r.Post("/{uint}", kcd.Handler(hookBindHandler, 200))
server := httptest.NewServer(r)
defer server.Close()
e := httpexpect.New(t, server.URL)
t.Run("it should execute std http handler", func(t *testing.T) {
body := e.GET("/hello").Expect().Status(200).Body().Raw()
assert.Equal(t, "ok", body)
})
t.Run("it should normal handler without error", func(t *testing.T) {
e.GET(`/normalhandler`).WithQuery("username", "k2000").Expect().
Status(http.StatusOK).
JSON().Object().
Value("Username").Equal("k2000")
})
t.Run("it should normal handler with error", func(t *testing.T) {
e.GET(`/normalhandler`).WithQuery("username", "error").Expect().
Status(http.StatusInternalServerError)
})
t.Run("it should return nil with custom error", func(t *testing.T) {
body := e.GET("/testerrimpl").Expect().Body().Raw()
assert.Equal(t, "", body)
})
t.Run("it should succeed", func(t *testing.T) {
expect := e.POST("/4").
WithJSON(hookBindStruct{JSONName: ValString}).
WithQuery("query_string", "query_string").
WithQuery("query_float", 1.4).
WithQuery("query_bool", true).
WithQuery("query_int", 50).
WithQuery("query_list_uint", 0).
WithQuery("query_list_uint", 1).
WithHeader("header_anonymous_struct", "header_anonymous_struct").
WithQuery("embedded_string", "embedded_string").
WithQuery("embedded_string_ptr", "embedded_string_ptr").
WithQuery("filled_field", "filled_field").
WithQuery("struct_with_text_unmarshaller", "struct_with_text_unmarshaller").
WithQuery("slice_struct_with_text_unmarshaller", "one").
WithQuery("slice_struct_with_text_unmarshaller", "two").
WithQuery("duration", "45s").
WithQuery("slice_duration", "45s").
WithQuery("slice_duration", "2s").
WithQuery("slice_pointer", "one").
WithQuery("slice_pointer", "two").
WithQuery("array_duration", "45s").
WithQuery("array_duration", "2s").
WithQuery("array_int", "1").
WithQuery("array_int", "2").
WithQuery("array_int", "3").
WithQuery("struct_with_json_unmarshaller", `{"hi": 1}`).
WithQuery("struct_with_binary_unmarshaller", `goijerierjoer`).
WithQuery("slice_ptr_string", `hey`).
WithQuery("slice_ptr_string", `how`).
WithQuery("slice_int", 0).
WithQuery("slice_with_unmarshal", "hg").
Expect()
raw := expect.Body().Raw()
assert.NotContains(t, raw, "EmbeddedStringPtrNil")
j := expect.JSON()
j.Path("$.Uint").Equal(4)
j.Path("$.name").Equal(ValString)
j.Path("$.QueryString").Equal("query_string")
j.Path("$.QueryFloat").Equal(1.4)
j.Path("$.QueryBool").Equal(true)
j.Path("$.QueryInt").Equal(50)
j.Path("$.QueryIntPtr").Equal(50)
j.Path("$.QueryListUint").Equal([]uint{0, 1})
j.Path("$.Default").Equal("default_value")
j.Path("$.AnonymousStruct.AnonymousField").Equal("header_anonymous_struct")
j.Path("$.EmbeddedString").Equal("embedded_string")
j.Path("$.EmbeddedStringPtr").Equal("embedded_string_ptr")
j.Path("$.FilledStruct.Inner.FilledField").Equal("filled_field")
j.Path("$.StructWithTextUnmarshaller.Value").Equal("STRUCT_WITH_TEXT_UNMARSHALLER")
j.Path("$.SliceStructWithTextUnmarshaller").Equal([]map[string]interface{}{
{"Value": "ONE"},
{"Value": "TWO"},
})
j.Path("$.Duration").Equal(time.Second * 45)
j.Path("$.SliceDuration").Equal([]time.Duration{time.Second * 45, time.Second * 2})
j.Path("$.SlicePointer").Equal([]string{"one", "two"})
j.Path("$.ArrayDuration").Equal([]time.Duration{time.Second * 45, time.Second * 2})
j.Path("$.ArrayInt").Equal([]int{1, 2, 3})
j.Path("$.StructWithJSONUnmarshaller.Value").Equal(`{"hi": 1}`)
j.Path("$.StructWithBinaryUnmarshaller.Value").Equal(`goijerierjoer`)
j.Path("$.SlicePtrString").Equal([]string{"hey", "how"})
j.Path("$.SliceInt").Equal([]int{0})
j.Path("$.SliceWithUnmarshal").Equal(SliceWithUnmarshal{'h', 'g'})
})
t.Run("it should fail because of invalid body", func(t *testing.T) {
e.POST("/3").
WithHeader("Content-type", "application/json").
WithBytes([]byte("{ this is a malformed json")).Expect().
Status(http.StatusBadRequest).
JSON().Path("$.error_description").Equal("unable to read json request")
})
t.Run("it should succeed with an empty body", func(t *testing.T) {
e.POST("/3").Expect().
Status(http.StatusOK).
JSON().Path("$.name").Equal("")
})
t.Run("it should fail because of invalid uint", func(t *testing.T) {
e.POST("/-3").Expect().
Status(http.StatusBadRequest).
JSON().Path("$.fields.uint").Equal("invalid positive integer")
})
t.Run("it should fail because of invalid boolean", func(t *testing.T) {
e.POST("/4").WithQuery("query_bool", "yes").Expect().
Status(http.StatusBadRequest).
JSON().Path("$.fields.query_bool").Equal("invalid boolean")
})
t.Run("it should fail because of invalid float", func(t *testing.T) {
e.POST("/4").WithQuery("query_float", "yes").Expect().
Status(http.StatusBadRequest).
JSON().Path("$.fields.query_float").Equal("invalid floating number")
})
t.Run("it should fail because of invalid duration", func(t *testing.T) {
e.POST("/4").WithQuery("duration", "yes").Expect().
Status(http.StatusBadRequest).
JSON().Path("$.fields.duration").Equal("unable to parse duration (format: 1ms, 1s, 3h3s)")
})
t.Run("it should fail because of invalid duration", func(t *testing.T) {
e.POST("/4").WithQuery("slice_int", "yes").Expect().
Status(http.StatusBadRequest).
JSON().Path("$.fields.slice_int").Equal("invalid integer")
})
}