Debian Codegraph @

values_test.go

raw
1 package schema
2
3 import (
4 "errors"
5 "math/rand/v2"
6 "reflect"
7 "slices"
8 "strconv"
9 "strings"
10 "testing"
11 "time"
12 )
13
14 // valuesTarget exercises every way a key reaches a field: scalars and their
15 // pointers, slices built from repeated keys and from commas, nested and
16 // embedded structs, slices of structs addressed by index, TextUnmarshaler
17 // and custom-converter types, required keys and defaults.
18 type valuesTarget struct {
19 Embedded
20 Time time.Time `schema:"time"`
21 Nested valuesNested `schema:"nested"`
22 PNested *valuesNested `schema:"pnested"`
23 Custom valuesCustom `schema:"custom"`
24 PStr *string `schema:"pstr"`
25 Rude rudeBool `schema:"rude"`
26 Str string `schema:"str"`
27 Strs []string `schema:"strs"`
28 Ints []int `schema:"ints"`
29 Items []valuesNested `schema:"items"`
30 Named []IntAlias `schema:"named"`
31 Float float64 `schema:"float"`
32 Int int `schema:"int"`
33 Def int `schema:"def,default:42"`
34 Req string `schema:"req,required"`
35 Bool bool `schema:"bool"`
36 }
37
38 type Embedded struct {
39 Emb string `schema:"emb"`
40 }
41
42 // valuesCustom decodes through a registered converter.
43 type valuesCustom struct {
44 S string
45 }
46
47 type valuesNested struct {
48 A string `schema:"a"`
49 B []int `schema:"b"`
50 NReq string `schema:"nreq,required"`
51 }
52
53 // decodeBoth decodes pairs through DecodeValues and through Decode, into
54 // fresh values of the same type, and returns both results.
55 func decodeBoth[T any](t *testing.T, d *Decoder, keys, values []string) (viaValues, viaMap T, errValues, errMap error) { //nolint:nonamedreturns,gocritic // the four results read best named
56 t.Helper()
57 m := make(map[string][]string, len(keys))
58 for i, key := range keys {
59 m[key] = append(m[key], values[i])
60 }
61 errValues = d.DecodeValues(&viaValues, keys, values)
62 errMap = d.Decode(&viaMap, m)
63 return viaValues, viaMap, errValues, errMap
64 }
65
66 // requireSameErrors requires two decode errors to report the same keys with
67 // the same messages.
68 func requireSameErrors(t *testing.T, want, got error, context string) {
69 t.Helper()
70 if (want == nil) != (got == nil) {
71 t.Fatalf("%s: Decode returned %v, DecodeValues %v", context, want, got)
72 }
73 if want == nil {
74 return
75 }
76 var wantMulti, gotMulti MultiError
77 if !errors.As(want, &wantMulti) || !errors.As(got, &gotMulti) {
78 if want.Error() != got.Error() {
79 t.Fatalf("%s: Decode returned %q, DecodeValues %q", context, want, got)
80 }
81 return
82 }
83 if len(wantMulti) != len(gotMulti) {
84 t.Fatalf("%s: Decode reported %v, DecodeValues %v", context, wantMulti, gotMulti)
85 }
86 for key, err := range wantMulti {
87 if gotErr, ok := gotMulti[key]; !ok || gotErr.Error() != err.Error() {
88 t.Fatalf("%s: key %q: Decode reported %v, DecodeValues %v", context, key, err, gotMulti[key])
89 }
90 }
91 }
92
93 // TestDecodeValuesMatchesDecode is the differential guard for DecodeValues:
94 // across generated pairs, repeated keys adjacent and apart, empty values,
95 // unknown and malformed keys, and every decoder option, it must decode what
96 // Decode decodes from the map the same pairs make, and report the same errors.
97 func TestDecodeValuesMatchesDecode(t *testing.T) {
98 t.Parallel()
99
100 keyPool := []string{
101 "str", "Str", "pstr", "strs", "ints", "int", "float", "bool", "rude",
102 "time", "custom", "named", "emb", "def", "req", "nested.a", "nested.b",
103 "nested.nreq", "pnested.a", "pnested.nreq", "items.0.a", "items.1.b",
104 "items.3.nreq", "unknown", "nested.unknown", "items.x.a", "items.1001.a", "",
105 "nested", "pnested", ".", "a..b",
106 }
107 valuePool := []string{
108 "", "x", "1", "2", "-3", "4.5", "true", "on", "no", "1,2", "a,b,", "nope",
109 "2006-01-02T15:04:05Z", "99999999999999999999",
110 }
111
112 rng := rand.New(rand.NewPCG(7, 11)) //nolint:gosec // deterministic test input, not security
113 for _, option := range []func(*Decoder){
114 func(*Decoder) {},
115 func(d *Decoder) { d.IgnoreUnknownKeys(true) },
116 func(d *Decoder) { d.ZeroEmpty(true) },
117 func(d *Decoder) { d.IgnoreUnknownKeys(true); d.ZeroEmpty(true) },
118 } {
119 d := NewDecoder()
120 option(d)
121 d.RegisterConverter(valuesCustom{}, func(s string) reflect.Value {
122 if s == "nope" {
123 return reflect.Value{}
124 }
125 return reflect.ValueOf(valuesCustom{S: s})
126 })
127 for round := range 3000 {
128 n := rng.IntN(12)
129 keys := make([]string, 0, n)
130 values := make([]string, 0, n)
131 for range n {
132 key := keyPool[rng.IntN(len(keyPool))]
133 // The keys that differ from "str" only in case name one field
134 // between them, which Decode resolves in map order: keep one.
135 if key == "Str" && slices.Contains(keys, "str") || key == "str" && slices.Contains(keys, "Str") {
136 continue
137 }
138 // An empty value under a struct's own key zeroes the whole
139 // struct with ZeroEmpty, wiping the fields its dotted keys
140 // set before it or not, by map order: give it a value.
141 value := func() string {
142 for {
143 v := valuePool[rng.IntN(len(valuePool))]
144 if v != "" || (key != "nested" && key != "pnested") {
145 return v
146 }
147 }
148 }
149 keys = append(keys, key)
150 values = append(values, value())
151 // Now and then repeat the key, next to it or later on.
152 if rng.IntN(4) == 0 {
153 keys = append(keys, key)
154 values = append(values, value())
155 }
156 }
157
158 viaValues, viaMap, errValues, errMap := decodeBoth[valuesTarget](t, d, keys, values)
159 context := "round " + strconv.Itoa(round) + " pairs " + pairsString(keys, values)
160 requireSameErrors(t, errMap, errValues, context)
161 if !reflect.DeepEqual(viaMap, viaValues) {
162 t.Fatalf("%s: Decode decoded %+v, DecodeValues %+v", context, viaMap, viaValues)
163 }
164 }
165 }
166 }
167
168 func pairsString(keys, values []string) string {
169 var b strings.Builder
170 for i := range keys {
171 if i > 0 {
172 b.WriteByte('&')
173 }
174 b.WriteString(keys[i] + "=" + values[i])
175 }
176 return b.String()
177 }
178
179 // TestDecodeValuesGroupsKeys pins how pairs of one key become its values:
180 // in the order given, whether the pairs are adjacent or not, past the pairs
181 // grouped on the stack, and with the key found again when required keys and
182 // defaults look it up.
183 func TestDecodeValuesGroupsKeys(t *testing.T) {
184 t.Parallel()
185
186 type target struct {
187 A []string `schema:"a"`
188 B []int `schema:"b"`
189 C string `schema:"c"`
190 Req []string `schema:"req,required"`
191 Def string `schema:"def,default:d"`
192 }
193 d := NewDecoder()
194
195 var got target
196 err := d.DecodeValues(&got,
197 []string{"a", "b", "a", "a", "c", "b", "c", "req", "req"},
198 []string{"1", "2", "3", "4", "first", "5", "last", "", "r"})
199 if err != nil {
200 t.Fatalf("unexpected error: %v", err)
201 }
202 // Without ZeroEmpty an empty value adds no element.
203 want := target{A: []string{"1", "3", "4"}, B: []int{2, 5}, C: "last", Req: []string{"r"}, Def: "d"}
204 if !reflect.DeepEqual(want, got) {
205 t.Fatalf("got %+v, want %+v", got, want)
206 }
207
208 // More pairs than the stack holds, so the grouping is allocated.
209 var keys, values []string
210 for i := range maxInlinePairs * 3 {
211 keys = append(keys, "ab"[i%2:i%2+1])
212 values = append(values, strconv.Itoa(i))
213 }
214 keys = append(keys, "req")
215 values = append(values, "r")
216 got = target{}
217 if err = d.DecodeValues(&got, keys, values); err != nil {
218 t.Fatalf("unexpected error: %v", err)
219 }
220 if len(got.A) != maxInlinePairs*3/2 || got.A[0] != "0" || got.A[len(got.A)-1] != strconv.Itoa(maxInlinePairs*3-2) {
221 t.Fatalf("grouped values out of order: %v", got.A)
222 }
223 if len(got.B) != maxInlinePairs*3/2 || got.B[0] != 1 {
224 t.Fatalf("grouped values out of order: %v", got.B)
225 }
226
227 // A required key given only empty values is still missing, and a key
228 // given no pairs at all takes its default.
229 got = target{}
230 err = d.DecodeValues(&got, []string{"c"}, []string{"x"})
231 var multi MultiError
232 if !errors.As(err, &multi) || multi["req"] == nil {
233 t.Fatalf("expected the missing required key to be reported, got %v", err)
234 }
235 if got.Def != "d" {
236 t.Fatalf("expected the default, got %q", got.Def)
237 }
238 }
239
240 // A nested field's default applies only while no key under its struct's
241 // prefix provides the field, which the check looks up with the prefix and
242 // the field's name assembled in a buffer: among a few pairs by comparing
243 // keys, among more through the hash table. A key given with an empty value
244 // leaves its field zero but still counts as provided, as it does for Decode.
245 func TestDecodeValuesNestedDefaults(t *testing.T) {
246 t.Parallel()
247
248 type inner struct {
249 A string `schema:"a,default:da"`
250 B string `schema:"b,default:db"`
251 }
252 type target struct {
253 In inner `schema:"in"`
254 }
255 d := NewDecoder()
256 d.IgnoreUnknownKeys(true)
257 for _, filler := range []int{0, 2 * maxScanPairs} {
258 keys := []string{"in.a"}
259 values := []string{""}
260 for i := range filler {
261 keys = append(keys, "filler"+strconv.Itoa(i))
262 values = append(values, "f")
263 }
264 viaValues, viaMap, errValues, errMap := decodeBoth[target](t, d, keys, values)
265 if errValues != nil || errMap != nil {
266 t.Fatalf("%d pairs: unexpected errors %v, %v", len(keys), errValues, errMap)
267 }
268 want := target{In: inner{A: "", B: "db"}}
269 if viaValues != want || viaMap != want {
270 t.Fatalf("%d pairs: DecodeValues decoded %+v, Decode %+v, want %+v", len(keys), viaValues, viaMap, want)
271 }
272 }
273 }
274
275 // caseVariants returns every spelling of word, which must be lowercase
276 // letters, in upper and lower case: 1<<len(word) keys naming one field.
277 func caseVariants(word string) []string {
278 keys := make([]string, 1<<len(word))
279 for i := range keys {
280 b := []byte(word)
281 for j := range b {
282 if i>>j&1 == 1 {
283 b[j] -= 'a' - 'A'
284 }
285 }
286 keys[i] = string(b)
287 }
288 return keys
289 }
290
291 // The pairs' keys are the request's, so the table grouping them must not
292 // let chosen keys pile onto one slot. Keys that differ only in case group
293 // apart, and a case-folding hash sent them all to the same slot: each
294 // insert then probed past every key before it, quadratic in their number.
295 // Built from every case variant of one key, the table keeps every key close
296 // to its home slot.
297 func TestPairIndexSpreadsCaseVariants(t *testing.T) {
298 t.Parallel()
299
300 keys := caseVariants("abcdefghij")
301 n := len(keys)
302 values := make([]string, n)
303 p := pairIndex{
304 keys: keys, values: values,
305 table: make([]int32, indexSize(n)), next: make([]int32, n), last: make([]int32, n),
306 }
307 p.index()
308 longest := 0
309 for i, key := range keys {
310 if !p.first(i) || p.find(key) != i || p.findBytes([]byte(key)) != i {
311 t.Fatalf("%q is not a key of its own", key)
312 }
313 // How far the key sits past the slot its hash names.
314 for j, d := pairHash(key)&p.mask, 0; ; j, d = (j+1)&p.mask, d+1 {
315 if int(p.table[j]) == i+1 {
316 longest = max(longest, d)
317 break
318 }
319 }
320 }
321 // A seeded hash at half load keeps the longest probe near log n; the
322 // case-folding hash put the last variant n-1 slots out.
323 if longest > 64 {
324 t.Fatalf("a key sits %d slots past its home slot of %d; the keys pile up", longest, len(p.table))
325 }
326 }
327
328 // Every case variant of a key names the same field. Each is a key of its
329 // own, and DecodeValues decodes keys in the order they first appear, so the
330 // last variant sets the field.
331 func TestDecodeValuesCaseVariants(t *testing.T) {
332 t.Parallel()
333
334 type target struct {
335 F string `schema:"abcdefgh"`
336 }
337 keys := caseVariants("abcdefgh")
338 values := make([]string, len(keys))
339 for i := range values {
340 values[i] = strconv.Itoa(i)
341 }
342 var got target
343 if err := NewDecoder().DecodeValues(&got, keys, values); err != nil {
344 t.Fatalf("unexpected error: %v", err)
345 }
346 if want := values[len(values)-1]; got.F != want {
347 t.Fatalf("got %q, want the last variant's value %q", got.F, want)
348 }
349 }
350
351 func TestDecodeValuesRejectsMismatchedInput(t *testing.T) {
352 t.Parallel()
353
354 d := NewDecoder()
355 var s struct {
356 A string `schema:"a"`
357 }
358 if err := d.DecodeValues(&s, []string{"a"}, nil); !errors.Is(err, errValuesLength) {
359 t.Fatalf("expected errValuesLength, got %v", err)
360 }
361 if err := d.DecodeValues(s, []string{"a"}, []string{"x"}); !errors.Is(err, errNotPointerToStruct) {
362 t.Fatalf("expected errNotPointerToStruct, got %v", err)
363 }
364 if err := d.DecodeValues(&s, nil, nil); err != nil {
365 t.Fatalf("expected no error for no pairs, got %v", err)
366 }
367 }
368
369 // TestDecodeValuesDoesNotAllocate pins that grouping the pairs costs no
370 // allocation: a struct of scalars decodes without any.
371 func TestDecodeValuesDoesNotAllocate(t *testing.T) { //nolint:paralleltest // testing.AllocsPerRun panics in a parallel test
372 type target struct {
373 A string `schema:"a"`
374 B int `schema:"b"`
375 C bool `schema:"c"`
376 D float64 `schema:"d"`
377 }
378 d := NewDecoder()
379 keys := []string{"a", "b", "c", "d", "b", "unknown"}
380 values := []string{"x", "1", "true", "2.5", "2", "y"}
381 d.IgnoreUnknownKeys(true)
382 var s target
383 if err := d.DecodeValues(&s, keys, values); err != nil {
384 t.Fatalf("unexpected error: %v", err)
385 }
386 if allocs := testing.AllocsPerRun(100, func() {
387 _ = d.DecodeValues(&s, keys, values) //nolint:errcheck // checked above
388 }); allocs != 0 {
389 t.Fatalf("DecodeValues allocated %v times per run", allocs)
390 }
391 }
392
393 func BenchmarkDecodeValues(b *testing.B) {
394 type target struct {
395 Name string `schema:"name"`
396 Hobby []string `schema:"hobby"`
397 ID int `schema:"id"`
398 }
399 keys := []string{"id", "name", "hobby", "hobby"}
400 values := []string{"1", "tom", "basketball", "football"}
401 m := map[string][]string{"id": {"1"}, "name": {"tom"}, "hobby": {"basketball", "football"}}
402 d := NewDecoder()
403 var s target
404
405 b.Run("values", func(b *testing.B) {
406 b.ReportAllocs()
407 for b.Loop() {
408 _ = d.DecodeValues(&s, keys, values) //nolint:errcheck // benchmark
409 }
410 })
411 b.Run("map", func(b *testing.B) {
412 b.ReportAllocs()
413 for b.Loop() {
414 _ = d.Decode(&s, m) //nolint:errcheck // benchmark
415 }
416 })
417 }
418
419 // TestDecodeStackStateDoesNotAllocate pins that what a decode keeps from key
420 // to key, the required-key bitset and the slice growth tracker, stays on the
421 // stack for both Decode and DecodeValues: a struct with required keys and an
422 // indexed slice that needs no growing decodes without allocating.
423 func TestDecodeStackStateDoesNotAllocate(t *testing.T) { //nolint:paralleltest // testing.AllocsPerRun panics in a parallel test
424 type item struct {
425 A string `schema:"a"`
426 }
427 type target struct {
428 Req string `schema:"req,required"`
429 Items []item `schema:"items"`
430 }
431 d := NewDecoder()
432 keys := []string{"req", "items.0.a", "items.1.a"}
433 values := []string{"x", "y", "z"}
434 m := map[string][]string{"req": {"x"}, "items.0.a": {"y"}, "items.1.a": {"z"}}
435 s := target{Items: make([]item, 2)}
436
437 if err := d.DecodeValues(&s, keys, values); err != nil {
438 t.Fatalf("unexpected error: %v", err)
439 }
440 if err := d.Decode(&s, m); err != nil {
441 t.Fatalf("unexpected error: %v", err)
442 }
443 if s.Req != "x" || s.Items[0].A != "y" || s.Items[1].A != "z" {
444 t.Fatalf("unexpected result %+v", s)
445 }
446 if allocs := testing.AllocsPerRun(100, func() {
447 _ = d.DecodeValues(&s, keys, values) //nolint:errcheck // checked above
448 }); allocs != 0 {
449 t.Fatalf("DecodeValues allocated %v times per run", allocs)
450 }
451 if allocs := testing.AllocsPerRun(100, func() {
452 _ = d.Decode(&s, m) //nolint:errcheck // checked above
453 }); allocs != 0 {
454 t.Fatalf("Decode allocated %v times per run", allocs)
455 }
456 }