Repository navigation
Expand file tree
/
Copy pathbindform_test.go
More file actions
475 lines (442 loc) · 18.2 KB
/
Copy pathbindform_test.go
File metadata and controls
475 lines (442 loc) · 18.2 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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
package runtime
import (
"bytes"
"mime/multipart"
"net/url"
"testing"
"time"
"github.com/oapi-codegen/nullable"
"github.com/oapi-codegen/runtime/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBindURLForm(t *testing.T) {
type testSubStruct struct {
Int int `json:"int"`
String string `json:"string"`
AdditionalProperties map[string]string `json:"-"`
}
type testStruct struct {
Int int `json:"int"`
Bool bool `json:"bool,omitempty"`
String string `json:"string"`
IntSlice []int `json:"int_slice"`
Struct testSubStruct `json:"struct"`
StructSlice []testSubStruct `json:"struct_slice"`
OptInt *int `json:"opt_int,omitempty"`
OptBool *bool `json:"opt_bool,omitempty"`
OptString *string `json:"opt_string,omitempty"`
OptStruct *testSubStruct `json:"opt_struct,omitempty"`
OptStructSlice *[]testSubStruct `json:"opt_struct_slice,omitempty"`
NotSerializable int `json:"-"`
unexported int //nolint:unused
}
testCases := map[string]testStruct{
"int=123": {Int: 123},
"bool=true": {Bool: true},
"string=example": {String: "example"},
"int_slice=1&int_slice=2&int_slice=3": {IntSlice: []int{1, 2, 3}},
"int_slice[]=1&int_slice[]=2&int_slice[]=3": {IntSlice: []int{1, 2, 3}},
"int_slice[2]=3&int_slice[1]=2&int_slice[0]=1": {IntSlice: []int{1, 2, 3}},
"struct[int]=789&struct[string]=abc": {Struct: testSubStruct{Int: 789, String: "abc"}},
"struct_slice[0][int]=3&struct_slice[0][string]=a&struct_slice[1][int]=2&struct_slice[1][string]=b&struct_slice[2][int]=1&struct_slice[2][string]=c": {
StructSlice: []testSubStruct{{Int: 3, String: "a"}, {Int: 2, String: "b"}, {Int: 1, String: "c"}},
},
"opt_int=456": {OptInt: func(v int) *int { return &v }(456)},
"opt_bool=true": {OptBool: func(v bool) *bool { return &v }(true)},
"opt_string=def": {OptString: func(v string) *string { return &v }("def")},
"opt_struct[int]=456&opt_struct[string]=def": {OptStruct: &testSubStruct{Int: 456, String: "def"}},
"opt_struct_slice[0][int]=123&opt_struct_slice[0][string]=abc&opt_struct_slice[1][int]=456&opt_struct_slice[1][string]=def": {
OptStructSlice: &([]testSubStruct{{Int: 123, String: "abc"}, {Int: 456, String: "def"}}),
},
"opt_struct[additional_property]=123": {
OptStruct: &testSubStruct{AdditionalProperties: map[string]string{"additional_property": "123"}},
},
}
for k, v := range testCases {
values, err := url.ParseQuery(k)
assert.NoError(t, err)
var result testStruct
err = BindForm(&result, values, nil, nil)
assert.NoError(t, err)
assert.Equal(t, v, result)
}
}
// TestBindURLFormNullable reproduces oapi-codegen/runtime#129: BindForm fails on
// a nullable.Nullable[T] field because Nullable's underlying type is map[bool]T
// and neither bindFormImpl nor BindStringToObjectWithOptions handles maps.
func TestBindURLFormNullable(t *testing.T) {
type testStruct struct {
Name nullable.Nullable[string] `json:"name"`
Age nullable.Nullable[int] `json:"age"`
}
t.Run("string value is bound", func(t *testing.T) {
values, err := url.ParseQuery("name=alice")
require.NoError(t, err)
var result testStruct
err = BindForm(&result, values, nil, nil)
require.NoError(t, err)
got, err := result.Name.Get()
require.NoError(t, err)
assert.Equal(t, "alice", got)
})
t.Run("int value is bound", func(t *testing.T) {
values, err := url.ParseQuery("age=42")
require.NoError(t, err)
var result testStruct
err = BindForm(&result, values, nil, nil)
require.NoError(t, err)
got, err := result.Age.Get()
require.NoError(t, err)
assert.Equal(t, 42, got)
})
t.Run("missing field stays unspecified", func(t *testing.T) {
var result testStruct
err := BindForm(&result, url.Values{}, nil, nil)
require.NoError(t, err)
assert.False(t, result.Name.IsSpecified())
assert.False(t, result.Age.IsSpecified())
})
}
// TestBindURLFormGenericMap covers binding into a non-Nullable map[K]V field
// using the `name[key]=value` form encoding.
func TestBindURLFormGenericMap(t *testing.T) {
t.Run("string keys, int values", func(t *testing.T) {
type testStruct struct {
Attrs map[string]int `json:"attrs"`
}
values, err := url.ParseQuery("attrs[a]=1&attrs[b]=2")
require.NoError(t, err)
var result testStruct
err = BindForm(&result, values, nil, nil)
require.NoError(t, err)
assert.Equal(t, map[string]int{"a": 1, "b": 2}, result.Attrs)
})
t.Run("int keys, string values", func(t *testing.T) {
type testStruct struct {
Labels map[int]string `json:"labels"`
}
values, err := url.ParseQuery("labels[1]=one&labels[2]=two")
require.NoError(t, err)
var result testStruct
err = BindForm(&result, values, nil, nil)
require.NoError(t, err)
assert.Equal(t, map[int]string{1: "one", 2: "two"}, result.Labels)
})
t.Run("absent map stays nil", func(t *testing.T) {
type testStruct struct {
Attrs map[string]int `json:"attrs"`
}
var result testStruct
err := BindForm(&result, url.Values{}, nil, nil)
require.NoError(t, err)
assert.Nil(t, result.Attrs)
})
}
func TestBindMultipartForm(t *testing.T) {
var testStruct struct {
File types.File `json:"file"`
OptFile *types.File `json:"opt_file,omitempty"`
Files []types.File `json:"files"`
OptFiles *[]types.File `json:"opt_files"`
}
form, err := makeMultipartFilesForm([]fileData{{field: "file", filename: "123.txt", content: []byte("123")}})
assert.NoError(t, err)
err = BindForm(&testStruct, form.Value, form.File, nil)
assert.NoError(t, err)
assert.Equal(t, "123.txt", testStruct.File.Filename())
content, err := testStruct.File.Bytes()
assert.NoError(t, err)
assert.Equal(t, []byte("123"), content)
form, err = makeMultipartFilesForm([]fileData{
{field: "files", filename: "123.pdf", content: []byte("123")},
{field: "files", filename: "456.pdf", content: []byte("456")},
{field: "files", filename: "789.pdf", content: []byte("789")},
})
assert.NoError(t, err)
err = BindForm(&testStruct, form.Value, form.File, nil)
assert.NoError(t, err)
assert.Equal(t, 3, len(testStruct.Files))
assert.Equal(t, "123.pdf", testStruct.Files[0].Filename())
assert.Equal(t, "456.pdf", testStruct.Files[1].Filename())
assert.Equal(t, "789.pdf", testStruct.Files[2].Filename())
form, err = makeMultipartFilesForm([]fileData{{field: "opt_file", filename: "456.png", content: []byte("456")}})
assert.NoError(t, err)
err = BindForm(&testStruct, form.Value, form.File, nil)
assert.NoError(t, err)
assert.Equal(t, "456.png", testStruct.OptFile.Filename())
content, err = testStruct.OptFile.Bytes()
assert.NoError(t, err)
assert.Equal(t, []byte("456"), content)
form, err = makeMultipartFilesForm([]fileData{
{field: "opt_files[2]", filename: "123.pdf", content: []byte("123")},
{field: "opt_files[1]", filename: "456.pdf", content: []byte("456")},
{field: "opt_files[0]", filename: "789.pdf", content: []byte("789")},
})
assert.NoError(t, err)
err = BindForm(&testStruct, form.Value, form.File, nil)
assert.NoError(t, err)
assert.NotNil(t, testStruct.OptFiles)
assert.Equal(t, 3, len(*testStruct.OptFiles))
assert.Equal(t, "789.pdf", (*testStruct.OptFiles)[0].Filename())
assert.Equal(t, "456.pdf", (*testStruct.OptFiles)[1].Filename())
assert.Equal(t, "123.pdf", (*testStruct.OptFiles)[2].Filename())
}
func TestMarshalForm(t *testing.T) {
type testSubStruct struct {
Int int `json:"int"`
String string `json:"string"`
}
type testStruct struct {
Int int `json:"int,omitempty"`
Bool bool `json:"bool,omitempty"`
String string `json:"string,omitempty"`
IntSlice []int `json:"int_slice,omitempty"`
Struct testSubStruct `json:"struct,omitempty"`
StructSlice []testSubStruct `json:"struct_slice,omitempty"`
OptInt *int `json:"opt_int,omitempty"`
OptBool *bool `json:"opt_bool,omitempty"`
OptBoolNullable *bool `json:"opt_bool_nullable"`
OptString *string `json:"opt_string,omitempty"`
OptStruct *testSubStruct `json:"opt_struct,omitempty"`
OptStructSlice *[]testSubStruct `json:"opt_struct_slice,omitempty"`
NotSerializable int `json:"-"`
unexported int //nolint:unused
}
testCases := map[string]testStruct{
"int=123": {Int: 123},
"bool=true": {Bool: true},
"string=example": {String: "example"},
"int_slice[0]=1&int_slice[1]=2&int_slice[2]=3": {IntSlice: []int{1, 2, 3}},
"struct[int]=789&struct[string]=abc": {Struct: testSubStruct{Int: 789, String: "abc"}},
"struct_slice[0][int]=3&struct_slice[0][string]=a&struct_slice[1][int]=2&struct_slice[1][string]=b&struct_slice[2][int]=1&struct_slice[2][string]=c": {
StructSlice: []testSubStruct{{Int: 3, String: "a"}, {Int: 2, String: "b"}, {Int: 1, String: "c"}},
},
"opt_int=456": {OptInt: func(v int) *int { return &v }(456)},
"opt_bool=true": {OptBool: func(v bool) *bool { return &v }(true)},
"": {OptBoolNullable: nil},
"opt_string=def": {OptString: func(v string) *string { return &v }("def")},
"opt_struct[int]=456&opt_struct[string]=def": {OptStruct: &testSubStruct{Int: 456, String: "def"}},
"opt_struct_slice[0][int]=123&opt_struct_slice[0][string]=abc&opt_struct_slice[1][int]=456&opt_struct_slice[1][string]=def": {
OptStructSlice: &([]testSubStruct{{Int: 123, String: "abc"}, {Int: 456, String: "def"}}),
},
}
for k, v := range testCases {
marshaled, err := MarshalForm(v, nil)
assert.NoError(t, err)
encoded, err := url.QueryUnescape(marshaled.Encode())
assert.NoError(t, err)
assert.Equal(t, k, encoded)
}
}
// TestMarshalFormEncoding covers oapi-codegen issue #2604: a property with an
// encoding is serialized by its style and explode, rather than in the
// bracketed default.
func TestMarshalFormEncoding(t *testing.T) {
type object struct {
Role string `json:"role"`
Age int `json:"age"`
}
type body struct {
Email string `json:"email,omitempty"`
Topic []string `json:"topic,omitempty"`
OptTopic *[]int `json:"opt_topic,omitempty"`
Object *object `json:"object,omitempty"`
Map map[string]string `json:"map,omitempty"`
When *types.Date `json:"when,omitempty"`
}
yes, no := true, false
topics := body{Email: "jane@example.com", Topic: []string{"news", "a,b c"}}
date := types.Date{Time: time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC)}
testCases := []struct {
name string
body body
encodings map[string]RequestBodyEncoding
expected url.Values
}{
{
name: "no encoding keeps indexed keys",
body: topics,
expected: url.Values{"email": {"jane@example.com"}, "topic[0]": {"news"}, "topic[1]": {"a,b c"}},
},
{
name: "encoding without style or explode keeps indexed keys",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Required: &yes}},
expected: url.Values{"email": {"jane@example.com"}, "topic[0]": {"news"}, "topic[1]": {"a,b c"}},
},
{
name: "form explode repeats the key",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Style: "form", Explode: &yes}},
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news", "a,b c"}},
},
{
name: "form explodes by default",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Style: "form"}},
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news", "a,b c"}},
},
{
name: "explode alone implies form",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Explode: &yes}},
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news", "a,b c"}},
},
{
name: "form without explode joins with commas",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Style: "form", Explode: &no}},
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news,a,b c"}},
},
{
name: "spaceDelimited does not explode by default",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Style: "spaceDelimited"}},
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news a,b c"}},
},
{
name: "pipeDelimited",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Style: "pipeDelimited", Explode: &no}},
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news|a,b c"}},
},
{
name: "pipeDelimited explode repeats the key",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Style: "pipeDelimited", Explode: &yes}},
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news", "a,b c"}},
},
{
name: "deepObject is the bracketed default",
body: body{Topic: []string{"news"}, Object: &object{Role: "admin", Age: 3}},
encodings: map[string]RequestBodyEncoding{"topic": {Style: "deepObject", Explode: &yes}, "object": {Style: "deepObject", Explode: &yes}},
expected: url.Values{"topic[0]": {"news"}, "object[role]": {"admin"}, "object[age]": {"3"}},
},
{
name: "optional array",
body: body{OptTopic: &[]int{1, 2}},
encodings: map[string]RequestBodyEncoding{"opt_topic": {Style: "form", Explode: &yes}},
expected: url.Values{"opt_topic": {"1", "2"}},
},
{
name: "primitive",
body: body{Email: "jane@example.com", When: &date},
encodings: map[string]RequestBodyEncoding{"email": {Style: "form", Explode: &yes}, "when": {Style: "form"}},
expected: url.Values{"email": {"jane@example.com"}, "when": {"2026-11-20"}},
},
{
name: "exploded object contributes its properties",
body: body{Object: &object{Role: "admin", Age: 3}, Map: map[string]string{"k": "v"}},
encodings: map[string]RequestBodyEncoding{"object": {Style: "form", Explode: &yes}, "map": {Style: "form"}},
expected: url.Values{"role": {"admin"}, "age": {"3"}, "k": {"v"}},
},
{
name: "object without explode",
body: body{Object: &object{Role: "admin", Age: 3}, Map: map[string]string{"k": "v"}},
encodings: map[string]RequestBodyEncoding{"object": {Style: "form", Explode: &no}, "map": {Style: "form", Explode: &no}},
expected: url.Values{"object": {"age,3,role,admin"}, "map": {"k,v"}},
},
{
name: "json content type",
body: body{Topic: []string{"news"}, Object: &object{Role: "admin", Age: 3}},
encodings: map[string]RequestBodyEncoding{"object": {ContentType: "application/json"}},
expected: url.Values{"topic[0]": {"news"}, "object": {`{"role":"admin","age":3}`}},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
marshaled, err := MarshalForm(tc.body, tc.encodings)
require.NoError(t, err)
assert.Equal(t, tc.expected, marshaled)
})
}
t.Run("wire format", func(t *testing.T) {
marshaled, err := MarshalForm(topics, map[string]RequestBodyEncoding{"topic": {Style: "form", Explode: &yes}})
require.NoError(t, err)
assert.Equal(t, "email=jane%40example.com&topic=news&topic=a%2Cb+c", marshaled.Encode())
// What we send is what BindForm reads back.
var bound body
require.NoError(t, BindForm(&bound, marshaled, nil, nil))
assert.Equal(t, topics, bound)
})
t.Run("errors", func(t *testing.T) {
_, err := MarshalForm(topics, map[string]RequestBodyEncoding{"topic": {Style: "matrix"}})
assert.ErrorContains(t, err, "unsupported style 'matrix'")
_, err = MarshalForm(topics, map[string]RequestBodyEncoding{"topic": {ContentType: "text/csv"}})
assert.ErrorContains(t, err, "unsupported encoding")
type nested struct {
Objects []object `json:"objects"`
}
_, err = MarshalForm(nested{Objects: []object{{}}}, map[string]RequestBodyEncoding{"objects": {Style: "form"}})
assert.Error(t, err)
})
}
type fileData struct {
field string
filename string
content []byte
}
func makeMultipartFilesForm(files []fileData) (*multipart.Form, error) {
var buffer bytes.Buffer
mw := multipart.NewWriter(&buffer)
for _, file := range files {
w, err := mw.CreateFormFile(file.field, file.filename)
if err != nil {
return nil, err
}
_, err = w.Write(file.content)
if err != nil {
return nil, err
}
}
err := mw.Close()
if err != nil {
return nil, err
}
mr := multipart.NewReader(&buffer, mw.Boundary())
return mr.ReadForm(1024)
}
// TestFormTagPreferredOverJSONTag covers issue #128: form encoding keys on
// the `form` struct tag when present — for field names, `-` skips and
// `,omitempty` — falling back to the `json` tag for structs that only carry
// json tags.
func TestFormTagPreferredOverJSONTag(t *testing.T) {
type testSubStruct struct {
Value string `json:"json_value" form:"form_value"`
}
type testStruct struct {
// Divergent names: the form name must win on the wire.
Renamed string `json:"json_name" form:"form_name"`
// omitempty only on the form tag: zero value is omitted even
// though the json tag would keep it.
FormOmit string `json:"keep" form:"form_omit,omitempty"`
// omitempty only on the json tag: the form tag wins, so the zero
// value is NOT omitted.
JSONOmit string `json:"json_omit,omitempty" form:"form_keep"`
// Skipped for form encoding only.
FormSkipped string `json:"json_visible" form:"-"`
// No form tag: json tag remains authoritative.
Fallback string `json:"fallback_name,omitempty"`
// Nested structs resolve their fields the same way.
Nested testSubStruct `form:"nested,omitempty"`
}
src := testStruct{
Renamed: "a",
FormSkipped: "hidden",
Fallback: "b",
Nested: testSubStruct{Value: "c"},
}
marshaled, err := MarshalForm(src, nil)
require.NoError(t, err)
encoded, err := url.QueryUnescape(marshaled.Encode())
require.NoError(t, err)
assert.Equal(t, "fallback_name=b&form_keep=&form_name=a&nested[form_value]=c", encoded)
// Binding uses the same tag resolution, so the marshaled form
// round-trips (minus the form-skipped field).
var dst testStruct
require.NoError(t, BindForm(&dst, marshaled, nil, nil))
want := src
want.FormSkipped = ""
assert.Equal(t, want, dst)
}