-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbind_test.go
More file actions
376 lines (322 loc) · 12 KB
/
bind_test.go
File metadata and controls
376 lines (322 loc) · 12 KB
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package bind_test
import (
"bytes"
"errors"
"mime/multipart"
"net/http"
"strings"
"sync"
"testing"
"github.com/DevNewbie1826/bind"
)
// --- 테스트용 구조체 정의 ---
type TestPayload struct {
Name string `json:"name" xml:"name" form:"name"`
Value int `json:"value" xml:"value" form:"value"`
}
func (p *TestPayload) Bind(r *http.Request) error { return nil }
type FileUploadPayload struct {
Name string `form:"name"`
File *multipart.FileHeader `form:"file"`
Files []*multipart.FileHeader `form:"files"`
}
func (p *FileUploadPayload) Bind(r *http.Request) error { return nil }
type NestedPayload struct {
OuterField string `json:"outer_field"`
Inner *TestPayload `json:"inner"`
}
func (p *NestedPayload) Bind(r *http.Request) error { return nil }
type ParentBinder struct {
Child *TestPayload `json:"child"`
}
func (pb *ParentBinder) Bind(r *http.Request) error { return nil }
type InnerBinder struct{}
func (b *InnerBinder) Bind(r *http.Request) error { return errors.New("inner error") }
type MiddleBinder struct {
Inner *InnerBinder `json:"inner"`
}
func (b *MiddleBinder) Bind(r *http.Request) error { return nil }
type OuterBinder struct {
Middle *MiddleBinder `json:"middle"`
}
func (b *OuterBinder) Bind(r *http.Request) error { return nil }
type DeepBinder struct {
Child *DeepBinder `json:"child"`
}
func (b *DeepBinder) Bind(r *http.Request) error { return nil }
type EmbeddedPayload struct {
TestPayload
Extra string `json:"extra"`
}
func (p *EmbeddedPayload) Bind(r *http.Request) error { return nil }
type UnexportedFieldPayload struct {
unexportedBinder *TestPayload `form:"unexported"`
Exported string `form:"exported"`
}
func (p *UnexportedFieldPayload) Bind(r *http.Request) error { return nil }
// --- 테스트 함수 ---
func TestAction_JSONBinding(t *testing.T) {
req, _ := http.NewRequest("POST", "/", strings.NewReader(`{"name":"test", "value":42}`))
req.Header.Set("Content-Type", "application/json")
payload := &TestPayload{}
if err := bind.Action(req, payload); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if payload.Name != "test" || payload.Value != 42 {
t.Errorf(`expected {"test", 42}, got {"%s", %d}`, payload.Name, payload.Value)
}
}
func TestAction_XMLBinding(t *testing.T) {
req, _ := http.NewRequest("POST", "/", strings.NewReader(`<TestPayload><name>test</name><value>42</value></TestPayload>`))
req.Header.Set("Content-Type", "application/xml")
payload := &TestPayload{}
if err := bind.Action(req, payload); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if payload.Name != "test" || payload.Value != 42 {
t.Errorf(`expected {"test", 42}, got {"%s", %d}`, payload.Name, payload.Value)
}
}
func TestAction_FormBinding(t *testing.T) {
req, _ := http.NewRequest("POST", "/", strings.NewReader("name=test&value=42"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
payload := &TestPayload{}
if err := bind.Action(req, payload); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if payload.Name != "test" || payload.Value != 42 {
t.Errorf(`expected {"test", 42}, got {"%s", %d}`, payload.Name, payload.Value)
}
}
func TestAction_NestedBinding(t *testing.T) {
req, _ := http.NewRequest("POST", "/", strings.NewReader(`{"outer_field":"outer", "inner":{"name":"inner_test", "value":123}}`))
req.Header.Set("Content-Type", "application/json")
payload := &NestedPayload{Inner: &TestPayload{}}
if err := bind.Action(req, payload); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if payload.OuterField != "outer" || payload.Inner.Name != "inner_test" || payload.Inner.Value != 123 {
t.Errorf("nested binding failed, got %+v", payload)
}
}
func TestAction_UnsupportedContentType(t *testing.T) {
req, _ := http.NewRequest("POST", "/", strings.NewReader("data"))
req.Header.Set("Content-Type", "application/octet-stream")
err := bind.Action(req, &TestPayload{})
if err == nil {
t.Error("expected error for unsupported content type, got nil")
}
}
func TestAction_InvalidJSON(t *testing.T) {
req, _ := http.NewRequest("POST", "/", strings.NewReader(`{"name": "abc", "value":}`))
req.Header.Set("Content-Type", "application/json")
err := bind.Action(req, &TestPayload{})
if err == nil {
t.Error("expected JSON decode error, got nil")
}
}
func TestAction_NilBinderField(t *testing.T) {
req, _ := http.NewRequest("POST", "/", strings.NewReader(`{"child":null}`))
req.Header.Set("Content-Type", "application/json")
if err := bind.Action(req, &ParentBinder{}); err != nil {
t.Errorf("unexpected error with nil binder field: %v", err)
}
}
func TestAction_MultipartForm(t *testing.T) {
body := new(bytes.Buffer)
body.WriteString("--BOUNDARY\r\n")
body.WriteString(`Content-Disposition: form-data; name="name"` + "\r\n\r\n")
body.WriteString("multi\r\n")
body.WriteString("--BOUNDARY\r\n")
body.WriteString(`Content-Disposition: form-data; name="value"` + "\r\n\r\n")
body.WriteString("123\r\n")
body.WriteString("--BOUNDARY--\r\n")
req, _ := http.NewRequest("POST", "/", body)
req.Header.Set("Content-Type", "multipart/form-data; boundary=BOUNDARY")
payload := &TestPayload{}
if err := bind.Action(req, payload); err != nil {
t.Errorf("unexpected error: %v", err)
}
if payload.Name != "multi" || payload.Value != 123 {
t.Errorf("multipart binding failed, got %+v", payload)
}
}
func TestAction_MultipartFileUpload(t *testing.T) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, _ := writer.CreateFormFile("file", "test.txt")
part.Write([]byte("test file"))
writer.WriteField("name", "file-test")
writer.Close()
req, _ := http.NewRequest("POST", "/", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
payload := &FileUploadPayload{}
if err := bind.Action(req, payload); err != nil {
t.Fatalf("Action failed with file upload: %v", err)
}
if payload.Name != "file-test" || payload.File == nil || payload.File.Filename != "test.txt" {
t.Errorf("single file upload binding failed, got %+v", payload)
}
}
func TestAction_MultiFileUpload(t *testing.T) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part1, _ := writer.CreateFormFile("files", "test1.txt")
part1.Write([]byte("file1"))
part2, _ := writer.CreateFormFile("files", "test2.txt")
part2.Write([]byte("file2"))
writer.Close()
req, _ := http.NewRequest("POST", "/", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
payload := &FileUploadPayload{}
if err := bind.Action(req, payload); err != nil {
t.Fatalf("Action failed with multi-file upload: %v", err)
}
if len(payload.Files) != 2 || payload.Files[0].Filename != "test1.txt" || payload.Files[1].Filename != "test2.txt" {
t.Error("multi-file upload binding failed")
}
}
func TestAction_NestedErrorPropagation(t *testing.T) {
payload := &OuterBinder{Middle: &MiddleBinder{Inner: &InnerBinder{}}}
req, _ := http.NewRequest("POST", "/", strings.NewReader(`{"middle":{"inner":{}}}`))
req.Header.Set("Content-Type", "application/json")
err := bind.Action(req, payload)
if err == nil {
t.Fatal("Expected an error, but got nil")
}
expected := "bind failed on field 'Middle.Inner': inner error"
if err.Error() != expected {
t.Errorf("Expected error '%s', got '%s'", expected, err.Error())
}
}
func TestAction_RecursionDepthLimit(t *testing.T) {
jsonBody := strings.Repeat(`{"child":`, 1001) + "null" + strings.Repeat("}", 1001)
req, _ := http.NewRequest("POST", "/", strings.NewReader(jsonBody))
req.Header.Set("Content-Type", "application/json")
err := bind.Action(req, &DeepBinder{})
if err == nil || !strings.Contains(err.Error(), "max recursion depth (1000) exceeded") {
t.Errorf("Expected recursion depth error, got: %v", err)
}
}
func TestAction_EmbeddedStruct(t *testing.T) {
req, _ := http.NewRequest("POST", "/", strings.NewReader(`{"name":"embedded", "value":99, "extra":"field"}`))
req.Header.Set("Content-Type", "application/json")
payload := &EmbeddedPayload{}
if err := bind.Action(req, payload); err != nil {
t.Fatalf("unexpected error with embedded struct: %v", err)
}
if payload.Name != "embedded" || payload.Value != 99 || payload.Extra != "field" {
t.Errorf("embedded struct binding failed, got %+v", payload)
}
}
func TestErrorToJSON_Nil(t *testing.T) {
result := bind.ErrorToJSON(nil)
if string(result) != `{"error":""}` {
t.Errorf(`Expected '{"error":""}', got '%s'`, string(result))
}
}
func TestErrorToMap_Nil(t *testing.T) {
result := bind.ErrorToMap(nil)
if val, ok := result["error"]; !ok || val != "" {
t.Errorf(`Expected map[error:""]', got '%v'`, result)
}
}
func TestCustomDecoderRegistration(t *testing.T) {
originalDecoder := bind.DefaultDecoder
originalJSONDecoder, ok := bind.GetDecoder(bind.ContentTypeJSON)
if !ok {
t.Fatal("failed to get original JSON decoder")
}
t.Cleanup(func() {
bind.SetDecode(originalDecoder)
bind.RegisterDecoder(bind.ContentTypeJSON, originalJSONDecoder)
})
customErr := errors.New("custom decoder error")
bind.RegisterDecoder(bind.ContentTypeJSON, func(r *http.Request, v any) error {
return customErr
})
req, _ := http.NewRequest("POST", "/", strings.NewReader(`{ }`))
req.Header.Set("Content-Type", "application/json")
err := bind.Action(req, &TestPayload{})
if err == nil {
t.Fatal("Expected custom decoder error, but got nil")
}
var bindErr bind.BindError
if !errors.As(err, &bindErr) || bindErr.Unwrap() != customErr {
t.Errorf("Expected error to wrap '%v', but got '%v'", customErr, err)
}
}
// --- 추가된 테스트 케이스 ---
func TestGetContentType(t *testing.T) {
testCases := []struct {
input string
expected bind.ContentType
}{
{"text/plain; charset=utf-8", bind.ContentTypePlainText},
{"application/json", bind.ContentTypeJSON},
{"application/problem+json", bind.ContentTypeJSON},
{"text/xml; charset=utf-8", bind.ContentTypeXML},
{"application/x-www-form-urlencoded", bind.ContentTypeForm},
{"multipart/form-data; boundary=...", bind.ContentTypeMultipart},
{"text/html", bind.ContentTypeHTML},
{"text/event-stream", bind.ContentTypeEventStream},
{"application/unknown", bind.ContentTypeUnknown},
}
for _, tc := range testCases {
t.Run(tc.input, func(t *testing.T) {
if got := bind.GetContentType(tc.input); got != tc.expected {
t.Errorf("expected %v, got %v", tc.expected, got)
}
})
}
}
func TestAction_MalformedMultipartForm(t *testing.T) {
// A body that is missing the final boundary
body := new(bytes.Buffer)
body.WriteString("--BOUNDARY\r\n")
body.WriteString(`Content-Disposition: form-data; name="name"` + "\r\n\r\n")
body.WriteString("multi\r\n")
req, _ := http.NewRequest("POST", "/", body)
req.Header.Set("Content-Type", "multipart/form-data; boundary=BOUNDARY")
payload := &TestPayload{}
err := bind.Action(req, payload)
if err == nil {
t.Fatal("expected error for malformed multipart form, got nil")
}
if !strings.Contains(err.Error(), "unexpected EOF") {
t.Errorf("expected multipart EOF error, got %v", err)
}
}
func TestAction_UnexportedField(t *testing.T) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
writer.WriteField("exported", "value")
writer.Close()
req, _ := http.NewRequest("POST", "/", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
payload := &UnexportedFieldPayload{}
// This should not panic and should bind the exported field.
if err := bind.Action(req, payload); err != nil {
t.Fatalf("unexpected error with unexported field: %v", err)
}
if payload.Exported != "value" {
t.Errorf("expected exported field to be 'value', got '%s'", payload.Exported)
}
}
// TestConcurrentBinding - `go test -race`를 통해 캐시의 동시성 안전성을 검증합니다.
func TestConcurrentBinding(t *testing.T) {
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
req, _ := http.NewRequest("POST", "/", strings.NewReader(`{"name":"test", "value":42}`))
req.Header.Set("Content-Type", "application/json")
payload := &TestPayload{}
if err := bind.Action(req, payload); err != nil {
t.Errorf("concurrent binding failed: %v", err)
}
}()
}
wg.Wait()
}