Debian Codegraph @

fastpath_test.go

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 package schema
2
3 import (
4 "reflect"
5 "strings"
6 "testing"
7 "time"
8 )
9
10 // Keys served by the direct-path map must behave exactly like the generic
11 // parser: case-insensitive, covering flat aliases and nested dotted chains.
12 func TestDirectPathLookup(t *testing.T) {
13 type Inner struct {
14 Value string `schema:"value"`
15 }
16 type Outer struct {
17 Name string `schema:"name"`
18 Nested Inner `schema:"nested"`
19 }
20
21 for _, keys := range []struct {
22 name, nested string
23 }{
24 {"name", "nested.value"},
25 {"NAME", "NESTED.VALUE"},
26 {"NaMe", "NeStEd.VaLuE"},
27 } {
28 var s Outer
29 data := map[string][]string{
30 keys.name: {"x"},
31 keys.nested: {"y"},
32 }
33 if err := NewDecoder().Decode(&s, data); err != nil {
34 t.Fatalf("Decode(%q, %q): %v", keys.name, keys.nested, err)
35 }
36 if s.Name != "x" || s.Nested.Value != "y" {
37 t.Fatalf("Decode(%q, %q) = %+v, want Name=x Nested.Value=y", keys.name, keys.nested, s)
38 }
39 }
40 }
41
42 // Direct-path entries exist for statically-resolvable keys only; everything
43 // else must keep flowing through the generic parser unchanged.
44 func TestDirectPathLookupFallbacks(t *testing.T) {
45 // Keys longer than the case-fold buffer take the generic path.
46 longAlias := strings.Repeat("a", maxDirectKeyLen+8)
47 type Long struct {
48 Field string `schema:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"`
49 }
50 if len(longAlias) != maxDirectKeyLen+8 {
51 t.Fatal("bad test setup")
52 }
53 var l Long
54 if err := NewDecoder().Decode(&l, map[string][]string{longAlias: {"v"}}); err != nil {
55 t.Fatalf("long key: %v", err)
56 }
57 if l.Field != "v" {
58 t.Fatalf("long key decoded %+v", l)
59 }
60
61 // A bare slice-of-structs alias still needs a slice index; the direct map
62 // must not make it valid.
63 type Item struct {
64 Value string `schema:"value"`
65 }
66 type WithItems struct {
67 Items []Item `schema:"items"`
68 }
69 var w WithItems
70 err := NewDecoder().Decode(&w, map[string][]string{"items": {"x"}})
71 if err == nil {
72 t.Fatal("bare slice-of-structs alias must remain an invalid path")
73 }
74 if _, ok := err.(MultiError)["items"].(UnknownKeyError); !ok {
75 t.Fatalf("want UnknownKeyError, got %v", err)
76 }
77
78 // Pointer-to-struct chains are not precomputed but must keep decoding.
79 type Inner struct {
80 Value string `schema:"value"`
81 }
82 type WithPtr struct {
83 Nested *Inner `schema:"nested"`
84 }
85 var p WithPtr
86 if err := NewDecoder().Decode(&p, map[string][]string{"NESTED.value": {"y"}}); err != nil {
87 t.Fatalf("pointer chain: %v", err)
88 }
89 if p.Nested == nil || p.Nested.Value != "y" {
90 t.Fatalf("pointer chain decoded %+v", p)
91 }
92 }
93
94 // The native slice decode path must keep the generic path's semantics: comma
95 // splitting, zeroEmpty, all-or-nothing assignment, ConversionError details.
96 func TestNativeSliceDecode(t *testing.T) {
97 type S struct {
98 Tags []string `schema:"tags"`
99 IDs []int `schema:"ids"`
100 Scores []float64 `schema:"scores"`
101 Flags []bool `schema:"flags"`
102 Big []int64 `schema:"big"`
103 U []uint `schema:"u"`
104 U64 []uint64 `schema:"u64"`
105 }
106
107 var s S
108 data := map[string][]string{
109 "tags": {"a", "b,c", ""}, // strings never split on commas
110 "ids": {"1,2", "3"},
111 "scores": {"1.5", "2.5"},
112 "flags": {"true", "on"},
113 "big": {"9007199254740993"},
114 "u": {"7"},
115 "u64": {"18446744073709551615"},
116 }
117 if err := NewDecoder().Decode(&s, data); err != nil {
118 t.Fatal(err)
119 }
120 want := S{
121 Tags: []string{"a", "b,c"},
122 IDs: []int{1, 2, 3},
123 Scores: []float64{1.5, 2.5},
124 Flags: []bool{true, true},
125 Big: []int64{9007199254740993},
126 U: []uint{7},
127 U64: []uint64{18446744073709551615},
128 }
129 if !reflect.DeepEqual(s, want) {
130 t.Fatalf("got %+v, want %+v", s, want)
131 }
132
133 // zeroEmpty appends zero values for empty items.
134 var z S
135 d := NewDecoder()
136 d.ZeroEmpty(true)
137 if err := d.Decode(&z, map[string][]string{"ids": {"1,,2", ""}}); err != nil {
138 t.Fatal(err)
139 }
140 if !reflect.DeepEqual(z.IDs, []int{1, 0, 2, 0}) {
141 t.Fatalf("zeroEmpty got %v", z.IDs)
142 }
143
144 // A parse failure must leave the field untouched and carry the value's
145 // index in the ConversionError.
146 pre := S{IDs: []int{42}}
147 err := NewDecoder().Decode(&pre, map[string][]string{"ids": {"1", "oops"}})
148 if err == nil {
149 t.Fatal("want conversion error")
150 }
151 convErr, ok := err.(MultiError)["ids"].(ConversionError)
152 if !ok {
153 t.Fatalf("want ConversionError, got %v", err)
154 }
155 if convErr.Index != 1 {
156 t.Fatalf("want Index=1, got %d", convErr.Index)
157 }
158 if !reflect.DeepEqual(pre.IDs, []int{42}) {
159 t.Fatalf("field must stay untouched on error, got %v", pre.IDs)
160 }
161 }
162
163 // Named slice types take the generic reflect loop, not the native path; its
164 // semantics must match the native path's exactly.
165 func TestGenericSliceNamedTypes(t *testing.T) {
166 type IDs []int
167 type Tags []string
168 type S struct {
169 IDs IDs `schema:"ids"`
170 Tags Tags `schema:"tags"`
171 }
172
173 var s S
174 data := map[string][]string{
175 "ids": {"1,2", "3"},
176 "tags": {"a", "b,c"},
177 }
178 if err := NewDecoder().Decode(&s, data); err != nil {
179 t.Fatal(err)
180 }
181 if !reflect.DeepEqual(s.IDs, IDs{1, 2, 3}) || !reflect.DeepEqual(s.Tags, Tags{"a", "b,c"}) {
182 t.Fatalf("got %+v", s)
183 }
184
185 // zeroEmpty fills zero slots; empties are dropped without it.
186 var z S
187 d := NewDecoder()
188 d.ZeroEmpty(true)
189 if err := d.Decode(&z, map[string][]string{"ids": {"1,,2", ""}}); err != nil {
190 t.Fatal(err)
191 }
192 if !reflect.DeepEqual(z.IDs, IDs{1, 0, 2, 0}) {
193 t.Fatalf("zeroEmpty got %v", z.IDs)
194 }
195 var trunc S
196 if err := NewDecoder().Decode(&trunc, map[string][]string{"ids": {"1,,2", ""}}); err != nil {
197 t.Fatal(err)
198 }
199 if !reflect.DeepEqual(trunc.IDs, IDs{1, 2}) {
200 t.Fatalf("truncation got %v", trunc.IDs)
201 }
202
203 // Parse failures, both inside a comma list and as a plain value.
204 for _, bad := range []string{"1,x", "x"} {
205 var b S
206 err := NewDecoder().Decode(&b, map[string][]string{"ids": {bad}})
207 if _, ok := err.(MultiError)["ids"].(ConversionError); !ok {
208 t.Fatalf("value %q: want ConversionError, got %v", bad, err)
209 }
210 }
211 }
212
213 // Fields the fast scalar path skips (pointers) keep their generic behavior.
214 func TestGenericScalarFallbacks(t *testing.T) {
215 type S struct {
216 N *int `schema:"n"`
217 }
218
219 // Empty value + ZeroEmpty on a pointer field takes the generic zeroing.
220 d := NewDecoder()
221 d.ZeroEmpty(true)
222 var s S
223 if err := d.Decode(&s, map[string][]string{"n": {""}}); err != nil {
224 t.Fatal(err)
225 }
226 if s.N == nil || *s.N != 0 {
227 t.Fatalf("want zeroed *int, got %+v", s.N)
228 }
229 }
230
231 // Encoding into a fresh dst must handle every appendValue branch: duplicate
232 // aliases appending to a scratch-backed entry, caller-derived strings and
233 // long formatter output bypassing the shared scratch, and short numeric
234 // values using it.
235 func TestEncodeDuplicateAliasFreshDst(t *testing.T) {
236 type S struct {
237 A int `schema:"k"`
238 B int `schema:"k"`
239 C string `schema:"c"`
240 L float64 `schema:"l"`
241 }
242 dst := map[string][]string{}
243 // 1e300 in 'f' format is far longer than maxScratchValueLen.
244 if err := NewEncoder().Encode(S{A: 1, B: 2, C: "3", L: 1e300}, dst); err != nil {
245 t.Fatal(err)
246 }
247 if !reflect.DeepEqual(dst["k"], []string{"1", "2"}) || !reflect.DeepEqual(dst["c"], []string{"3"}) {
248 t.Fatalf("got %v", dst)
249 }
250 if len(dst["l"]) != 1 || len(dst["l"][0]) <= maxScratchValueLen {
251 t.Fatalf("long value got %v", dst["l"])
252 }
253 }
254
255 type sliceHeavyStruct struct {
256 Tags []string `schema:"tags"`
257 IDs []int `schema:"ids"`
258 Scores []float64 `schema:"scores"`
259 Flags []bool `schema:"flags"`
260 }
261
262 func BenchmarkSliceHeavyDecode(b *testing.B) {
263 data := map[string][]string{
264 "tags": {"alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi"},
265 "ids": {"1,2,3,4,5,6,7,8", "9,10,11,12,13,14,15,16"},
266 "scores": {"1.5", "2.5", "3.5", "4.5", "5.5", "6.5", "7.5", "8.5"},
267 "flags": {"true", "false", "true", "false", "true", "false", "true", "false"},
268 }
269 decoder := NewDecoder()
270 s := &sliceHeavyStruct{}
271 b.ReportAllocs()
272 for b.Loop() {
273 if err := decoder.Decode(s, data); err != nil {
274 b.Fatal(err)
275 }
276 }
277 }
278
279 type fan0 struct {
280 V string `schema:"v"`
281 }
282 type fan1 struct {
283 A fan0 `schema:"a"`
284 B fan0 `schema:"b"`
285 }
286 type fan2 struct {
287 A fan1 `schema:"a"`
288 B fan1 `schema:"b"`
289 }
290 type fan3 struct {
291 A fan2 `schema:"a"`
292 B fan2 `schema:"b"`
293 }
294 type fan4 struct {
295 A fan3 `schema:"a"`
296 B fan3 `schema:"b"`
297 }
298 type fan5 struct {
299 A fan4 `schema:"a"`
300 B fan4 `schema:"b"`
301 }
302 type fan6 struct {
303 A fan5 `schema:"a"`
304 B fan5 `schema:"b"`
305 }
306 type fan7 struct {
307 A fan6 `schema:"a"`
308 B fan6 `schema:"b"`
309 }
310 type fan8 struct {
311 A fan7 `schema:"a"`
312 B fan7 `schema:"b"`
313 }
314 type fan9 struct {
315 A fan8 `schema:"a"`
316 B fan8 `schema:"b"`
317 }
318 type fan10 struct {
319 A fan9 `schema:"a"`
320 B fan9 `schema:"b"`
321 }
322 type fan11 struct {
323 A fan10 `schema:"a"`
324 B fan10 `schema:"b"`
325 }
326 type fan12 struct {
327 A fan11 `schema:"a"`
328 B fan11 `schema:"b"`
329 }
330 type fan13 struct {
331 A fan12 `schema:"a"`
332 B fan12 `schema:"b"`
333 }
334 type fan14 struct {
335 A fan13 `schema:"a"`
336 B fan13 `schema:"b"`
337 }
338 type fan15 struct {
339 A fan14 `schema:"a"`
340 B fan14 `schema:"b"`
341 }
342 type fan16 struct {
343 A fan15 `schema:"a"`
344 B fan15 `schema:"b"`
345 }
346 type fan17 struct {
347 A fan16 `schema:"a"`
348 B fan16 `schema:"b"`
349 }
350 type fan18 struct {
351 A fan17 `schema:"a"`
352 B fan17 `schema:"b"`
353 }
354 type fan19 struct {
355 A fan18 `schema:"a"`
356 B fan18 `schema:"b"`
357 }
358
359 // Deep fan-out nesting has exponentially many dotted paths; the direct map
360 // must stay capped so the first Decode neither stalls nor retains huge maps.
361 func TestDirectPathsCappedForDeepFanout(t *testing.T) {
362 d := NewDecoder()
363 var s fan19
364 deepKey := strings.Repeat("a.", 10) + strings.Repeat("b.", 9) + "v"
365 data := map[string][]string{deepKey: {"deep"}}
366 done := make(chan error, 1)
367 go func() { done <- d.Decode(&s, data) }()
368 select {
369 case err := <-done:
370 if err != nil {
371 t.Fatal(err)
372 }
373 case <-time.After(30 * time.Second):
374 t.Fatal("Decode stalled: direct-path precomputation not capped")
375 }
376 if s.A.A.A.A.A.A.A.A.A.A.B.B.B.B.B.B.B.B.B.V != "deep" {
377 t.Fatal("deep key not decoded")
378 }
379 info := d.cache.get(reflect.TypeOf(s))
380 if len(info.direct) > maxDirectPaths+2 {
381 t.Fatalf("direct map has %d entries, want <= %d", len(info.direct), maxDirectPaths+2)
382 }
383 }
384
385 // Unlike the other encode benchmarks, this one encodes into a fresh map each
386 // iteration, matching how callers build url.Values per request.
387 func BenchmarkEncodeFreshDst(b *testing.B) {
388 type S struct {
389 A string `schema:"a"`
390 B int `schema:"b"`
391 C bool `schema:"c"`
392 D float64 `schema:"d"`
393 E []int `schema:"e"`
394 F string `schema:"f,omitempty"`
395 }
396 s := S{A: "abc", B: 123, C: true, D: 3.14, E: []int{1, 2, 3}}
397 enc := NewEncoder()
398 b.ReportAllocs()
399 for b.Loop() {
400 vals := make(map[string][]string, 8)
401 if err := enc.Encode(&s, vals); err != nil {
402 b.Fatal(err)
403 }
404 }
405 }
406
407 func BenchmarkMixedCaseKeyDecode(b *testing.B) {
408 type S struct {
409 FirstName string `schema:"firstName"`
410 LastName string `schema:"lastName"`
411 Age int `schema:"age"`
412 }
413 data := map[string][]string{
414 "FirstName": {"Grace"},
415 "LASTNAME": {"Hopper"},
416 "age": {"85"},
417 }
418 decoder := NewDecoder()
419 s := &S{}
420 for b.Loop() {
421 if err := decoder.Decode(s, data); err != nil {
422 b.Fatal(err)
423 }
424 }
425 }