| 1 |
// Copyright 2012 The Gorilla Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package schema |
| 6 |
|
| 7 |
import ( |
| 8 |
"encoding/hex" |
| 9 |
"errors" |
| 10 |
"fmt" |
| 11 |
"math" |
| 12 |
"math/rand/v2" |
| 13 |
"mime/multipart" |
| 14 |
"reflect" |
| 15 |
"strconv" |
| 16 |
"strings" |
| 17 |
"sync" |
| 18 |
"testing" |
| 19 |
"time" |
| 20 |
) |
| 21 |
|
| 22 |
type IntAlias int |
| 23 |
|
| 24 |
type rudeBool bool |
| 25 |
|
| 26 |
func (id *rudeBool) UnmarshalText(text []byte) error { |
| 27 |
value := string(text) |
| 28 |
switch { |
| 29 |
case strings.EqualFold("Yup", value): |
| 30 |
*id = true |
| 31 |
case strings.EqualFold("Nope", value): |
| 32 |
*id = false |
| 33 |
default: |
| 34 |
return errors.New("value must be yup or nope") |
| 35 |
} |
| 36 |
return nil |
| 37 |
} |
| 38 |
|
| 39 |
// All cases we want to cover, in a nutshell. |
| 40 |
type S1 struct { |
| 41 |
F01 int `schema:"f1"` |
| 42 |
F02 *int `schema:"f2"` |
| 43 |
F03 []int `schema:"f3"` |
| 44 |
F04 []*int `schema:"f4"` |
| 45 |
F05 *[]int `schema:"f5"` |
| 46 |
F06 *[]*int `schema:"f6"` |
| 47 |
F07 S2 `schema:"f7"` |
| 48 |
F08 *S1 `schema:"f8"` |
| 49 |
F09 int `schema:"-"` |
| 50 |
F10 []S1 `schema:"f10"` |
| 51 |
F11 []*S1 `schema:"f11"` |
| 52 |
F12 *[]S1 `schema:"f12"` |
| 53 |
F13 *[]*S1 `schema:"f13"` |
| 54 |
F14 int `schema:"f14"` |
| 55 |
F15 IntAlias `schema:"f15"` |
| 56 |
F16 []IntAlias `schema:"f16"` |
| 57 |
F17 S19 `schema:"f17"` |
| 58 |
F18 rudeBool `schema:"f18"` |
| 59 |
F19 *rudeBool `schema:"f19"` |
| 60 |
F20 []rudeBool `schema:"f20"` |
| 61 |
F21 []*rudeBool `schema:"f21"` |
| 62 |
} |
| 63 |
|
| 64 |
type LargeStructForBenchmark struct { |
| 65 |
F1 string `schema:"f1"` |
| 66 |
F2 string `schema:"f2"` |
| 67 |
F3 int `schema:"f3"` |
| 68 |
F4 int `schema:"f4"` |
| 69 |
F5 []string `schema:"f5"` |
| 70 |
F6 []int `schema:"f6"` |
| 71 |
F7 float64 `schema:"f7"` |
| 72 |
F8 bool `schema:"f8"` |
| 73 |
F9 struct { |
| 74 |
N1 time.Time `schema:"n1"` |
| 75 |
N2 string `schema:"n2"` |
| 76 |
} `schema:"f9"` |
| 77 |
} |
| 78 |
|
| 79 |
// A simple struct for demonstration benchmarks |
| 80 |
type SimpleStructForBenchmark struct { |
| 81 |
A string `schema:"a"` |
| 82 |
B int `schema:"b"` |
| 83 |
C bool `schema:"c"` |
| 84 |
D float64 `schema:"d"` |
| 85 |
E struct { |
| 86 |
F float64 `schema:"f"` |
| 87 |
} `schema:"e"` |
| 88 |
} |
| 89 |
|
| 90 |
type S2 struct { |
| 91 |
F01 *[]*int `schema:"f1"` |
| 92 |
} |
| 93 |
|
| 94 |
type S19 [2]byte |
| 95 |
|
| 96 |
func (id *S19) UnmarshalText(text []byte) error { |
| 97 |
buf, err := hex.DecodeString(string(text)) |
| 98 |
if err != nil { |
| 99 |
return err |
| 100 |
} |
| 101 |
if len(buf) > len(*id) { |
| 102 |
return errors.New("out of range") |
| 103 |
} |
| 104 |
copy((*id)[:], buf) |
| 105 |
return nil |
| 106 |
} |
| 107 |
|
| 108 |
func TestAll(t *testing.T) { |
| 109 |
v := map[string][]string{ |
| 110 |
"f1": {"1"}, |
| 111 |
"f2": {"2"}, |
| 112 |
"f3": {"31", "32"}, |
| 113 |
"f4": {"41", "42"}, |
| 114 |
"f5": {"51", "52"}, |
| 115 |
"f6": {"61", "62"}, |
| 116 |
"f7.f1": {"71", "72"}, |
| 117 |
"f8.f8.f7.f1": {"81", "82"}, |
| 118 |
"f9": {"9"}, |
| 119 |
"f10.0.f10.0.f6": {"101", "102"}, |
| 120 |
"f10.0.f10.1.f6": {"103", "104"}, |
| 121 |
"f11.0.f11.0.f6": {"111", "112"}, |
| 122 |
"f11.0.f11.1.f6": {"113", "114"}, |
| 123 |
"f12.0.f12.0.f6": {"121", "122"}, |
| 124 |
"f12.0.f12.1.f6": {"123", "124"}, |
| 125 |
"f13.0.f13.0.f6": {"131", "132"}, |
| 126 |
"f13.0.f13.1.f6": {"133", "134"}, |
| 127 |
"f14": {}, |
| 128 |
"f15": {"151"}, |
| 129 |
"f16": {"161", "162"}, |
| 130 |
"f17": {"1a2b"}, |
| 131 |
"f18": {"yup"}, |
| 132 |
"f19": {"nope"}, |
| 133 |
"f20": {"nope", "yup"}, |
| 134 |
"f21": {"yup", "nope"}, |
| 135 |
} |
| 136 |
f2 := 2 |
| 137 |
f41, f42 := 41, 42 |
| 138 |
f61, f62 := 61, 62 |
| 139 |
f71, f72 := 71, 72 |
| 140 |
f81, f82 := 81, 82 |
| 141 |
f101, f102, f103, f104 := 101, 102, 103, 104 |
| 142 |
f111, f112, f113, f114 := 111, 112, 113, 114 |
| 143 |
f121, f122, f123, f124 := 121, 122, 123, 124 |
| 144 |
f131, f132, f133, f134 := 131, 132, 133, 134 |
| 145 |
var f151 IntAlias = 151 |
| 146 |
var f161, f162 IntAlias = 161, 162 |
| 147 |
var f152, f153 rudeBool = true, false |
| 148 |
e := S1{ |
| 149 |
F01: 1, |
| 150 |
F02: &f2, |
| 151 |
F03: []int{31, 32}, |
| 152 |
F04: []*int{&f41, &f42}, |
| 153 |
F05: &[]int{51, 52}, |
| 154 |
F06: &[]*int{&f61, &f62}, |
| 155 |
F07: S2{ |
| 156 |
F01: &[]*int{&f71, &f72}, |
| 157 |
}, |
| 158 |
F08: &S1{ |
| 159 |
F08: &S1{ |
| 160 |
F07: S2{ |
| 161 |
F01: &[]*int{&f81, &f82}, |
| 162 |
}, |
| 163 |
}, |
| 164 |
}, |
| 165 |
F09: 0, |
| 166 |
F10: []S1{ |
| 167 |
{ |
| 168 |
F10: []S1{ |
| 169 |
{F06: &[]*int{&f101, &f102}}, |
| 170 |
{F06: &[]*int{&f103, &f104}}, |
| 171 |
}, |
| 172 |
}, |
| 173 |
}, |
| 174 |
F11: []*S1{ |
| 175 |
{ |
| 176 |
F11: []*S1{ |
| 177 |
{F06: &[]*int{&f111, &f112}}, |
| 178 |
{F06: &[]*int{&f113, &f114}}, |
| 179 |
}, |
| 180 |
}, |
| 181 |
}, |
| 182 |
F12: &[]S1{ |
| 183 |
{ |
| 184 |
F12: &[]S1{ |
| 185 |
{F06: &[]*int{&f121, &f122}}, |
| 186 |
{F06: &[]*int{&f123, &f124}}, |
| 187 |
}, |
| 188 |
}, |
| 189 |
}, |
| 190 |
F13: &[]*S1{ |
| 191 |
{ |
| 192 |
F13: &[]*S1{ |
| 193 |
{F06: &[]*int{&f131, &f132}}, |
| 194 |
{F06: &[]*int{&f133, &f134}}, |
| 195 |
}, |
| 196 |
}, |
| 197 |
}, |
| 198 |
F14: 0, |
| 199 |
F15: f151, |
| 200 |
F16: []IntAlias{f161, f162}, |
| 201 |
F17: S19{0x1a, 0x2b}, |
| 202 |
F18: f152, |
| 203 |
F19: &f153, |
| 204 |
F20: []rudeBool{f153, f152}, |
| 205 |
F21: []*rudeBool{&f152, &f153}, |
| 206 |
} |
| 207 |
|
| 208 |
s := &S1{} |
| 209 |
_ = NewDecoder().Decode(s, v) |
| 210 |
|
| 211 |
vals := func(values []*int) []int { |
| 212 |
r := make([]int, len(values)) |
| 213 |
for k, v := range values { |
| 214 |
r[k] = *v |
| 215 |
} |
| 216 |
return r |
| 217 |
} |
| 218 |
|
| 219 |
if s.F01 != e.F01 { |
| 220 |
t.Errorf("f1: expected %v, got %v", e.F01, s.F01) |
| 221 |
} |
| 222 |
if s.F02 == nil { |
| 223 |
t.Errorf("f2: expected %v, got nil", *e.F02) |
| 224 |
} else if *s.F02 != *e.F02 { |
| 225 |
t.Errorf("f2: expected %v, got %v", *e.F02, *s.F02) |
| 226 |
} |
| 227 |
if s.F03 == nil { |
| 228 |
t.Errorf("f3: expected %v, got nil", e.F03) |
| 229 |
} else if len(s.F03) != 2 || s.F03[0] != e.F03[0] || s.F03[1] != e.F03[1] { |
| 230 |
t.Errorf("f3: expected %v, got %v", e.F03, s.F03) |
| 231 |
} |
| 232 |
if s.F04 == nil { |
| 233 |
t.Errorf("f4: expected %v, got nil", e.F04) |
| 234 |
} else { |
| 235 |
if len(s.F04) != 2 || *s.F04[0] != *e.F04[0] || *s.F04[1] != *e.F04[1] { |
| 236 |
t.Errorf("f4: expected %v, got %v", vals(e.F04), vals(s.F04)) |
| 237 |
} |
| 238 |
} |
| 239 |
if s.F05 == nil { |
| 240 |
t.Errorf("f5: expected %v, got nil", e.F05) |
| 241 |
} else { |
| 242 |
sF05, eF05 := *s.F05, *e.F05 |
| 243 |
if len(sF05) != 2 || sF05[0] != eF05[0] || sF05[1] != eF05[1] { |
| 244 |
t.Errorf("f5: expected %v, got %v", eF05, sF05) |
| 245 |
} |
| 246 |
} |
| 247 |
if s.F06 == nil { |
| 248 |
t.Errorf("f6: expected %v, got nil", vals(*e.F06)) |
| 249 |
} else { |
| 250 |
sF06, eF06 := *s.F06, *e.F06 |
| 251 |
if len(sF06) != 2 || *sF06[0] != *eF06[0] || *sF06[1] != *eF06[1] { |
| 252 |
t.Errorf("f6: expected %v, got %v", vals(eF06), vals(sF06)) |
| 253 |
} |
| 254 |
} |
| 255 |
if s.F07.F01 == nil { |
| 256 |
t.Errorf("f7.f1: expected %v, got nil", vals(*e.F07.F01)) |
| 257 |
} else { |
| 258 |
sF07, eF07 := *s.F07.F01, *e.F07.F01 |
| 259 |
if len(sF07) != 2 || *sF07[0] != *eF07[0] || *sF07[1] != *eF07[1] { |
| 260 |
t.Errorf("f7.f1: expected %v, got %v", vals(eF07), vals(sF07)) |
| 261 |
} |
| 262 |
} |
| 263 |
if s.F08 == nil { |
| 264 |
t.Errorf("f8: got nil") |
| 265 |
} else if s.F08.F08 == nil { |
| 266 |
t.Errorf("f8.f8: got nil") |
| 267 |
} else if s.F08.F08.F07.F01 == nil { |
| 268 |
t.Errorf("f8.f8.f7.f1: expected %v, got nil", vals(*e.F08.F08.F07.F01)) |
| 269 |
} else { |
| 270 |
sF08, eF08 := *s.F08.F08.F07.F01, *e.F08.F08.F07.F01 |
| 271 |
if len(sF08) != 2 || *sF08[0] != *eF08[0] || *sF08[1] != *eF08[1] { |
| 272 |
t.Errorf("f8.f8.f7.f1: expected %v, got %v", vals(eF08), vals(sF08)) |
| 273 |
} |
| 274 |
} |
| 275 |
if s.F09 != e.F09 { |
| 276 |
t.Errorf("f9: expected %v, got %v", e.F09, s.F09) |
| 277 |
} |
| 278 |
if s.F10 == nil { |
| 279 |
t.Errorf("f10: got nil") |
| 280 |
} else if len(s.F10) != 1 { |
| 281 |
t.Errorf("f10: expected 1 element, got %v", s.F10) |
| 282 |
} else { |
| 283 |
if len(s.F10[0].F10) != 2 { |
| 284 |
t.Errorf("f10.0.f10: expected 1 element, got %v", s.F10[0].F10) |
| 285 |
} else { |
| 286 |
sF10, eF10 := *s.F10[0].F10[0].F06, *e.F10[0].F10[0].F06 |
| 287 |
if sF10 == nil { |
| 288 |
t.Errorf("f10.0.f10.0.f6: expected %v, got nil", vals(eF10)) |
| 289 |
} else { |
| 290 |
if len(sF10) != 2 || *sF10[0] != *eF10[0] || *sF10[1] != *eF10[1] { |
| 291 |
t.Errorf("f10.0.f10.0.f6: expected %v, got %v", vals(eF10), vals(sF10)) |
| 292 |
} |
| 293 |
} |
| 294 |
sF10, eF10 = *s.F10[0].F10[1].F06, *e.F10[0].F10[1].F06 |
| 295 |
if sF10 == nil { |
| 296 |
t.Errorf("f10.0.f10.0.f6: expected %v, got nil", vals(eF10)) |
| 297 |
} else { |
| 298 |
if len(sF10) != 2 || *sF10[0] != *eF10[0] || *sF10[1] != *eF10[1] { |
| 299 |
t.Errorf("f10.0.f10.0.f6: expected %v, got %v", vals(eF10), vals(sF10)) |
| 300 |
} |
| 301 |
} |
| 302 |
} |
| 303 |
} |
| 304 |
if s.F11 == nil { |
| 305 |
t.Errorf("f11: got nil") |
| 306 |
} else if len(s.F11) != 1 { |
| 307 |
t.Errorf("f11: expected 1 element, got %v", s.F11) |
| 308 |
} else { |
| 309 |
if len(s.F11[0].F11) != 2 { |
| 310 |
t.Errorf("f11.0.f11: expected 1 element, got %v", s.F11[0].F11) |
| 311 |
} else { |
| 312 |
sF11, eF11 := *s.F11[0].F11[0].F06, *e.F11[0].F11[0].F06 |
| 313 |
if sF11 == nil { |
| 314 |
t.Errorf("f11.0.f11.0.f6: expected %v, got nil", vals(eF11)) |
| 315 |
} else { |
| 316 |
if len(sF11) != 2 || *sF11[0] != *eF11[0] || *sF11[1] != *eF11[1] { |
| 317 |
t.Errorf("f11.0.f11.0.f6: expected %v, got %v", vals(eF11), vals(sF11)) |
| 318 |
} |
| 319 |
} |
| 320 |
sF11, eF11 = *s.F11[0].F11[1].F06, *e.F11[0].F11[1].F06 |
| 321 |
if sF11 == nil { |
| 322 |
t.Errorf("f11.0.f11.0.f6: expected %v, got nil", vals(eF11)) |
| 323 |
} else { |
| 324 |
if len(sF11) != 2 || *sF11[0] != *eF11[0] || *sF11[1] != *eF11[1] { |
| 325 |
t.Errorf("f11.0.f11.0.f6: expected %v, got %v", vals(eF11), vals(sF11)) |
| 326 |
} |
| 327 |
} |
| 328 |
} |
| 329 |
} |
| 330 |
if s.F12 == nil { |
| 331 |
t.Errorf("f12: got nil") |
| 332 |
} else if len(*s.F12) != 1 { |
| 333 |
t.Errorf("f12: expected 1 element, got %v", *s.F12) |
| 334 |
} else { |
| 335 |
sF12, eF12 := *s.F12, *e.F12 |
| 336 |
if len(*sF12[0].F12) != 2 { |
| 337 |
t.Errorf("f12.0.f12: expected 1 element, got %v", *sF12[0].F12) |
| 338 |
} else { |
| 339 |
sF122, eF122 := *(*sF12[0].F12)[0].F06, *(*eF12[0].F12)[0].F06 |
| 340 |
if sF122 == nil { |
| 341 |
t.Errorf("f12.0.f12.0.f6: expected %v, got nil", vals(eF122)) |
| 342 |
} else { |
| 343 |
if len(sF122) != 2 || *sF122[0] != *eF122[0] || *sF122[1] != *eF122[1] { |
| 344 |
t.Errorf("f12.0.f12.0.f6: expected %v, got %v", vals(eF122), vals(sF122)) |
| 345 |
} |
| 346 |
} |
| 347 |
sF122, eF122 = *(*sF12[0].F12)[1].F06, *(*eF12[0].F12)[1].F06 |
| 348 |
if sF122 == nil { |
| 349 |
t.Errorf("f12.0.f12.0.f6: expected %v, got nil", vals(eF122)) |
| 350 |
} else { |
| 351 |
if len(sF122) != 2 || *sF122[0] != *eF122[0] || *sF122[1] != *eF122[1] { |
| 352 |
t.Errorf("f12.0.f12.0.f6: expected %v, got %v", vals(eF122), vals(sF122)) |
| 353 |
} |
| 354 |
} |
| 355 |
} |
| 356 |
} |
| 357 |
if s.F13 == nil { |
| 358 |
t.Errorf("f13: got nil") |
| 359 |
} else if len(*s.F13) != 1 { |
| 360 |
t.Errorf("f13: expected 1 element, got %v", *s.F13) |
| 361 |
} else { |
| 362 |
sF13, eF13 := *s.F13, *e.F13 |
| 363 |
if len(*sF13[0].F13) != 2 { |
| 364 |
t.Errorf("f13.0.f13: expected 1 element, got %v", *sF13[0].F13) |
| 365 |
} else { |
| 366 |
sF132, eF132 := *(*sF13[0].F13)[0].F06, *(*eF13[0].F13)[0].F06 |
| 367 |
if sF132 == nil { |
| 368 |
t.Errorf("f13.0.f13.0.f6: expected %v, got nil", vals(eF132)) |
| 369 |
} else { |
| 370 |
if len(sF132) != 2 || *sF132[0] != *eF132[0] || *sF132[1] != *eF132[1] { |
| 371 |
t.Errorf("f13.0.f13.0.f6: expected %v, got %v", vals(eF132), vals(sF132)) |
| 372 |
} |
| 373 |
} |
| 374 |
sF132, eF132 = *(*sF13[0].F13)[1].F06, *(*eF13[0].F13)[1].F06 |
| 375 |
if sF132 == nil { |
| 376 |
t.Errorf("f13.0.f13.0.f6: expected %v, got nil", vals(eF132)) |
| 377 |
} else { |
| 378 |
if len(sF132) != 2 || *sF132[0] != *eF132[0] || *sF132[1] != *eF132[1] { |
| 379 |
t.Errorf("f13.0.f13.0.f6: expected %v, got %v", vals(eF132), vals(sF132)) |
| 380 |
} |
| 381 |
} |
| 382 |
} |
| 383 |
} |
| 384 |
if s.F14 != e.F14 { |
| 385 |
t.Errorf("f14: expected %v, got %v", e.F14, s.F14) |
| 386 |
} |
| 387 |
if s.F15 != e.F15 { |
| 388 |
t.Errorf("f15: expected %v, got %v", e.F15, s.F15) |
| 389 |
} |
| 390 |
if s.F16 == nil { |
| 391 |
t.Errorf("f16: nil") |
| 392 |
} else if len(s.F16) != len(e.F16) { |
| 393 |
t.Errorf("f16: expected len %d, got %d", len(e.F16), len(s.F16)) |
| 394 |
} else if !reflect.DeepEqual(s.F16, e.F16) { |
| 395 |
t.Errorf("f16: expected %v, got %v", e.F16, s.F16) |
| 396 |
} |
| 397 |
if s.F17 != e.F17 { |
| 398 |
t.Errorf("f17: expected %v, got %v", e.F17, s.F17) |
| 399 |
} |
| 400 |
if s.F18 != e.F18 { |
| 401 |
t.Errorf("f18: expected %v, got %v", e.F18, s.F18) |
| 402 |
} |
| 403 |
if *s.F19 != *e.F19 { |
| 404 |
t.Errorf("f19: expected %v, got %v", *e.F19, *s.F19) |
| 405 |
} |
| 406 |
if s.F20 == nil { |
| 407 |
t.Errorf("f20: nil") |
| 408 |
} else if len(s.F20) != len(e.F20) { |
| 409 |
t.Errorf("f20: expected %v, got %v", e.F20, s.F20) |
| 410 |
} else if !reflect.DeepEqual(s.F20, e.F20) { |
| 411 |
t.Errorf("f20: expected %v, got %v", e.F20, s.F20) |
| 412 |
} |
| 413 |
if s.F21 == nil { |
| 414 |
t.Errorf("f21: nil") |
| 415 |
} else if len(s.F21) != len(e.F21) { |
| 416 |
t.Errorf("f21: expected length %d, got %d", len(e.F21), len(s.F21)) |
| 417 |
} else if !reflect.DeepEqual(s.F21, e.F21) { |
| 418 |
t.Errorf("f21: expected %v, got %v", e.F21, s.F21) |
| 419 |
} |
| 420 |
} |
| 421 |
|
| 422 |
func BenchmarkAll(b *testing.B) { |
| 423 |
v := map[string][]string{ |
| 424 |
"f1": {"1"}, |
| 425 |
"f2": {"2"}, |
| 426 |
"f3": {"31", "32"}, |
| 427 |
"f4": {"41", "42"}, |
| 428 |
"f5": {"51", "52"}, |
| 429 |
"f6": {"61", "62"}, |
| 430 |
"f7.f1": {"71", "72"}, |
| 431 |
"f8.f8.f7.f1": {"81", "82"}, |
| 432 |
"f9": {"9"}, |
| 433 |
"f10.0.f10.0.f6": {"101", "102"}, |
| 434 |
"f10.0.f10.1.f6": {"103", "104"}, |
| 435 |
"f11.0.f11.0.f6": {"111", "112"}, |
| 436 |
"f11.0.f11.1.f6": {"113", "114"}, |
| 437 |
"f12.0.f12.0.f6": {"121", "122"}, |
| 438 |
"f12.0.f12.1.f6": {"123", "124"}, |
| 439 |
"f13.0.f13.0.f6": {"131", "132"}, |
| 440 |
"f13.0.f13.1.f6": {"133", "134"}, |
| 441 |
} |
| 442 |
|
| 443 |
decoder := NewDecoder() |
| 444 |
for b.Loop() { |
| 445 |
_ = decoder.Decode(S1{}, v) |
| 446 |
} |
| 447 |
} |
| 448 |
|
| 449 |
// ---------------------------------------------------------------------------- |
| 450 |
|
| 451 |
type S3 struct { |
| 452 |
F01 bool |
| 453 |
F02 float32 |
| 454 |
F03 float64 |
| 455 |
F04 int |
| 456 |
F05 int8 |
| 457 |
F06 int16 |
| 458 |
F07 int32 |
| 459 |
F08 int64 |
| 460 |
F09 string |
| 461 |
F10 uint |
| 462 |
F11 uint8 |
| 463 |
F12 uint16 |
| 464 |
F13 uint32 |
| 465 |
F14 uint64 |
| 466 |
} |
| 467 |
|
| 468 |
func TestDefaultConverters(t *testing.T) { |
| 469 |
v := map[string][]string{ |
| 470 |
"F01": {"true"}, |
| 471 |
"F02": {"4.2"}, |
| 472 |
"F03": {"4.3"}, |
| 473 |
"F04": {"-42"}, |
| 474 |
"F05": {"-43"}, |
| 475 |
"F06": {"-44"}, |
| 476 |
"F07": {"-45"}, |
| 477 |
"F08": {"-46"}, |
| 478 |
"F09": {"foo"}, |
| 479 |
"F10": {"42"}, |
| 480 |
"F11": {"43"}, |
| 481 |
"F12": {"44"}, |
| 482 |
"F13": {"45"}, |
| 483 |
"F14": {"46"}, |
| 484 |
} |
| 485 |
e := S3{ |
| 486 |
F01: true, |
| 487 |
F02: 4.2, |
| 488 |
F03: 4.3, |
| 489 |
F04: -42, |
| 490 |
F05: -43, |
| 491 |
F06: -44, |
| 492 |
F07: -45, |
| 493 |
F08: -46, |
| 494 |
F09: "foo", |
| 495 |
F10: 42, |
| 496 |
F11: 43, |
| 497 |
F12: 44, |
| 498 |
F13: 45, |
| 499 |
F14: 46, |
| 500 |
} |
| 501 |
s := &S3{} |
| 502 |
_ = NewDecoder().Decode(s, v) |
| 503 |
if s.F01 != e.F01 { |
| 504 |
t.Errorf("F01: expected %v, got %v", e.F01, s.F01) |
| 505 |
} |
| 506 |
if s.F02 != e.F02 { |
| 507 |
t.Errorf("F02: expected %v, got %v", e.F02, s.F02) |
| 508 |
} |
| 509 |
if s.F03 != e.F03 { |
| 510 |
t.Errorf("F03: expected %v, got %v", e.F03, s.F03) |
| 511 |
} |
| 512 |
if s.F04 != e.F04 { |
| 513 |
t.Errorf("F04: expected %v, got %v", e.F04, s.F04) |
| 514 |
} |
| 515 |
if s.F05 != e.F05 { |
| 516 |
t.Errorf("F05: expected %v, got %v", e.F05, s.F05) |
| 517 |
} |
| 518 |
if s.F06 != e.F06 { |
| 519 |
t.Errorf("F06: expected %v, got %v", e.F06, s.F06) |
| 520 |
} |
| 521 |
if s.F07 != e.F07 { |
| 522 |
t.Errorf("F07: expected %v, got %v", e.F07, s.F07) |
| 523 |
} |
| 524 |
if s.F08 != e.F08 { |
| 525 |
t.Errorf("F08: expected %v, got %v", e.F08, s.F08) |
| 526 |
} |
| 527 |
if s.F09 != e.F09 { |
| 528 |
t.Errorf("F09: expected %v, got %v", e.F09, s.F09) |
| 529 |
} |
| 530 |
if s.F10 != e.F10 { |
| 531 |
t.Errorf("F10: expected %v, got %v", e.F10, s.F10) |
| 532 |
} |
| 533 |
if s.F11 != e.F11 { |
| 534 |
t.Errorf("F11: expected %v, got %v", e.F11, s.F11) |
| 535 |
} |
| 536 |
if s.F12 != e.F12 { |
| 537 |
t.Errorf("F12: expected %v, got %v", e.F12, s.F12) |
| 538 |
} |
| 539 |
if s.F13 != e.F13 { |
| 540 |
t.Errorf("F13: expected %v, got %v", e.F13, s.F13) |
| 541 |
} |
| 542 |
if s.F14 != e.F14 { |
| 543 |
t.Errorf("F14: expected %v, got %v", e.F14, s.F14) |
| 544 |
} |
| 545 |
} |
| 546 |
|
| 547 |
func TestOn(t *testing.T) { |
| 548 |
v := map[string][]string{ |
| 549 |
"F01": {"on"}, |
| 550 |
} |
| 551 |
s := S3{} |
| 552 |
err := NewDecoder().Decode(&s, v) |
| 553 |
if err != nil { |
| 554 |
t.Fatal(err) |
| 555 |
} |
| 556 |
if !s.F01 { |
| 557 |
t.Fatal("Value was not set to true") |
| 558 |
} |
| 559 |
} |
| 560 |
|
| 561 |
// ---------------------------------------------------------------------------- |
| 562 |
|
| 563 |
func TestInlineStruct(t *testing.T) { |
| 564 |
s1 := &struct { |
| 565 |
F01 bool |
| 566 |
}{} |
| 567 |
s2 := &struct { |
| 568 |
F01 int |
| 569 |
}{} |
| 570 |
v1 := map[string][]string{ |
| 571 |
"F01": {"true"}, |
| 572 |
} |
| 573 |
v2 := map[string][]string{ |
| 574 |
"F01": {"42"}, |
| 575 |
} |
| 576 |
decoder := NewDecoder() |
| 577 |
_ = decoder.Decode(s1, v1) |
| 578 |
if s1.F01 != true { |
| 579 |
t.Errorf("s1: expected %v, got %v", true, s1.F01) |
| 580 |
} |
| 581 |
_ = decoder.Decode(s2, v2) |
| 582 |
if s2.F01 != 42 { |
| 583 |
t.Errorf("s2: expected %v, got %v", 42, s2.F01) |
| 584 |
} |
| 585 |
} |
| 586 |
|
| 587 |
// ---------------------------------------------------------------------------- |
| 588 |
|
| 589 |
type Foo struct { |
| 590 |
F01 int |
| 591 |
F02 Bar |
| 592 |
Bif []Baz |
| 593 |
} |
| 594 |
|
| 595 |
type Bar struct { |
| 596 |
F01 string |
| 597 |
F02 string |
| 598 |
F03 string |
| 599 |
F14 string |
| 600 |
S05 string |
| 601 |
Str string |
| 602 |
} |
| 603 |
|
| 604 |
type Baz struct { |
| 605 |
F99 []string |
| 606 |
} |
| 607 |
|
| 608 |
func TestSimpleExample(t *testing.T) { |
| 609 |
data := map[string][]string{ |
| 610 |
"F01": {"1"}, |
| 611 |
"F02.F01": {"S1"}, |
| 612 |
"F02.F02": {"S2"}, |
| 613 |
"F02.F03": {"S3"}, |
| 614 |
"F02.F14": {"S4"}, |
| 615 |
"F02.S05": {"S5"}, |
| 616 |
"F02.Str": {"Str"}, |
| 617 |
"Bif.0.F99": {"A", "B", "C"}, |
| 618 |
} |
| 619 |
|
| 620 |
e := &Foo{ |
| 621 |
F01: 1, |
| 622 |
F02: Bar{ |
| 623 |
F01: "S1", |
| 624 |
F02: "S2", |
| 625 |
F03: "S3", |
| 626 |
F14: "S4", |
| 627 |
S05: "S5", |
| 628 |
Str: "Str", |
| 629 |
}, |
| 630 |
Bif: []Baz{ |
| 631 |
{ |
| 632 |
F99: []string{"A", "B", "C"}, |
| 633 |
}, |
| 634 |
}, |
| 635 |
} |
| 636 |
|
| 637 |
s := &Foo{} |
| 638 |
_ = NewDecoder().Decode(s, data) |
| 639 |
|
| 640 |
if s.F01 != e.F01 { |
| 641 |
t.Errorf("F01: expected %v, got %v", e.F01, s.F01) |
| 642 |
} |
| 643 |
if s.F02.F01 != e.F02.F01 { |
| 644 |
t.Errorf("F02.F01: expected %v, got %v", e.F02.F01, s.F02.F01) |
| 645 |
} |
| 646 |
if s.F02.F02 != e.F02.F02 { |
| 647 |
t.Errorf("F02.F02: expected %v, got %v", e.F02.F02, s.F02.F02) |
| 648 |
} |
| 649 |
if s.F02.F03 != e.F02.F03 { |
| 650 |
t.Errorf("F02.F03: expected %v, got %v", e.F02.F03, s.F02.F03) |
| 651 |
} |
| 652 |
if s.F02.F14 != e.F02.F14 { |
| 653 |
t.Errorf("F02.F14: expected %v, got %v", e.F02.F14, s.F02.F14) |
| 654 |
} |
| 655 |
if s.F02.S05 != e.F02.S05 { |
| 656 |
t.Errorf("F02.S05: expected %v, got %v", e.F02.S05, s.F02.S05) |
| 657 |
} |
| 658 |
if s.F02.Str != e.F02.Str { |
| 659 |
t.Errorf("F02.Str: expected %v, got %v", e.F02.Str, s.F02.Str) |
| 660 |
} |
| 661 |
if len(s.Bif) != len(e.Bif) { |
| 662 |
t.Errorf("Bif len: expected %d, got %d", len(e.Bif), len(s.Bif)) |
| 663 |
} else { |
| 664 |
if len(s.Bif[0].F99) != len(e.Bif[0].F99) { |
| 665 |
t.Errorf("Bif[0].F99 len: expected %d, got %d", len(e.Bif[0].F99), len(s.Bif[0].F99)) |
| 666 |
} |
| 667 |
} |
| 668 |
} |
| 669 |
|
| 670 |
// ---------------------------------------------------------------------------- |
| 671 |
|
| 672 |
type S4 struct { |
| 673 |
F01 int64 |
| 674 |
F02 float64 |
| 675 |
F03 bool |
| 676 |
F04 rudeBool |
| 677 |
} |
| 678 |
|
| 679 |
func TestConversionError(t *testing.T) { |
| 680 |
data := map[string][]string{ |
| 681 |
"F01": {"foo"}, |
| 682 |
"F02": {"bar"}, |
| 683 |
"F03": {"baz"}, |
| 684 |
"F04": {"not-a-yes-or-nope"}, |
| 685 |
} |
| 686 |
s := &S4{} |
| 687 |
e := NewDecoder().Decode(s, data) |
| 688 |
|
| 689 |
m := e.(MultiError) |
| 690 |
if len(m) != 4 { |
| 691 |
t.Errorf("Expected 3 errors, got %v", m) |
| 692 |
} |
| 693 |
} |
| 694 |
|
| 695 |
// ---------------------------------------------------------------------------- |
| 696 |
|
| 697 |
type S5 struct { |
| 698 |
F01 []string |
| 699 |
} |
| 700 |
|
| 701 |
func TestEmptyValue(t *testing.T) { |
| 702 |
data := map[string][]string{ |
| 703 |
"F01": {"", "foo"}, |
| 704 |
} |
| 705 |
s := &S5{} |
| 706 |
err := NewDecoder().Decode(s, data) |
| 707 |
if err != nil { |
| 708 |
t.Fatalf("Failed to decode: %v", err) |
| 709 |
} |
| 710 |
if len(s.F01) != 1 { |
| 711 |
t.Errorf("Expected 1 values in F01") |
| 712 |
} |
| 713 |
} |
| 714 |
|
| 715 |
func TestEmptyValueZeroEmpty(t *testing.T) { |
| 716 |
data := map[string][]string{ |
| 717 |
"F01": {"", "foo"}, |
| 718 |
} |
| 719 |
s := S5{} |
| 720 |
d := NewDecoder() |
| 721 |
d.ZeroEmpty(true) |
| 722 |
err := d.Decode(&s, data) |
| 723 |
if err != nil { |
| 724 |
t.Fatal(err) |
| 725 |
} |
| 726 |
if len(s.F01) != 2 { |
| 727 |
t.Errorf("Expected 1 values in F01") |
| 728 |
} |
| 729 |
} |
| 730 |
|
| 731 |
// ---------------------------------------------------------------------------- |
| 732 |
|
| 733 |
type S6 struct { |
| 734 |
id string |
| 735 |
} |
| 736 |
|
| 737 |
func TestUnexportedField(t *testing.T) { |
| 738 |
data := map[string][]string{ |
| 739 |
"id": {"identifier"}, |
| 740 |
} |
| 741 |
s := &S6{} |
| 742 |
err := NewDecoder().Decode(s, data) |
| 743 |
if err != nil { |
| 744 |
t.Fatalf("Failed to decode: %v", err) |
| 745 |
} |
| 746 |
if s.id != "" { |
| 747 |
t.Errorf("Unexported field expected to be ignored") |
| 748 |
} |
| 749 |
} |
| 750 |
|
| 751 |
// ---------------------------------------------------------------------------- |
| 752 |
|
| 753 |
type S7 struct { |
| 754 |
ID string |
| 755 |
} |
| 756 |
|
| 757 |
func TestMultipleValues(t *testing.T) { |
| 758 |
data := map[string][]string{ |
| 759 |
"ID": {"0", "1"}, |
| 760 |
} |
| 761 |
|
| 762 |
s := S7{} |
| 763 |
err := NewDecoder().Decode(&s, data) |
| 764 |
if err != nil { |
| 765 |
t.Fatalf("Failed to decode: %v", err) |
| 766 |
} |
| 767 |
if s.ID != "1" { |
| 768 |
t.Errorf("Last defined value must be used when multiple values for same field are provided") |
| 769 |
} |
| 770 |
} |
| 771 |
|
| 772 |
type S8 struct { |
| 773 |
ID string `json:"id"` |
| 774 |
} |
| 775 |
|
| 776 |
func TestSetAliasTag(t *testing.T) { |
| 777 |
data := map[string][]string{ |
| 778 |
"id": {"foo"}, |
| 779 |
} |
| 780 |
|
| 781 |
s := S8{} |
| 782 |
dec := NewDecoder() |
| 783 |
dec.SetAliasTag("json") |
| 784 |
err := dec.Decode(&s, data) |
| 785 |
if err != nil { |
| 786 |
t.Fatalf("Failed to decode: %v", err) |
| 787 |
} |
| 788 |
if s.ID != "foo" { |
| 789 |
t.Fatalf("Bad value: got %q, want %q", s.ID, "foo") |
| 790 |
} |
| 791 |
} |
| 792 |
|
| 793 |
func TestSetAliasTagAfterCacheWarm(t *testing.T) { |
| 794 |
type aliased struct { |
| 795 |
ID string `schema:"schema_id" json:"json_id"` |
| 796 |
} |
| 797 |
|
| 798 |
dec := NewDecoder() |
| 799 |
|
| 800 |
var schemaTagged aliased |
| 801 |
err := dec.Decode(&schemaTagged, map[string][]string{ |
| 802 |
"schema_id": {"schema"}, |
| 803 |
}) |
| 804 |
if err != nil { |
| 805 |
t.Fatalf("Failed to decode schema tag: %v", err) |
| 806 |
} |
| 807 |
|
| 808 |
dec.SetAliasTag("json") |
| 809 |
|
| 810 |
var jsonTagged aliased |
| 811 |
err = dec.Decode(&jsonTagged, map[string][]string{ |
| 812 |
"json_id": {"json"}, |
| 813 |
}) |
| 814 |
if err != nil { |
| 815 |
t.Fatalf("Failed to decode json tag after alias change: %v", err) |
| 816 |
} |
| 817 |
if jsonTagged.ID != "json" { |
| 818 |
t.Fatalf("Bad value after alias change: got %q, want %q", jsonTagged.ID, "json") |
| 819 |
} |
| 820 |
} |
| 821 |
|
| 822 |
func TestZeroEmpty(t *testing.T) { |
| 823 |
data := map[string][]string{ |
| 824 |
"F01": {""}, |
| 825 |
"F03": {"true"}, |
| 826 |
} |
| 827 |
s := S4{1, 1, false, false} |
| 828 |
d := NewDecoder() |
| 829 |
d.ZeroEmpty(true) |
| 830 |
|
| 831 |
err := d.Decode(&s, data) |
| 832 |
if err != nil { |
| 833 |
t.Fatal(err) |
| 834 |
} |
| 835 |
if s.F01 != 0 { |
| 836 |
t.Errorf("F01: got %v, want %v", s.F01, 0) |
| 837 |
} |
| 838 |
if s.F02 != 1 { |
| 839 |
t.Errorf("F02: got %v, want %v", s.F02, 1) |
| 840 |
} |
| 841 |
if s.F03 != true { |
| 842 |
t.Errorf("F03: got %v, want %v", s.F03, true) |
| 843 |
} |
| 844 |
} |
| 845 |
|
| 846 |
func TestNoZeroEmpty(t *testing.T) { |
| 847 |
data := map[string][]string{ |
| 848 |
"F01": {""}, |
| 849 |
"F03": {"true"}, |
| 850 |
} |
| 851 |
s := S4{1, 1, false, false} |
| 852 |
d := NewDecoder() |
| 853 |
d.ZeroEmpty(false) |
| 854 |
err := d.Decode(&s, data) |
| 855 |
if err != nil { |
| 856 |
t.Fatal(err) |
| 857 |
} |
| 858 |
if s.F01 != 1 { |
| 859 |
t.Errorf("F01: got %v, want %v", s.F01, 1) |
| 860 |
} |
| 861 |
if s.F02 != 1 { |
| 862 |
t.Errorf("F02: got %v, want %v", s.F02, 1) |
| 863 |
} |
| 864 |
if s.F03 != true { |
| 865 |
t.Errorf("F03: got %v, want %v", s.F03, true) |
| 866 |
} |
| 867 |
if s.F04 != false { |
| 868 |
t.Errorf("F04: got %v, want %v", s.F04, false) |
| 869 |
} |
| 870 |
} |
| 871 |
|
| 872 |
// ---------------------------------------------------------------------------- |
| 873 |
|
| 874 |
type S9 struct { |
| 875 |
Id string |
| 876 |
} |
| 877 |
|
| 878 |
type S10 struct { |
| 879 |
S9 |
| 880 |
} |
| 881 |
|
| 882 |
func TestEmbeddedField(t *testing.T) { |
| 883 |
data := map[string][]string{ |
| 884 |
"Id": {"identifier"}, |
| 885 |
} |
| 886 |
s := &S10{} |
| 887 |
err := NewDecoder().Decode(s, data) |
| 888 |
if err != nil { |
| 889 |
t.Fatalf("Failed to decode: %v", err) |
| 890 |
} |
| 891 |
if s.Id != "identifier" { |
| 892 |
t.Errorf("Missing support for embedded fields") |
| 893 |
} |
| 894 |
} |
| 895 |
|
| 896 |
type S11 struct { |
| 897 |
S10 |
| 898 |
} |
| 899 |
|
| 900 |
func TestMultipleLevelEmbeddedField(t *testing.T) { |
| 901 |
data := map[string][]string{ |
| 902 |
"Id": {"identifier"}, |
| 903 |
} |
| 904 |
s := &S11{} |
| 905 |
err := NewDecoder().Decode(s, data) |
| 906 |
if s.Id != "identifier" { |
| 907 |
t.Errorf("Missing support for multiple-level embedded fields (%v)", err) |
| 908 |
} |
| 909 |
} |
| 910 |
|
| 911 |
func TestInvalidPath(t *testing.T) { |
| 912 |
data := map[string][]string{ |
| 913 |
"Foo.Bar": {"baz"}, |
| 914 |
} |
| 915 |
s := S9{} |
| 916 |
err := NewDecoder().Decode(&s, data) |
| 917 |
expectedErr := `schema: invalid path "Foo.Bar"` |
| 918 |
if err.Error() != expectedErr { |
| 919 |
t.Fatalf("got %q, want %q", err, expectedErr) |
| 920 |
} |
| 921 |
} |
| 922 |
|
| 923 |
func TestInvalidPathIgnoreUnknownKeys(t *testing.T) { |
| 924 |
data := map[string][]string{ |
| 925 |
"Foo.Bar": {"baz"}, |
| 926 |
} |
| 927 |
s := S9{} |
| 928 |
dec := NewDecoder() |
| 929 |
dec.IgnoreUnknownKeys(true) |
| 930 |
err := dec.Decode(&s, data) |
| 931 |
if err != nil { |
| 932 |
t.Fatal(err) |
| 933 |
} |
| 934 |
} |
| 935 |
|
| 936 |
// ---------------------------------------------------------------------------- |
| 937 |
|
| 938 |
type S1NT struct { |
| 939 |
F1 int |
| 940 |
F2 *int |
| 941 |
F3 []int |
| 942 |
F4 []*int |
| 943 |
F5 *[]int |
| 944 |
F6 *[]*int |
| 945 |
F7 S2 |
| 946 |
F8 *S1 |
| 947 |
F9 int `schema:"-"` |
| 948 |
F10 []S1 |
| 949 |
F11 []*S1 |
| 950 |
F12 *[]S1 |
| 951 |
F13 *[]*S1 |
| 952 |
} |
| 953 |
|
| 954 |
func TestAllNT(t *testing.T) { |
| 955 |
v := map[string][]string{ |
| 956 |
"f1": {"1"}, |
| 957 |
"f2": {"2"}, |
| 958 |
"f3": {"31", "32"}, |
| 959 |
"f4": {"41", "42"}, |
| 960 |
"f5": {"51", "52"}, |
| 961 |
"f6": {"61", "62"}, |
| 962 |
"f7.f1": {"71", "72"}, |
| 963 |
"f8.f8.f7.f1": {"81", "82"}, |
| 964 |
"f9": {"9"}, |
| 965 |
"f10.0.f10.0.f6": {"101", "102"}, |
| 966 |
"f10.0.f10.1.f6": {"103", "104"}, |
| 967 |
"f11.0.f11.0.f6": {"111", "112"}, |
| 968 |
"f11.0.f11.1.f6": {"113", "114"}, |
| 969 |
"f12.0.f12.0.f6": {"121", "122"}, |
| 970 |
"f12.0.f12.1.f6": {"123", "124"}, |
| 971 |
"f13.0.f13.0.f6": {"131", "132"}, |
| 972 |
"f13.0.f13.1.f6": {"133", "134"}, |
| 973 |
} |
| 974 |
f2 := 2 |
| 975 |
f41, f42 := 41, 42 |
| 976 |
f61, f62 := 61, 62 |
| 977 |
f71, f72 := 71, 72 |
| 978 |
f81, f82 := 81, 82 |
| 979 |
f101, f102, f103, f104 := 101, 102, 103, 104 |
| 980 |
f111, f112, f113, f114 := 111, 112, 113, 114 |
| 981 |
f121, f122, f123, f124 := 121, 122, 123, 124 |
| 982 |
f131, f132, f133, f134 := 131, 132, 133, 134 |
| 983 |
e := S1NT{ |
| 984 |
F1: 1, |
| 985 |
F2: &f2, |
| 986 |
F3: []int{31, 32}, |
| 987 |
F4: []*int{&f41, &f42}, |
| 988 |
F5: &[]int{51, 52}, |
| 989 |
F6: &[]*int{&f61, &f62}, |
| 990 |
F7: S2{ |
| 991 |
F01: &[]*int{&f71, &f72}, |
| 992 |
}, |
| 993 |
F8: &S1{ |
| 994 |
F08: &S1{ |
| 995 |
F07: S2{ |
| 996 |
F01: &[]*int{&f81, &f82}, |
| 997 |
}, |
| 998 |
}, |
| 999 |
}, |
| 1000 |
F9: 0, |
| 1001 |
F10: []S1{ |
| 1002 |
{ |
| 1003 |
F10: []S1{ |
| 1004 |
{F06: &[]*int{&f101, &f102}}, |
| 1005 |
{F06: &[]*int{&f103, &f104}}, |
| 1006 |
}, |
| 1007 |
}, |
| 1008 |
}, |
| 1009 |
F11: []*S1{ |
| 1010 |
{ |
| 1011 |
F11: []*S1{ |
| 1012 |
{F06: &[]*int{&f111, &f112}}, |
| 1013 |
{F06: &[]*int{&f113, &f114}}, |
| 1014 |
}, |
| 1015 |
}, |
| 1016 |
}, |
| 1017 |
F12: &[]S1{ |
| 1018 |
{ |
| 1019 |
F12: &[]S1{ |
| 1020 |
{F06: &[]*int{&f121, &f122}}, |
| 1021 |
{F06: &[]*int{&f123, &f124}}, |
| 1022 |
}, |
| 1023 |
}, |
| 1024 |
}, |
| 1025 |
F13: &[]*S1{ |
| 1026 |
{ |
| 1027 |
F13: &[]*S1{ |
| 1028 |
{F06: &[]*int{&f131, &f132}}, |
| 1029 |
{F06: &[]*int{&f133, &f134}}, |
| 1030 |
}, |
| 1031 |
}, |
| 1032 |
}, |
| 1033 |
} |
| 1034 |
|
| 1035 |
s := &S1NT{} |
| 1036 |
_ = NewDecoder().Decode(s, v) |
| 1037 |
|
| 1038 |
vals := func(values []*int) []int { |
| 1039 |
r := make([]int, len(values)) |
| 1040 |
for k, v := range values { |
| 1041 |
r[k] = *v |
| 1042 |
} |
| 1043 |
return r |
| 1044 |
} |
| 1045 |
|
| 1046 |
if s.F1 != e.F1 { |
| 1047 |
t.Errorf("f1: expected %v, got %v", e.F1, s.F1) |
| 1048 |
} |
| 1049 |
if s.F2 == nil { |
| 1050 |
t.Errorf("f2: expected %v, got nil", *e.F2) |
| 1051 |
} else if *s.F2 != *e.F2 { |
| 1052 |
t.Errorf("f2: expected %v, got %v", *e.F2, *s.F2) |
| 1053 |
} |
| 1054 |
if s.F3 == nil { |
| 1055 |
t.Errorf("f3: expected %v, got nil", e.F3) |
| 1056 |
} else if len(s.F3) != 2 || s.F3[0] != e.F3[0] || s.F3[1] != e.F3[1] { |
| 1057 |
t.Errorf("f3: expected %v, got %v", e.F3, s.F3) |
| 1058 |
} |
| 1059 |
if s.F4 == nil { |
| 1060 |
t.Errorf("f4: expected %v, got nil", e.F4) |
| 1061 |
} else { |
| 1062 |
if len(s.F4) != 2 || *s.F4[0] != *e.F4[0] || *s.F4[1] != *e.F4[1] { |
| 1063 |
t.Errorf("f4: expected %v, got %v", vals(e.F4), vals(s.F4)) |
| 1064 |
} |
| 1065 |
} |
| 1066 |
if s.F5 == nil { |
| 1067 |
t.Errorf("f5: expected %v, got nil", e.F5) |
| 1068 |
} else { |
| 1069 |
sF5, eF5 := *s.F5, *e.F5 |
| 1070 |
if len(sF5) != 2 || sF5[0] != eF5[0] || sF5[1] != eF5[1] { |
| 1071 |
t.Errorf("f5: expected %v, got %v", eF5, sF5) |
| 1072 |
} |
| 1073 |
} |
| 1074 |
if s.F6 == nil { |
| 1075 |
t.Errorf("f6: expected %v, got nil", vals(*e.F6)) |
| 1076 |
} else { |
| 1077 |
sF6, eF6 := *s.F6, *e.F6 |
| 1078 |
if len(sF6) != 2 || *sF6[0] != *eF6[0] || *sF6[1] != *eF6[1] { |
| 1079 |
t.Errorf("f6: expected %v, got %v", vals(eF6), vals(sF6)) |
| 1080 |
} |
| 1081 |
} |
| 1082 |
if s.F7.F01 == nil { |
| 1083 |
t.Errorf("f7.f1: expected %v, got nil", vals(*e.F7.F01)) |
| 1084 |
} else { |
| 1085 |
sF7, eF7 := *s.F7.F01, *e.F7.F01 |
| 1086 |
if len(sF7) != 2 || *sF7[0] != *eF7[0] || *sF7[1] != *eF7[1] { |
| 1087 |
t.Errorf("f7.f1: expected %v, got %v", vals(eF7), vals(sF7)) |
| 1088 |
} |
| 1089 |
} |
| 1090 |
if s.F8 == nil { |
| 1091 |
t.Errorf("f8: got nil") |
| 1092 |
} else if s.F8.F08 == nil { |
| 1093 |
t.Errorf("f8.f8: got nil") |
| 1094 |
} else if s.F8.F08.F07.F01 == nil { |
| 1095 |
t.Errorf("f8.f8.f7.f1: expected %v, got nil", vals(*e.F8.F08.F07.F01)) |
| 1096 |
} else { |
| 1097 |
sF8, eF8 := *s.F8.F08.F07.F01, *e.F8.F08.F07.F01 |
| 1098 |
if len(sF8) != 2 || *sF8[0] != *eF8[0] || *sF8[1] != *eF8[1] { |
| 1099 |
t.Errorf("f8.f8.f7.f1: expected %v, got %v", vals(eF8), vals(sF8)) |
| 1100 |
} |
| 1101 |
} |
| 1102 |
if s.F9 != e.F9 { |
| 1103 |
t.Errorf("f9: expected %v, got %v", e.F9, s.F9) |
| 1104 |
} |
| 1105 |
if s.F10 == nil { |
| 1106 |
t.Errorf("f10: got nil") |
| 1107 |
} else if len(s.F10) != 1 { |
| 1108 |
t.Errorf("f10: expected 1 element, got %v", s.F10) |
| 1109 |
} else { |
| 1110 |
if len(s.F10[0].F10) != 2 { |
| 1111 |
t.Errorf("f10.0.f10: expected 1 element, got %v", s.F10[0].F10) |
| 1112 |
} else { |
| 1113 |
sF10, eF10 := *s.F10[0].F10[0].F06, *e.F10[0].F10[0].F06 |
| 1114 |
if sF10 == nil { |
| 1115 |
t.Errorf("f10.0.f10.0.f6: expected %v, got nil", vals(eF10)) |
| 1116 |
} else { |
| 1117 |
if len(sF10) != 2 || *sF10[0] != *eF10[0] || *sF10[1] != *eF10[1] { |
| 1118 |
t.Errorf("f10.0.f10.0.f6: expected %v, got %v", vals(eF10), vals(sF10)) |
| 1119 |
} |
| 1120 |
} |
| 1121 |
sF10, eF10 = *s.F10[0].F10[1].F06, *e.F10[0].F10[1].F06 |
| 1122 |
if sF10 == nil { |
| 1123 |
t.Errorf("f10.0.f10.0.f6: expected %v, got nil", vals(eF10)) |
| 1124 |
} else { |
| 1125 |
if len(sF10) != 2 || *sF10[0] != *eF10[0] || *sF10[1] != *eF10[1] { |
| 1126 |
t.Errorf("f10.0.f10.0.f6: expected %v, got %v", vals(eF10), vals(sF10)) |
| 1127 |
} |
| 1128 |
} |
| 1129 |
} |
| 1130 |
} |
| 1131 |
if s.F11 == nil { |
| 1132 |
t.Errorf("f11: got nil") |
| 1133 |
} else if len(s.F11) != 1 { |
| 1134 |
t.Errorf("f11: expected 1 element, got %v", s.F11) |
| 1135 |
} else { |
| 1136 |
if len(s.F11[0].F11) != 2 { |
| 1137 |
t.Errorf("f11.0.f11: expected 1 element, got %v", s.F11[0].F11) |
| 1138 |
} else { |
| 1139 |
sF11, eF11 := *s.F11[0].F11[0].F06, *e.F11[0].F11[0].F06 |
| 1140 |
if sF11 == nil { |
| 1141 |
t.Errorf("f11.0.f11.0.f6: expected %v, got nil", vals(eF11)) |
| 1142 |
} else { |
| 1143 |
if len(sF11) != 2 || *sF11[0] != *eF11[0] || *sF11[1] != *eF11[1] { |
| 1144 |
t.Errorf("f11.0.f11.0.f6: expected %v, got %v", vals(eF11), vals(sF11)) |
| 1145 |
} |
| 1146 |
} |
| 1147 |
sF11, eF11 = *s.F11[0].F11[1].F06, *e.F11[0].F11[1].F06 |
| 1148 |
if sF11 == nil { |
| 1149 |
t.Errorf("f11.0.f11.0.f6: expected %v, got nil", vals(eF11)) |
| 1150 |
} else { |
| 1151 |
if len(sF11) != 2 || *sF11[0] != *eF11[0] || *sF11[1] != *eF11[1] { |
| 1152 |
t.Errorf("f11.0.f11.0.f6: expected %v, got %v", vals(eF11), vals(sF11)) |
| 1153 |
} |
| 1154 |
} |
| 1155 |
} |
| 1156 |
} |
| 1157 |
if s.F12 == nil { |
| 1158 |
t.Errorf("f12: got nil") |
| 1159 |
} else if len(*s.F12) != 1 { |
| 1160 |
t.Errorf("f12: expected 1 element, got %v", *s.F12) |
| 1161 |
} else { |
| 1162 |
sF12, eF12 := *s.F12, *e.F12 |
| 1163 |
if len(*sF12[0].F12) != 2 { |
| 1164 |
t.Errorf("f12.0.f12: expected 1 element, got %v", *sF12[0].F12) |
| 1165 |
} else { |
| 1166 |
sF122, eF122 := *(*sF12[0].F12)[0].F06, *(*eF12[0].F12)[0].F06 |
| 1167 |
if sF122 == nil { |
| 1168 |
t.Errorf("f12.0.f12.0.f6: expected %v, got nil", vals(eF122)) |
| 1169 |
} else { |
| 1170 |
if len(sF122) != 2 || *sF122[0] != *eF122[0] || *sF122[1] != *eF122[1] { |
| 1171 |
t.Errorf("f12.0.f12.0.f6: expected %v, got %v", vals(eF122), vals(sF122)) |
| 1172 |
} |
| 1173 |
} |
| 1174 |
sF122, eF122 = *(*sF12[0].F12)[1].F06, *(*eF12[0].F12)[1].F06 |
| 1175 |
if sF122 == nil { |
| 1176 |
t.Errorf("f12.0.f12.0.f6: expected %v, got nil", vals(eF122)) |
| 1177 |
} else { |
| 1178 |
if len(sF122) != 2 || *sF122[0] != *eF122[0] || *sF122[1] != *eF122[1] { |
| 1179 |
t.Errorf("f12.0.f12.0.f6: expected %v, got %v", vals(eF122), vals(sF122)) |
| 1180 |
} |
| 1181 |
} |
| 1182 |
} |
| 1183 |
} |
| 1184 |
if s.F13 == nil { |
| 1185 |
t.Errorf("f13: got nil") |
| 1186 |
} else if len(*s.F13) != 1 { |
| 1187 |
t.Errorf("f13: expected 1 element, got %v", *s.F13) |
| 1188 |
} else { |
| 1189 |
sF13, eF13 := *s.F13, *e.F13 |
| 1190 |
if len(*sF13[0].F13) != 2 { |
| 1191 |
t.Errorf("f13.0.f13: expected 1 element, got %v", *sF13[0].F13) |
| 1192 |
} else { |
| 1193 |
sF132, eF132 := *(*sF13[0].F13)[0].F06, *(*eF13[0].F13)[0].F06 |
| 1194 |
if sF132 == nil { |
| 1195 |
t.Errorf("f13.0.f13.0.f6: expected %v, got nil", vals(eF132)) |
| 1196 |
} else { |
| 1197 |
if len(sF132) != 2 || *sF132[0] != *eF132[0] || *sF132[1] != *eF132[1] { |
| 1198 |
t.Errorf("f13.0.f13.0.f6: expected %v, got %v", vals(eF132), vals(sF132)) |
| 1199 |
} |
| 1200 |
} |
| 1201 |
sF132, eF132 = *(*sF13[0].F13)[1].F06, *(*eF13[0].F13)[1].F06 |
| 1202 |
if sF132 == nil { |
| 1203 |
t.Errorf("f13.0.f13.0.f6: expected %v, got nil", vals(eF132)) |
| 1204 |
} else { |
| 1205 |
if len(sF132) != 2 || *sF132[0] != *eF132[0] || *sF132[1] != *eF132[1] { |
| 1206 |
t.Errorf("f13.0.f13.0.f6: expected %v, got %v", vals(eF132), vals(sF132)) |
| 1207 |
} |
| 1208 |
} |
| 1209 |
} |
| 1210 |
} |
| 1211 |
} |
| 1212 |
|
| 1213 |
// ---------------------------------------------------------------------------- |
| 1214 |
|
| 1215 |
type S12A struct { |
| 1216 |
ID []int |
| 1217 |
} |
| 1218 |
|
| 1219 |
func TestCSVSlice(t *testing.T) { |
| 1220 |
data := map[string][]string{ |
| 1221 |
"ID": {"0,1"}, |
| 1222 |
} |
| 1223 |
|
| 1224 |
s := S12A{} |
| 1225 |
err := NewDecoder().Decode(&s, data) |
| 1226 |
if err != nil { |
| 1227 |
t.Fatalf("Failed to decode: %v", err) |
| 1228 |
} |
| 1229 |
if len(s.ID) != 2 { |
| 1230 |
t.Errorf("Expected two values in the result list, got %+v", s.ID) |
| 1231 |
} |
| 1232 |
if s.ID[0] != 0 || s.ID[1] != 1 { |
| 1233 |
t.Errorf("Expected []{0, 1} got %+v", s) |
| 1234 |
} |
| 1235 |
} |
| 1236 |
|
| 1237 |
type S12B struct { |
| 1238 |
ID []string |
| 1239 |
} |
| 1240 |
|
| 1241 |
// Decode should not split on , into a slice for string only |
| 1242 |
func TestCSVStringSlice(t *testing.T) { |
| 1243 |
data := map[string][]string{ |
| 1244 |
"ID": {"0,1"}, |
| 1245 |
} |
| 1246 |
|
| 1247 |
s := S12B{} |
| 1248 |
err := NewDecoder().Decode(&s, data) |
| 1249 |
if err != nil { |
| 1250 |
t.Fatalf("Failed to decode: %v", err) |
| 1251 |
} |
| 1252 |
if len(s.ID) != 1 { |
| 1253 |
t.Errorf("Expected one value in the result list, got %+v", s.ID) |
| 1254 |
} |
| 1255 |
if s.ID[0] != "0,1" { |
| 1256 |
t.Errorf("Expected []{0, 1} got %+v", s) |
| 1257 |
} |
| 1258 |
} |
| 1259 |
|
| 1260 |
// Invalid data provided by client should not panic (github issue 33) |
| 1261 |
func TestInvalidDataProvidedByClient(t *testing.T) { |
| 1262 |
defer func() { |
| 1263 |
if r := recover(); r != nil { |
| 1264 |
t.Errorf("Panicked calling decoder.Decode: %v", r) |
| 1265 |
} |
| 1266 |
}() |
| 1267 |
|
| 1268 |
type S struct { |
| 1269 |
f string // nolint:unused |
| 1270 |
} |
| 1271 |
|
| 1272 |
data := map[string][]string{ |
| 1273 |
"f.f": {"v"}, |
| 1274 |
} |
| 1275 |
|
| 1276 |
err := NewDecoder().Decode(new(S), data) |
| 1277 |
if err == nil { |
| 1278 |
t.Errorf("invalid path in decoder.Decode should return an error.") |
| 1279 |
} |
| 1280 |
} |
| 1281 |
|
| 1282 |
// underlying cause of error in issue 33 |
| 1283 |
func TestInvalidPathInCacheParsePath(t *testing.T) { |
| 1284 |
type S struct { |
| 1285 |
f string // nolint:unused |
| 1286 |
} |
| 1287 |
|
| 1288 |
typ := reflect.ValueOf(new(S)).Elem().Type() |
| 1289 |
c := newCache() |
| 1290 |
_, err := c.parsePath("f.f", typ) |
| 1291 |
if err == nil { |
| 1292 |
t.Errorf("invalid path in cache.parsePath should return an error.") |
| 1293 |
} |
| 1294 |
} |
| 1295 |
|
| 1296 |
func TestCacheParsePathInvalidPathCases(t *testing.T) { |
| 1297 |
t.Parallel() |
| 1298 |
|
| 1299 |
type item struct { |
| 1300 |
Value string `schema:"value"` |
| 1301 |
} |
| 1302 |
type payload struct { |
| 1303 |
N1 []item `schema:"n1"` |
| 1304 |
Name string `schema:"name"` |
| 1305 |
} |
| 1306 |
|
| 1307 |
c := newCache() |
| 1308 |
payloadType := reflect.TypeOf(payload{}) |
| 1309 |
|
| 1310 |
tests := []struct { |
| 1311 |
name string |
| 1312 |
path string |
| 1313 |
typ reflect.Type |
| 1314 |
}{ |
| 1315 |
{ |
| 1316 |
name: "non struct type", |
| 1317 |
path: "name", |
| 1318 |
typ: reflect.TypeOf(0), |
| 1319 |
}, |
| 1320 |
{ |
| 1321 |
name: "unknown field", |
| 1322 |
path: "missing", |
| 1323 |
typ: payloadType, |
| 1324 |
}, |
| 1325 |
{ |
| 1326 |
name: "empty index segment", |
| 1327 |
path: "n1..value", |
| 1328 |
typ: payloadType, |
| 1329 |
}, |
| 1330 |
{ |
| 1331 |
name: "invalid index segment", |
| 1332 |
path: "n1.x.value", |
| 1333 |
typ: payloadType, |
| 1334 |
}, |
| 1335 |
{ |
| 1336 |
name: "trailing dot after index", |
| 1337 |
path: "n1.0.", |
| 1338 |
typ: payloadType, |
| 1339 |
}, |
| 1340 |
} |
| 1341 |
|
| 1342 |
for _, tt := range tests { |
| 1343 |
t.Run(tt.name, func(t *testing.T) { |
| 1344 |
t.Parallel() |
| 1345 |
|
| 1346 |
_, err := c.parsePath(tt.path, tt.typ) |
| 1347 |
if !errors.Is(err, errInvalidPath) { |
| 1348 |
t.Fatalf("expected errInvalidPath for %q, got: %v", tt.path, err) |
| 1349 |
} |
| 1350 |
}) |
| 1351 |
} |
| 1352 |
} |
| 1353 |
|
| 1354 |
// issue 32 |
| 1355 |
func TestDecodeToTypedField(t *testing.T) { |
| 1356 |
type Aa bool |
| 1357 |
s1 := &struct{ Aa }{} |
| 1358 |
v1 := map[string][]string{"Aa": {"true"}} |
| 1359 |
err := NewDecoder().Decode(s1, v1) |
| 1360 |
if err != nil { |
| 1361 |
t.Fatalf("Failed to decode: %v", err) |
| 1362 |
} |
| 1363 |
if s1.Aa != Aa(true) { |
| 1364 |
t.Errorf("s1: expected %v, got %v", true, s1.Aa) |
| 1365 |
} |
| 1366 |
} |
| 1367 |
|
| 1368 |
// issue 37 |
| 1369 |
func TestRegisterConverter(t *testing.T) { |
| 1370 |
type Aa int |
| 1371 |
type Bb int |
| 1372 |
s1 := &struct { |
| 1373 |
Aa |
| 1374 |
Bb |
| 1375 |
}{} |
| 1376 |
decoder := NewDecoder() |
| 1377 |
|
| 1378 |
decoder.RegisterConverter(s1.Aa, func(s string) reflect.Value { return reflect.ValueOf(1) }) |
| 1379 |
decoder.RegisterConverter(s1.Bb, func(s string) reflect.Value { return reflect.ValueOf(2) }) |
| 1380 |
|
| 1381 |
v1 := map[string][]string{"Aa": {"4"}, "Bb": {"5"}} |
| 1382 |
err := decoder.Decode(s1, v1) |
| 1383 |
if err != nil { |
| 1384 |
t.Fatalf("Failed to decode: %v", err) |
| 1385 |
} |
| 1386 |
|
| 1387 |
if s1.Aa != Aa(1) { |
| 1388 |
t.Errorf("s1.Aa: expected %v, got %v", 1, s1.Aa) |
| 1389 |
} |
| 1390 |
if s1.Bb != Bb(2) { |
| 1391 |
t.Errorf("s1.Bb: expected %v, got %v", 2, s1.Bb) |
| 1392 |
} |
| 1393 |
} |
| 1394 |
|
| 1395 |
func TestRegisterConverterAfterCacheWarm(t *testing.T) { |
| 1396 |
type custom int |
| 1397 |
type payload struct { |
| 1398 |
Value custom `schema:"value"` |
| 1399 |
} |
| 1400 |
|
| 1401 |
decoder := NewDecoder() |
| 1402 |
|
| 1403 |
var warmed payload |
| 1404 |
err := decoder.Decode(&warmed, map[string][]string{}) |
| 1405 |
if err != nil { |
| 1406 |
t.Fatalf("Failed to warm decoder cache: %v", err) |
| 1407 |
} |
| 1408 |
|
| 1409 |
decoder.RegisterConverter(custom(0), func(s string) reflect.Value { |
| 1410 |
return reflect.ValueOf(custom(42)) |
| 1411 |
}) |
| 1412 |
|
| 1413 |
var result payload |
| 1414 |
err = decoder.Decode(&result, map[string][]string{ |
| 1415 |
"value": {"ignored"}, |
| 1416 |
}) |
| 1417 |
if err != nil { |
| 1418 |
t.Fatalf("Failed to decode with registered converter after cache warm: %v", err) |
| 1419 |
} |
| 1420 |
if result.Value != custom(42) { |
| 1421 |
t.Fatalf("Bad value: got %v, want %v", result.Value, custom(42)) |
| 1422 |
} |
| 1423 |
} |
| 1424 |
|
| 1425 |
// Issue #40 |
| 1426 |
func TestRegisterConverterSlice(t *testing.T) { |
| 1427 |
decoder := NewDecoder() |
| 1428 |
decoder.RegisterConverter([]string{}, func(input string) reflect.Value { |
| 1429 |
return reflect.ValueOf(strings.Split(input, ",")) |
| 1430 |
}) |
| 1431 |
|
| 1432 |
result := struct { |
| 1433 |
Multiple []string `schema:"multiple"` |
| 1434 |
}{} |
| 1435 |
|
| 1436 |
expected := []string{"one", "two", "three"} |
| 1437 |
err := decoder.Decode(&result, map[string][]string{ |
| 1438 |
"multiple": {"one,two,three"}, |
| 1439 |
}) |
| 1440 |
if err != nil { |
| 1441 |
t.Fatalf("Failed to decode: %v", err) |
| 1442 |
} |
| 1443 |
for i := range expected { |
| 1444 |
if got, want := expected[i], result.Multiple[i]; got != want { |
| 1445 |
t.Errorf("%d: got %s, want %s", i, got, want) |
| 1446 |
} |
| 1447 |
} |
| 1448 |
} |
| 1449 |
|
| 1450 |
func TestRegisterConverterMap(t *testing.T) { |
| 1451 |
decoder := NewDecoder() |
| 1452 |
decoder.IgnoreUnknownKeys(false) |
| 1453 |
decoder.RegisterConverter(map[string]string{}, func(input string) reflect.Value { |
| 1454 |
m := make(map[string]string) |
| 1455 |
for _, pair := range strings.Split(input, ",") { |
| 1456 |
parts := strings.Split(pair, ":") |
| 1457 |
switch len(parts) { |
| 1458 |
case 2: |
| 1459 |
m[parts[0]] = parts[1] |
| 1460 |
} |
| 1461 |
} |
| 1462 |
return reflect.ValueOf(m) |
| 1463 |
}) |
| 1464 |
|
| 1465 |
result := struct { |
| 1466 |
Multiple map[string]string `schema:"multiple"` |
| 1467 |
}{} |
| 1468 |
|
| 1469 |
err := decoder.Decode(&result, map[string][]string{ |
| 1470 |
"multiple": {"a:one,b:two"}, |
| 1471 |
}) |
| 1472 |
if err != nil { |
| 1473 |
t.Fatal(err) |
| 1474 |
} |
| 1475 |
expected := map[string]string{"a": "one", "b": "two"} |
| 1476 |
for k, v := range expected { |
| 1477 |
got, ok := result.Multiple[k] |
| 1478 |
if !ok { |
| 1479 |
t.Fatalf("got %v, want %v", result.Multiple, expected) |
| 1480 |
} |
| 1481 |
if got != v { |
| 1482 |
t.Errorf("got %s, want %s", got, v) |
| 1483 |
} |
| 1484 |
} |
| 1485 |
} |
| 1486 |
|
| 1487 |
type S13 struct { |
| 1488 |
Value []S14 |
| 1489 |
} |
| 1490 |
|
| 1491 |
type S14 struct { |
| 1492 |
F1 string |
| 1493 |
F2 string |
| 1494 |
} |
| 1495 |
|
| 1496 |
func (n *S14) UnmarshalText(text []byte) error { |
| 1497 |
textParts := strings.Split(string(text), " ") |
| 1498 |
if len(textParts) < 2 { |
| 1499 |
return errors.New("Not a valid name!") |
| 1500 |
} |
| 1501 |
|
| 1502 |
n.F1, n.F2 = textParts[0], textParts[len(textParts)-1] |
| 1503 |
return nil |
| 1504 |
} |
| 1505 |
|
| 1506 |
type S15 struct { |
| 1507 |
Value []S16 |
| 1508 |
} |
| 1509 |
|
| 1510 |
type S16 struct { |
| 1511 |
F1 string |
| 1512 |
F2 string |
| 1513 |
} |
| 1514 |
|
| 1515 |
func TestCustomTypeSlice(t *testing.T) { |
| 1516 |
data := map[string][]string{ |
| 1517 |
"Value.0": {"Louisa May Alcott"}, |
| 1518 |
"Value.1": {"Florence Nightingale"}, |
| 1519 |
"Value.2": {"Clara Barton"}, |
| 1520 |
} |
| 1521 |
|
| 1522 |
s := S13{} |
| 1523 |
decoder := NewDecoder() |
| 1524 |
|
| 1525 |
if err := decoder.Decode(&s, data); err != nil { |
| 1526 |
t.Fatal(err) |
| 1527 |
} |
| 1528 |
|
| 1529 |
if len(s.Value) != 3 { |
| 1530 |
t.Fatalf("Expected 3 values in the result list, got %+v", s.Value) |
| 1531 |
} |
| 1532 |
if s.Value[0].F1 != "Louisa" || s.Value[0].F2 != "Alcott" { |
| 1533 |
t.Errorf("Expected S14{'Louisa', 'Alcott'} got %+v", s.Value[0]) |
| 1534 |
} |
| 1535 |
if s.Value[1].F1 != "Florence" || s.Value[1].F2 != "Nightingale" { |
| 1536 |
t.Errorf("Expected S14{'Florence', 'Nightingale'} got %+v", s.Value[1]) |
| 1537 |
} |
| 1538 |
if s.Value[2].F1 != "Clara" || s.Value[2].F2 != "Barton" { |
| 1539 |
t.Errorf("Expected S14{'Clara', 'Barton'} got %+v", s.Value[2]) |
| 1540 |
} |
| 1541 |
} |
| 1542 |
|
| 1543 |
func TestCustomTypeSliceWithError(t *testing.T) { |
| 1544 |
data := map[string][]string{ |
| 1545 |
"Value.0": {"Louisa May Alcott"}, |
| 1546 |
"Value.1": {"Florence Nightingale"}, |
| 1547 |
"Value.2": {"Clara"}, |
| 1548 |
} |
| 1549 |
|
| 1550 |
s := S13{} |
| 1551 |
decoder := NewDecoder() |
| 1552 |
|
| 1553 |
if err := decoder.Decode(&s, data); err == nil { |
| 1554 |
t.Error("Not detecting error in conversion") |
| 1555 |
} |
| 1556 |
} |
| 1557 |
|
| 1558 |
func TestNoTextUnmarshalerTypeSlice(t *testing.T) { |
| 1559 |
data := map[string][]string{ |
| 1560 |
"Value.0": {"Louisa May Alcott"}, |
| 1561 |
"Value.1": {"Florence Nightingale"}, |
| 1562 |
"Value.2": {"Clara Barton"}, |
| 1563 |
} |
| 1564 |
|
| 1565 |
s := S15{} |
| 1566 |
decoder := NewDecoder() |
| 1567 |
|
| 1568 |
if err := decoder.Decode(&s, data); err == nil { |
| 1569 |
t.Error("Not detecting when there's no converter") |
| 1570 |
} |
| 1571 |
} |
| 1572 |
|
| 1573 |
// ---------------------------------------------------------------------------- |
| 1574 |
|
| 1575 |
type S17 struct { |
| 1576 |
Value S14 |
| 1577 |
} |
| 1578 |
|
| 1579 |
type S18 struct { |
| 1580 |
Value S16 |
| 1581 |
} |
| 1582 |
|
| 1583 |
func TestCustomType(t *testing.T) { |
| 1584 |
data := map[string][]string{ |
| 1585 |
"Value": {"Louisa May Alcott"}, |
| 1586 |
} |
| 1587 |
|
| 1588 |
s := S17{} |
| 1589 |
decoder := NewDecoder() |
| 1590 |
|
| 1591 |
if err := decoder.Decode(&s, data); err != nil { |
| 1592 |
t.Fatal(err) |
| 1593 |
} |
| 1594 |
|
| 1595 |
if s.Value.F1 != "Louisa" || s.Value.F2 != "Alcott" { |
| 1596 |
t.Errorf("Expected S14{'Louisa', 'Alcott'} got %+v", s.Value) |
| 1597 |
} |
| 1598 |
} |
| 1599 |
|
| 1600 |
func TestCustomTypeWithError(t *testing.T) { |
| 1601 |
data := map[string][]string{ |
| 1602 |
"Value": {"Louisa"}, |
| 1603 |
} |
| 1604 |
|
| 1605 |
s := S17{} |
| 1606 |
decoder := NewDecoder() |
| 1607 |
|
| 1608 |
if err := decoder.Decode(&s, data); err == nil { |
| 1609 |
t.Error("Not detecting error in conversion") |
| 1610 |
} |
| 1611 |
} |
| 1612 |
|
| 1613 |
func TestNoTextUnmarshalerType(t *testing.T) { |
| 1614 |
data := map[string][]string{ |
| 1615 |
"Value": {"Louisa May Alcott"}, |
| 1616 |
} |
| 1617 |
|
| 1618 |
s := S18{} |
| 1619 |
decoder := NewDecoder() |
| 1620 |
|
| 1621 |
if err := decoder.Decode(&s, data); err == nil { |
| 1622 |
t.Error("Not detecting when there's no converter") |
| 1623 |
} |
| 1624 |
} |
| 1625 |
|
| 1626 |
func TestExpectedType(t *testing.T) { |
| 1627 |
data := map[string][]string{ |
| 1628 |
"bools": {"1", "a"}, |
| 1629 |
"date": {"invalid"}, |
| 1630 |
"Foo.Bar": {"a", "b"}, |
| 1631 |
} |
| 1632 |
|
| 1633 |
type B struct { |
| 1634 |
Bar *int |
| 1635 |
} |
| 1636 |
type A struct { |
| 1637 |
Bools []bool `schema:"bools"` |
| 1638 |
Date time.Time `schema:"date"` |
| 1639 |
Foo B |
| 1640 |
} |
| 1641 |
|
| 1642 |
a := A{} |
| 1643 |
|
| 1644 |
err := NewDecoder().Decode(&a, data) |
| 1645 |
|
| 1646 |
e := err.(MultiError)["bools"].(ConversionError) |
| 1647 |
if e.Type != reflect.TypeOf(false) && e.Index == 1 { |
| 1648 |
t.Errorf("Expected bool, index: 1 got %+v, index: %d", e.Type, e.Index) |
| 1649 |
} |
| 1650 |
e = err.(MultiError)["date"].(ConversionError) |
| 1651 |
if e.Type != reflect.TypeOf(time.Time{}) { |
| 1652 |
t.Errorf("Expected time.Time got %+v", e.Type) |
| 1653 |
} |
| 1654 |
e = err.(MultiError)["Foo.Bar"].(ConversionError) |
| 1655 |
if e.Type != reflect.TypeOf(0) { |
| 1656 |
t.Errorf("Expected int got %+v", e.Type) |
| 1657 |
} |
| 1658 |
} |
| 1659 |
|
| 1660 |
type R1 struct { |
| 1661 |
A string `schema:"a,required"` |
| 1662 |
B struct { |
| 1663 |
C int `schema:"c,required"` |
| 1664 |
D float64 `schema:"d"` |
| 1665 |
E string `schema:"e,required"` |
| 1666 |
} `schema:"b"` |
| 1667 |
F []string `schema:"f,required"` |
| 1668 |
G []int `schema:"g,othertag"` |
| 1669 |
H bool `schema:"h,required"` |
| 1670 |
} |
| 1671 |
|
| 1672 |
func TestRequiredField(t *testing.T) { |
| 1673 |
var a R1 |
| 1674 |
v := map[string][]string{ |
| 1675 |
"a": {"bbb"}, |
| 1676 |
"b.c": {"88"}, |
| 1677 |
"b.d": {"9"}, |
| 1678 |
"f": {""}, |
| 1679 |
"h": {"true"}, |
| 1680 |
} |
| 1681 |
err := NewDecoder().Decode(&a, v) |
| 1682 |
if err == nil { |
| 1683 |
t.Errorf("error nil, b.e is empty expect") |
| 1684 |
return |
| 1685 |
} |
| 1686 |
// b.e empty |
| 1687 |
v["b.e"] = []string{""} // empty string |
| 1688 |
err = NewDecoder().Decode(&a, v) |
| 1689 |
if err == nil { |
| 1690 |
t.Errorf("error nil, b.e is empty expect") |
| 1691 |
return |
| 1692 |
} |
| 1693 |
if expected := `b.e is empty`; err.Error() != expected { |
| 1694 |
t.Errorf("got %q, want %q", err, expected) |
| 1695 |
} |
| 1696 |
|
| 1697 |
// all fields ok |
| 1698 |
v["b.e"] = []string{"nonempty"} |
| 1699 |
err = NewDecoder().Decode(&a, v) |
| 1700 |
if err != nil { |
| 1701 |
t.Errorf("error: %v", err) |
| 1702 |
return |
| 1703 |
} |
| 1704 |
|
| 1705 |
// set f empty |
| 1706 |
v["f"] = []string{} |
| 1707 |
err = NewDecoder().Decode(&a, v) |
| 1708 |
if err == nil { |
| 1709 |
t.Errorf("error nil, f is empty expect") |
| 1710 |
return |
| 1711 |
} |
| 1712 |
if expected := `f is empty`; err.Error() != expected { |
| 1713 |
t.Errorf("got %q, want %q", err, expected) |
| 1714 |
} |
| 1715 |
v["f"] = []string{"nonempty"} |
| 1716 |
|
| 1717 |
// b.c type int with empty string |
| 1718 |
v["b.c"] = []string{""} |
| 1719 |
err = NewDecoder().Decode(&a, v) |
| 1720 |
if err == nil { |
| 1721 |
t.Errorf("error nil, b.c is empty expect") |
| 1722 |
return |
| 1723 |
} |
| 1724 |
v["b.c"] = []string{"3"} |
| 1725 |
|
| 1726 |
// h type bool with empty string |
| 1727 |
v["h"] = []string{""} |
| 1728 |
err = NewDecoder().Decode(&a, v) |
| 1729 |
if err == nil { |
| 1730 |
t.Errorf("error nil, h is empty expect") |
| 1731 |
return |
| 1732 |
} |
| 1733 |
if expected := `h is empty`; err.Error() != expected { |
| 1734 |
t.Errorf("got %q, want %q", err, expected) |
| 1735 |
} |
| 1736 |
} |
| 1737 |
|
| 1738 |
type R2 struct { |
| 1739 |
A struct { |
| 1740 |
B int `schema:"b"` |
| 1741 |
} `schema:"a,required"` |
| 1742 |
} |
| 1743 |
|
| 1744 |
func TestRequiredStructFiled(t *testing.T) { |
| 1745 |
v := map[string][]string{ |
| 1746 |
"a.b": {"3"}, |
| 1747 |
} |
| 1748 |
var a R2 |
| 1749 |
err := NewDecoder().Decode(&a, v) |
| 1750 |
if err != nil { |
| 1751 |
t.Errorf("error: %v", err) |
| 1752 |
} |
| 1753 |
} |
| 1754 |
|
| 1755 |
type Node struct { |
| 1756 |
Value int `schema:"val,required"` |
| 1757 |
Next *Node `schema:"next,required"` |
| 1758 |
} |
| 1759 |
|
| 1760 |
func TestRecursiveStruct(t *testing.T) { |
| 1761 |
v := map[string][]string{ |
| 1762 |
"val": {"1"}, |
| 1763 |
"next.val": {"2"}, |
| 1764 |
} |
| 1765 |
var a Node |
| 1766 |
err := NewDecoder().Decode(&a, v) |
| 1767 |
if err != nil { |
| 1768 |
t.Errorf("error: %v", err) |
| 1769 |
} |
| 1770 |
} |
| 1771 |
|
| 1772 |
func TestRequiredFieldIsMissingCorrectError(t *testing.T) { |
| 1773 |
type RM1S struct { |
| 1774 |
A string `schema:"rm1aa,required"` |
| 1775 |
B string `schema:"rm1bb,required"` |
| 1776 |
} |
| 1777 |
type RM1 struct { |
| 1778 |
RM1S |
| 1779 |
} |
| 1780 |
|
| 1781 |
var a RM1 |
| 1782 |
v := map[string][]string{ |
| 1783 |
"rm1aa": {"aaa"}, |
| 1784 |
} |
| 1785 |
expectedError := "RM1S.rm1bb is empty" |
| 1786 |
err := NewDecoder().Decode(&a, v) |
| 1787 |
if err.Error() != expectedError { |
| 1788 |
t.Errorf("expected %v, got %v", expectedError, err) |
| 1789 |
} |
| 1790 |
} |
| 1791 |
|
| 1792 |
type AS1 struct { |
| 1793 |
A int32 `schema:"a,required"` |
| 1794 |
E int32 `schema:"e,required"` |
| 1795 |
} |
| 1796 |
type AS2 struct { |
| 1797 |
AS1 |
| 1798 |
B string `schema:"b,required"` |
| 1799 |
} |
| 1800 |
type AS3 struct { |
| 1801 |
C int32 `schema:"c"` |
| 1802 |
} |
| 1803 |
|
| 1804 |
type AS4 struct { |
| 1805 |
AS3 |
| 1806 |
D string `schema:"d"` |
| 1807 |
} |
| 1808 |
|
| 1809 |
func TestAnonymousStructField(t *testing.T) { |
| 1810 |
patterns := []map[string][]string{ |
| 1811 |
{ |
| 1812 |
"a": {"1"}, |
| 1813 |
"e": {"2"}, |
| 1814 |
"b": {"abc"}, |
| 1815 |
}, |
| 1816 |
{ |
| 1817 |
"AS1.a": {"1"}, |
| 1818 |
"AS1.e": {"2"}, |
| 1819 |
"b": {"abc"}, |
| 1820 |
}, |
| 1821 |
} |
| 1822 |
for _, v := range patterns { |
| 1823 |
a := AS2{} |
| 1824 |
err := NewDecoder().Decode(&a, v) |
| 1825 |
if err != nil { |
| 1826 |
t.Errorf("Decode failed %s, %#v", err, v) |
| 1827 |
continue |
| 1828 |
} |
| 1829 |
if a.A != 1 { |
| 1830 |
t.Errorf("A: expected %v, got %v", 1, a.A) |
| 1831 |
} |
| 1832 |
if a.E != 2 { |
| 1833 |
t.Errorf("E: expected %v, got %v", 2, a.E) |
| 1834 |
} |
| 1835 |
if a.B != "abc" { |
| 1836 |
t.Errorf("B: expected %v, got %v", "abc", a.B) |
| 1837 |
} |
| 1838 |
embedded := a.AS1 |
| 1839 |
if embedded.A != 1 { |
| 1840 |
t.Errorf("AS1.A: expected %v, got %v", 1, embedded.A) |
| 1841 |
} |
| 1842 |
if embedded.E != 2 { |
| 1843 |
t.Errorf("AS1.E: expected %v, got %v", 2, embedded.E) |
| 1844 |
} |
| 1845 |
} |
| 1846 |
a := AS2{} |
| 1847 |
err := NewDecoder().Decode(&a, map[string][]string{ |
| 1848 |
"e": {"2"}, |
| 1849 |
"b": {"abc"}, |
| 1850 |
}) |
| 1851 |
if err == nil { |
| 1852 |
t.Errorf("error nil, a is empty expect") |
| 1853 |
} |
| 1854 |
patterns = []map[string][]string{ |
| 1855 |
{ |
| 1856 |
"c": {"1"}, |
| 1857 |
"d": {"abc"}, |
| 1858 |
}, |
| 1859 |
{ |
| 1860 |
"AS3.c": {"1"}, |
| 1861 |
"d": {"abc"}, |
| 1862 |
}, |
| 1863 |
} |
| 1864 |
for _, v := range patterns { |
| 1865 |
a := AS4{} |
| 1866 |
err := NewDecoder().Decode(&a, v) |
| 1867 |
if err != nil { |
| 1868 |
t.Errorf("Decode failed %s, %#v", err, v) |
| 1869 |
continue |
| 1870 |
} |
| 1871 |
if a.C != 1 { |
| 1872 |
t.Errorf("C: expected %v, got %v", 1, a.C) |
| 1873 |
} |
| 1874 |
if a.D != "abc" { |
| 1875 |
t.Errorf("D: expected %v, got %v", "abc", a.D) |
| 1876 |
} |
| 1877 |
if embedded := a.AS3; embedded.C != 1 { |
| 1878 |
t.Errorf("AS3.C: expected %v, got %v", 1, embedded.C) |
| 1879 |
} |
| 1880 |
} |
| 1881 |
} |
| 1882 |
|
| 1883 |
func TestAmbiguousStructField(t *testing.T) { |
| 1884 |
type I1 struct { |
| 1885 |
X int |
| 1886 |
} |
| 1887 |
type I2 struct { |
| 1888 |
I1 |
| 1889 |
} |
| 1890 |
type B1 struct { |
| 1891 |
X bool |
| 1892 |
} |
| 1893 |
type B2 struct { |
| 1894 |
B1 |
| 1895 |
} |
| 1896 |
type IB struct { |
| 1897 |
I1 |
| 1898 |
B1 |
| 1899 |
} |
| 1900 |
type S struct { |
| 1901 |
I1 |
| 1902 |
I2 |
| 1903 |
B1 |
| 1904 |
B2 |
| 1905 |
IB |
| 1906 |
} |
| 1907 |
dst := S{} |
| 1908 |
src := map[string][]string{ |
| 1909 |
"X": {"123"}, |
| 1910 |
"IB.X": {"123"}, |
| 1911 |
} |
| 1912 |
dec := NewDecoder() |
| 1913 |
dec.IgnoreUnknownKeys(false) |
| 1914 |
err := dec.Decode(&dst, src) |
| 1915 |
e, ok := err.(MultiError) |
| 1916 |
if !ok || len(e) != 2 { |
| 1917 |
t.Errorf("Expected 2 errors, got %#v", err) |
| 1918 |
} |
| 1919 |
if expected := (UnknownKeyError{Key: "X"}); e["X"] != expected { |
| 1920 |
t.Errorf("X: expected %#v, got %#v", expected, e["X"]) |
| 1921 |
} |
| 1922 |
if expected := (UnknownKeyError{Key: "IB.X"}); e["IB.X"] != expected { |
| 1923 |
t.Errorf("X: expected %#v, got %#v", expected, e["IB.X"]) |
| 1924 |
} |
| 1925 |
dec.IgnoreUnknownKeys(true) |
| 1926 |
err = dec.Decode(&dst, src) |
| 1927 |
if err != nil { |
| 1928 |
t.Errorf("Decode failed %v", err) |
| 1929 |
} |
| 1930 |
|
| 1931 |
expected := S{ |
| 1932 |
I1: I1{X: 123}, |
| 1933 |
I2: I2{I1: I1{X: 234}}, |
| 1934 |
B1: B1{X: true}, |
| 1935 |
B2: B2{B1: B1{X: true}}, |
| 1936 |
IB: IB{I1: I1{X: 345}, B1: B1{X: true}}, |
| 1937 |
} |
| 1938 |
patterns := []map[string][]string{ |
| 1939 |
{ |
| 1940 |
"I1.X": {"123"}, |
| 1941 |
"I2.X": {"234"}, |
| 1942 |
"B1.X": {"true"}, |
| 1943 |
"B2.X": {"1"}, |
| 1944 |
"IB.I1.X": {"345"}, |
| 1945 |
"IB.B1.X": {"on"}, |
| 1946 |
}, |
| 1947 |
{ |
| 1948 |
"I1.X": {"123"}, |
| 1949 |
"I2.I1.X": {"234"}, |
| 1950 |
"B1.X": {"true"}, |
| 1951 |
"B2.B1.X": {"1"}, |
| 1952 |
"IB.I1.X": {"345"}, |
| 1953 |
"IB.B1.X": {"on"}, |
| 1954 |
}, |
| 1955 |
} |
| 1956 |
for _, src := range patterns { |
| 1957 |
dst := S{} |
| 1958 |
dec := NewDecoder() |
| 1959 |
dec.IgnoreUnknownKeys(false) |
| 1960 |
err := dec.Decode(&dst, src) |
| 1961 |
if err != nil { |
| 1962 |
t.Errorf("Decode failed %v, %#v", err, src) |
| 1963 |
} |
| 1964 |
if !reflect.DeepEqual(expected, dst) { |
| 1965 |
t.Errorf("Expected %+v, got %+v", expected, dst) |
| 1966 |
} |
| 1967 |
} |
| 1968 |
} |
| 1969 |
|
| 1970 |
func TestComprehensiveDecodingErrors(t *testing.T) { |
| 1971 |
type I1 struct { |
| 1972 |
V int `schema:",required"` |
| 1973 |
P *int `schema:",required"` |
| 1974 |
} |
| 1975 |
type I2 struct { |
| 1976 |
I1 |
| 1977 |
J I1 |
| 1978 |
} |
| 1979 |
type S1 struct { |
| 1980 |
V string `schema:"v,required"` |
| 1981 |
P *string `schema:"p,required"` |
| 1982 |
} |
| 1983 |
type S2 struct { |
| 1984 |
S1 `schema:"s"` |
| 1985 |
T S1 `schema:"t"` |
| 1986 |
} |
| 1987 |
type D struct { |
| 1988 |
I2 |
| 1989 |
X S2 `schema:"x"` |
| 1990 |
Y S2 `schema:"-"` |
| 1991 |
} |
| 1992 |
patterns := []map[string][]string{ |
| 1993 |
{ |
| 1994 |
"V": {"invalid"}, // invalid |
| 1995 |
"I2.I1.P": {}, // empty |
| 1996 |
"I2.J.V": {""}, // empty |
| 1997 |
"I2.J.P": {"123"}, // ok |
| 1998 |
"x.s.v": {""}, // empty |
| 1999 |
"x.s.p": {""}, // ok |
| 2000 |
"x.t.v": {"abc"}, // ok |
| 2001 |
"x.t.p": {}, // empty |
| 2002 |
"Y.s.v": {"ignored"}, // unknown |
| 2003 |
}, |
| 2004 |
{ |
| 2005 |
"V": {"invalid"}, // invalid |
| 2006 |
"P": {}, // empty |
| 2007 |
"J.V": {""}, // empty |
| 2008 |
"J.P": {"123"}, // ok |
| 2009 |
"x.v": {""}, // empty |
| 2010 |
"x.p": {""}, // ok |
| 2011 |
"x.t.v": {"abc"}, // ok |
| 2012 |
"x.t.p": {}, // empty |
| 2013 |
"Y.s.v": {"ignored"}, // unknown |
| 2014 |
}, |
| 2015 |
} |
| 2016 |
for _, src := range patterns { |
| 2017 |
dst := D{} |
| 2018 |
dec := NewDecoder() |
| 2019 |
dec.IgnoreUnknownKeys(false) |
| 2020 |
err := dec.Decode(&dst, src) |
| 2021 |
e, ok := err.(MultiError) |
| 2022 |
if !ok || len(e) != 6 { |
| 2023 |
t.Errorf("Expected 6 errors, got %#v", err) |
| 2024 |
} |
| 2025 |
if cerr, ok := e["V"].(ConversionError); !ok { |
| 2026 |
t.Errorf("%s: expected %#v, got %#v", "I2.I1.V", ConversionError{Key: "V"}, cerr) |
| 2027 |
} |
| 2028 |
if key, expected := "I2.I1.P", (EmptyFieldError{Key: "I2.I1.P"}); e[key] != expected { |
| 2029 |
t.Errorf("%s: expected %#v, got %#v", key, expected, e[key]) |
| 2030 |
} |
| 2031 |
if key, expected := "I2.J.V", (EmptyFieldError{Key: "I2.J.V"}); e[key] != expected { |
| 2032 |
t.Errorf("%s: expected %#v, got %#v", key, expected, e[key]) |
| 2033 |
} |
| 2034 |
if key, expected := "x.s.v", (EmptyFieldError{Key: "x.s.v"}); e[key] != expected { |
| 2035 |
t.Errorf("%s: expected %#v, got %#v", key, expected, e[key]) |
| 2036 |
} |
| 2037 |
if key, expected := "x.t.p", (EmptyFieldError{Key: "x.t.p"}); e[key] != expected { |
| 2038 |
t.Errorf("%s: expected %#v, got %#v", key, expected, e[key]) |
| 2039 |
} |
| 2040 |
if key, expected := "Y.s.v", (UnknownKeyError{Key: "Y.s.v"}); e[key] != expected { |
| 2041 |
t.Errorf("%s: expected %#v, got %#v", key, expected, e[key]) |
| 2042 |
} |
| 2043 |
// J is promoted from the embedded I2 struct. |
| 2044 |
if expected := 123; dst.J.P == nil || *dst.J.P != expected { |
| 2045 |
t.Errorf("I2.J.P: expected %#v, got %#v", expected, dst.J.P) |
| 2046 |
} |
| 2047 |
// P is promoted from the embedded S1 inside X. |
| 2048 |
if expected := ""; dst.X.P == nil || *dst.X.P != expected { |
| 2049 |
t.Errorf("X.S1.P: expected %#v, got %#v", expected, dst.X.P) |
| 2050 |
} |
| 2051 |
if expected := "abc"; dst.X.T.V != expected { |
| 2052 |
t.Errorf("X.T.V: expected %#v, got %#v", expected, dst.X.T.V) |
| 2053 |
} |
| 2054 |
} |
| 2055 |
} |
| 2056 |
|
| 2057 |
// Test to ensure that a registered converter overrides the default text unmarshaler. |
| 2058 |
func TestRegisterConverterOverridesTextUnmarshaler(t *testing.T) { |
| 2059 |
type MyTime time.Time |
| 2060 |
s1 := &struct { |
| 2061 |
MyTime |
| 2062 |
}{} |
| 2063 |
decoder := NewDecoder() |
| 2064 |
|
| 2065 |
ts := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) |
| 2066 |
decoder.RegisterConverter(s1.MyTime, func(s string) reflect.Value { return reflect.ValueOf(ts) }) |
| 2067 |
|
| 2068 |
v1 := map[string][]string{"MyTime": {"4"}} |
| 2069 |
err := decoder.Decode(s1, v1) |
| 2070 |
if err != nil { |
| 2071 |
t.Fatalf("Failed to decode: %v", err) |
| 2072 |
} |
| 2073 |
|
| 2074 |
if s1.MyTime != MyTime(ts) { |
| 2075 |
t.Errorf("s1.Aa: expected %v, got %v", ts, s1.MyTime) |
| 2076 |
} |
| 2077 |
} |
| 2078 |
|
| 2079 |
type S20E string |
| 2080 |
|
| 2081 |
func (e *S20E) UnmarshalText(text []byte) error { |
| 2082 |
*e = S20E("x") |
| 2083 |
return nil |
| 2084 |
} |
| 2085 |
|
| 2086 |
type S20 []S20E |
| 2087 |
|
| 2088 |
func (s *S20) UnmarshalText(text []byte) error { |
| 2089 |
*s = S20{"a", "b", "c"} |
| 2090 |
return nil |
| 2091 |
} |
| 2092 |
|
| 2093 |
// Test to ensure that when a custom type based on a slice implements an |
| 2094 |
// encoding.TextUnmarshaler interface that it takes precedence over any |
| 2095 |
// implementations by its elements. |
| 2096 |
func TestTextUnmarshalerTypeSlice(t *testing.T) { |
| 2097 |
data := map[string][]string{ |
| 2098 |
"Value": {"a,b,c"}, |
| 2099 |
} |
| 2100 |
s := struct { |
| 2101 |
Value S20 |
| 2102 |
}{} |
| 2103 |
decoder := NewDecoder() |
| 2104 |
if err := decoder.Decode(&s, data); err != nil { |
| 2105 |
t.Fatal("Error while decoding:", err) |
| 2106 |
} |
| 2107 |
expected := S20{"a", "b", "c"} |
| 2108 |
if !reflect.DeepEqual(expected, s.Value) { |
| 2109 |
t.Errorf("Expected %v errors, got %v", expected, s.Value) |
| 2110 |
} |
| 2111 |
} |
| 2112 |
|
| 2113 |
type S21E struct{ ElementValue string } |
| 2114 |
|
| 2115 |
func (e *S21E) UnmarshalText(text []byte) error { |
| 2116 |
*e = S21E{"x"} |
| 2117 |
return nil |
| 2118 |
} |
| 2119 |
|
| 2120 |
type S21 []S21E |
| 2121 |
|
| 2122 |
func (s *S21) UnmarshalText(text []byte) error { |
| 2123 |
*s = S21{{"a"}} |
| 2124 |
return nil |
| 2125 |
} |
| 2126 |
|
| 2127 |
type S21B []S21E |
| 2128 |
|
| 2129 |
// Test to ensure that if custom type base on a slice of structs implements an |
| 2130 |
// encoding.TextUnmarshaler interface it is unaffected by the special path |
| 2131 |
// requirements imposed on a slice of structs. |
| 2132 |
func TestTextUnmarshalerTypeSliceOfStructs(t *testing.T) { |
| 2133 |
data := map[string][]string{ |
| 2134 |
"Value": {"raw a"}, |
| 2135 |
} |
| 2136 |
// Implements encoding.TextUnmarshaler, should not throw invalid path |
| 2137 |
// error. |
| 2138 |
s := struct { |
| 2139 |
Value S21 |
| 2140 |
}{} |
| 2141 |
decoder := NewDecoder() |
| 2142 |
if err := decoder.Decode(&s, data); err != nil { |
| 2143 |
t.Fatal("Error while decoding:", err) |
| 2144 |
} |
| 2145 |
expected := S21{{"a"}} |
| 2146 |
if !reflect.DeepEqual(expected, s.Value) { |
| 2147 |
t.Errorf("Expected %v errors, got %v", expected, s.Value) |
| 2148 |
} |
| 2149 |
// Does not implement encoding.TextUnmarshaler, should throw invalid |
| 2150 |
// path error. |
| 2151 |
sb := struct { |
| 2152 |
Value S21B |
| 2153 |
}{} |
| 2154 |
if err := decoder.Decode(&sb, data); err == errInvalidPath { |
| 2155 |
t.Fatal("Expecting invalid path error", err) |
| 2156 |
} |
| 2157 |
} |
| 2158 |
|
| 2159 |
type S22 string |
| 2160 |
|
| 2161 |
func (s *S22) UnmarshalText(text []byte) error { |
| 2162 |
*s = S22("a") |
| 2163 |
return nil |
| 2164 |
} |
| 2165 |
|
| 2166 |
// Test to ensure that when a field that should be decoded into a type |
| 2167 |
// implementing the encoding.TextUnmarshaler interface is set to an empty value |
| 2168 |
// that the UnmarshalText method is utilized over other methods of decoding, |
| 2169 |
// especially including simply setting the zero value. |
| 2170 |
func TestTextUnmarshalerEmpty(t *testing.T) { |
| 2171 |
data := map[string][]string{ |
| 2172 |
"Value": {""}, // empty value |
| 2173 |
} |
| 2174 |
// Implements encoding.TextUnmarshaler, should use the type's |
| 2175 |
// UnmarshalText method. |
| 2176 |
s := struct { |
| 2177 |
Value S22 |
| 2178 |
}{} |
| 2179 |
decoder := NewDecoder() |
| 2180 |
if err := decoder.Decode(&s, data); err != nil { |
| 2181 |
t.Fatal("Error while decoding:", err) |
| 2182 |
} |
| 2183 |
expected := S22("a") |
| 2184 |
if expected != s.Value { |
| 2185 |
t.Errorf("Expected %v errors, got %v", expected, s.Value) |
| 2186 |
} |
| 2187 |
} |
| 2188 |
|
| 2189 |
type S23n struct { |
| 2190 |
F2 string `schema:"F2"` |
| 2191 |
F3 string `schema:"F3"` |
| 2192 |
} |
| 2193 |
|
| 2194 |
type S23e struct { |
| 2195 |
*S23n |
| 2196 |
F1 string `schema:"F1"` |
| 2197 |
} |
| 2198 |
|
| 2199 |
type S23 []*S23e |
| 2200 |
|
| 2201 |
func TestUnmashalPointerToEmbedded(t *testing.T) { |
| 2202 |
data := map[string][]string{ |
| 2203 |
"A.0.F2": {"raw a"}, |
| 2204 |
"A.0.F3": {"raw b"}, |
| 2205 |
} |
| 2206 |
|
| 2207 |
// Implements encoding.TextUnmarshaler, should not throw invalid path |
| 2208 |
// error. |
| 2209 |
s := struct { |
| 2210 |
Value S23 `schema:"A"` |
| 2211 |
}{} |
| 2212 |
decoder := NewDecoder() |
| 2213 |
|
| 2214 |
if err := decoder.Decode(&s, data); err != nil { |
| 2215 |
t.Fatal("Error while decoding:", err) |
| 2216 |
} |
| 2217 |
|
| 2218 |
expected := S23{ |
| 2219 |
&S23e{ |
| 2220 |
S23n: &S23n{"raw a", "raw b"}, |
| 2221 |
}, |
| 2222 |
} |
| 2223 |
if !reflect.DeepEqual(expected, s.Value) { |
| 2224 |
t.Errorf("Expected %v errors, got %v", expected, s.Value) |
| 2225 |
} |
| 2226 |
} |
| 2227 |
|
| 2228 |
type S24 struct { |
| 2229 |
F1 string `schema:"F1"` |
| 2230 |
} |
| 2231 |
|
| 2232 |
type S24e struct { |
| 2233 |
*S24 |
| 2234 |
F2 string `schema:"F2"` |
| 2235 |
} |
| 2236 |
|
| 2237 |
func TestUnmarshallToEmbeddedNoData(t *testing.T) { |
| 2238 |
data := map[string][]string{ |
| 2239 |
"F3": {"raw a"}, |
| 2240 |
} |
| 2241 |
|
| 2242 |
s := &S24e{} |
| 2243 |
|
| 2244 |
decoder := NewDecoder() |
| 2245 |
err := decoder.Decode(s, data) |
| 2246 |
|
| 2247 |
expectedErr := `schema: invalid path "F3"` |
| 2248 |
if err.Error() != expectedErr { |
| 2249 |
t.Fatalf("got %q, want %q", err, expectedErr) |
| 2250 |
} |
| 2251 |
} |
| 2252 |
|
| 2253 |
type S25ee struct { |
| 2254 |
F3 string `schema:"F3"` |
| 2255 |
} |
| 2256 |
|
| 2257 |
type S25e struct { |
| 2258 |
S25ee |
| 2259 |
F2 string `schema:"F2"` |
| 2260 |
} |
| 2261 |
|
| 2262 |
type S25 struct { |
| 2263 |
S25e |
| 2264 |
F1 string `schema:"F1"` |
| 2265 |
} |
| 2266 |
|
| 2267 |
func TestDoubleEmbedded(t *testing.T) { |
| 2268 |
data := map[string][]string{ |
| 2269 |
"F1": {"raw a"}, |
| 2270 |
"F2": {"raw b"}, |
| 2271 |
"F3": {"raw c"}, |
| 2272 |
} |
| 2273 |
|
| 2274 |
s := S25{} |
| 2275 |
decoder := NewDecoder() |
| 2276 |
|
| 2277 |
if err := decoder.Decode(&s, data); err != nil { |
| 2278 |
t.Fatal("Error while decoding:", err) |
| 2279 |
} |
| 2280 |
|
| 2281 |
expected := S25{ |
| 2282 |
F1: "raw a", |
| 2283 |
S25e: S25e{ |
| 2284 |
F2: "raw b", |
| 2285 |
S25ee: S25ee{ |
| 2286 |
F3: "raw c", |
| 2287 |
}, |
| 2288 |
}, |
| 2289 |
} |
| 2290 |
if !reflect.DeepEqual(expected, s) { |
| 2291 |
t.Errorf("Expected %v errors, got %v", expected, s) |
| 2292 |
} |
| 2293 |
} |
| 2294 |
|
| 2295 |
type S26ee struct { |
| 2296 |
F string `schema:"f"` |
| 2297 |
} |
| 2298 |
|
| 2299 |
type S26e struct { |
| 2300 |
*S26ee |
| 2301 |
} |
| 2302 |
|
| 2303 |
type S26 struct { |
| 2304 |
*S26e |
| 2305 |
A string `schema:"a"` |
| 2306 |
} |
| 2307 |
|
| 2308 |
// Fields promoted through two levels of embedded pointers must be reachable; |
| 2309 |
// this used to panic with "indirection through nil pointer to embedded |
| 2310 |
// struct" because only the first level was allocated. |
| 2311 |
func TestDoubleEmbeddedPointer(t *testing.T) { |
| 2312 |
data := map[string][]string{ |
| 2313 |
"f": {"raw a"}, |
| 2314 |
"a": {"raw b"}, |
| 2315 |
} |
| 2316 |
|
| 2317 |
s := S26{} |
| 2318 |
decoder := NewDecoder() |
| 2319 |
|
| 2320 |
if err := decoder.Decode(&s, data); err != nil { |
| 2321 |
t.Fatal("Error while decoding:", err) |
| 2322 |
} |
| 2323 |
|
| 2324 |
if s.A != "raw b" { |
| 2325 |
t.Errorf("A: expected %q, got %q", "raw b", s.A) |
| 2326 |
} |
| 2327 |
if s.S26e == nil || s.S26ee == nil { |
| 2328 |
t.Fatalf("embedded pointers not allocated: %+v", s) |
| 2329 |
} |
| 2330 |
if s.F != "raw a" { |
| 2331 |
t.Errorf("F: expected %q, got %q", "raw a", s.F) |
| 2332 |
} |
| 2333 |
} |
| 2334 |
|
| 2335 |
// Embedded anonymous pointers must be allocated by Decode even when the |
| 2336 |
// struct declares no defaults and src contains no matching keys — callers |
| 2337 |
// rely on promoted fields being reachable after Decode. |
| 2338 |
func TestEmbeddedPointerAllocatedWithoutDefaults(t *testing.T) { |
| 2339 |
type Inner struct { |
| 2340 |
X string `schema:"x"` |
| 2341 |
} |
| 2342 |
type Outer struct { |
| 2343 |
*Inner |
| 2344 |
Y string `schema:"y"` |
| 2345 |
} |
| 2346 |
|
| 2347 |
var o Outer |
| 2348 |
if err := NewDecoder().Decode(&o, map[string][]string{}); err != nil { |
| 2349 |
t.Fatal(err) |
| 2350 |
} |
| 2351 |
if o.Inner == nil { |
| 2352 |
t.Fatal("embedded pointer not allocated for empty src") |
| 2353 |
} |
| 2354 |
|
| 2355 |
var o2 Outer |
| 2356 |
if err := NewDecoder().Decode(&o2, map[string][]string{"y": {"v"}}); err != nil { |
| 2357 |
t.Fatal(err) |
| 2358 |
} |
| 2359 |
if o2.Inner == nil { |
| 2360 |
t.Fatal("embedded pointer not allocated when src only touches siblings") |
| 2361 |
} |
| 2362 |
} |
| 2363 |
|
| 2364 |
type shadowTU struct{ S string } |
| 2365 |
|
| 2366 |
func (c *shadowTU) UnmarshalText(b []byte) error { c.S = string(b); return nil } |
| 2367 |
|
| 2368 |
type shadowEmb struct { |
| 2369 |
F shadowTU `schema:"f"` |
| 2370 |
} |
| 2371 |
|
| 2372 |
type shadowOuter struct { |
| 2373 |
shadowEmb |
| 2374 |
F string `schema:"g"` |
| 2375 |
} |
| 2376 |
|
| 2377 |
// A promoted field whose Go name is shadowed by an outer field with a |
| 2378 |
// different alias must decode into the embedded field its alias identifies |
| 2379 |
// (this used to panic via mismatched cached unmarshaler metadata). |
| 2380 |
func TestShadowedPromotedFieldDecodes(t *testing.T) { |
| 2381 |
var s shadowOuter |
| 2382 |
if err := NewDecoder().Decode(&s, map[string][]string{"f": {"val"}, "g": {"out"}}); err != nil { |
| 2383 |
t.Fatal(err) |
| 2384 |
} |
| 2385 |
if s.shadowEmb.F.S != "val" { |
| 2386 |
t.Errorf("embedded field: expected %q, got %q", "val", s.shadowEmb.F.S) |
| 2387 |
} |
| 2388 |
if s.F != "out" { |
| 2389 |
t.Errorf("outer field: expected %q, got %q", "out", s.F) |
| 2390 |
} |
| 2391 |
} |
| 2392 |
|
| 2393 |
// Two promoted fields sharing a Go name but carrying distinct aliases must |
| 2394 |
// both be addressable by their aliases (the name-based walk used to skip or |
| 2395 |
// reject them). |
| 2396 |
func TestAmbiguousPromotedNamesDistinctAliases(t *testing.T) { |
| 2397 |
type ambA struct { |
| 2398 |
X string `schema:"xa"` |
| 2399 |
} |
| 2400 |
type ambB struct { |
| 2401 |
X string `schema:"xb"` |
| 2402 |
} |
| 2403 |
type elem struct { |
| 2404 |
ambA |
| 2405 |
ambB |
| 2406 |
N string `schema:"n"` |
| 2407 |
} |
| 2408 |
type s struct { |
| 2409 |
Items []elem `schema:"items"` |
| 2410 |
} |
| 2411 |
|
| 2412 |
var dst s |
| 2413 |
err := NewDecoder().Decode(&dst, map[string][]string{ |
| 2414 |
"items.0.n": {"ok"}, |
| 2415 |
"items.0.xa": {"va"}, |
| 2416 |
"items.0.xb": {"vb"}, |
| 2417 |
}) |
| 2418 |
if err != nil { |
| 2419 |
t.Fatal(err) |
| 2420 |
} |
| 2421 |
got := dst.Items[0] |
| 2422 |
if got.N != "ok" || got.ambA.X != "va" || got.ambB.X != "vb" { |
| 2423 |
t.Errorf("unexpected result: %+v", got) |
| 2424 |
} |
| 2425 |
} |
| 2426 |
|
| 2427 |
// Growing a slice must never write into spare capacity of the caller's |
| 2428 |
// original backing array — other slices may alias it. |
| 2429 |
func TestSliceGrowthDetachesFromCallerArray(t *testing.T) { |
| 2430 |
type item struct { |
| 2431 |
P int `schema:"p"` |
| 2432 |
} |
| 2433 |
type cart struct { |
| 2434 |
Items []item `schema:"items"` |
| 2435 |
} |
| 2436 |
|
| 2437 |
backing := make([]item, 8) |
| 2438 |
for i := range backing { |
| 2439 |
backing[i] = item{P: -1} |
| 2440 |
} |
| 2441 |
c := cart{Items: backing[:2]} |
| 2442 |
if err := NewDecoder().Decode(&c, map[string][]string{"items.4.p": {"7"}}); err != nil { |
| 2443 |
t.Fatal(err) |
| 2444 |
} |
| 2445 |
if len(c.Items) != 5 || c.Items[4].P != 7 { |
| 2446 |
t.Fatalf("unexpected decode result: %+v", c.Items) |
| 2447 |
} |
| 2448 |
for i := 2; i < 8; i++ { |
| 2449 |
if backing[i].P != -1 { |
| 2450 |
t.Fatalf("caller backing array mutated at %d: %+v", i, backing[i]) |
| 2451 |
} |
| 2452 |
} |
| 2453 |
} |
| 2454 |
|
| 2455 |
// Reused destination slices must not leak stale element data into slots the |
| 2456 |
// decoder grows into, and out-of-order indices must land correctly. |
| 2457 |
func TestDecodeSliceIndexGrowth(t *testing.T) { |
| 2458 |
type item struct { |
| 2459 |
Name string `schema:"name"` |
| 2460 |
Price int `schema:"price"` |
| 2461 |
} |
| 2462 |
type cart struct { |
| 2463 |
Items []item `schema:"items"` |
| 2464 |
} |
| 2465 |
|
| 2466 |
src := map[string][]string{} |
| 2467 |
for i := 0; i < 50; i++ { |
| 2468 |
src["items."+strconv.Itoa(i)+".price"] = []string{strconv.Itoa(i * 3)} |
| 2469 |
} |
| 2470 |
d := NewDecoder() |
| 2471 |
|
| 2472 |
var c cart |
| 2473 |
if err := d.Decode(&c, src); err != nil { |
| 2474 |
t.Fatal(err) |
| 2475 |
} |
| 2476 |
if len(c.Items) != 50 { |
| 2477 |
t.Fatalf("len = %d, want 50", len(c.Items)) |
| 2478 |
} |
| 2479 |
for i, it := range c.Items { |
| 2480 |
if it.Price != i*3 { |
| 2481 |
t.Fatalf("Items[%d].Price = %d, want %d", i, it.Price, i*3) |
| 2482 |
} |
| 2483 |
} |
| 2484 |
|
| 2485 |
// A destination with spare capacity full of stale data must decode the |
| 2486 |
// same way: grown slots start from zero. |
| 2487 |
stale := cart{Items: make([]item, 0, 64)} |
| 2488 |
full := stale.Items[:64] |
| 2489 |
for i := range full { |
| 2490 |
full[i] = item{Name: "stale", Price: -1} |
| 2491 |
} |
| 2492 |
if err := d.Decode(&stale, src); err != nil { |
| 2493 |
t.Fatal(err) |
| 2494 |
} |
| 2495 |
if len(stale.Items) != 50 { |
| 2496 |
t.Fatalf("len = %d, want 50", len(stale.Items)) |
| 2497 |
} |
| 2498 |
for i, it := range stale.Items { |
| 2499 |
if it.Name != "" || it.Price != i*3 { |
| 2500 |
t.Fatalf("Items[%d] = %+v, want zero Name and Price %d", i, it, i*3) |
| 2501 |
} |
| 2502 |
} |
| 2503 |
} |
| 2504 |
|
| 2505 |
// Growing a slice of structs reuses capacity this call reserved, but must |
| 2506 |
// never extend one the caller supplied: memory past its length may still be |
| 2507 |
// aliased by another of their slices. |
| 2508 |
func TestSliceGrowthDoesNotExtendCallerCapacity(t *testing.T) { |
| 2509 |
t.Parallel() |
| 2510 |
|
| 2511 |
type item struct { |
| 2512 |
V string `schema:"v"` |
| 2513 |
} |
| 2514 |
type cart struct { |
| 2515 |
Items []item `schema:"items"` |
| 2516 |
} |
| 2517 |
|
| 2518 |
backing := make([]item, 1, 8) |
| 2519 |
backing[0] = item{V: "keep"} |
| 2520 |
tail := backing[1:8:8] // the caller keeps an alias into the spare capacity |
| 2521 |
for i := range tail { |
| 2522 |
tail[i] = item{V: "alias"} |
| 2523 |
} |
| 2524 |
|
| 2525 |
c := cart{Items: backing} |
| 2526 |
d := NewDecoder() |
| 2527 |
if err := d.Decode(&c, map[string][]string{"items.3.v": {"new"}}); err != nil { |
| 2528 |
t.Fatal(err) |
| 2529 |
} |
| 2530 |
for i, got := range tail { |
| 2531 |
if got.V != "alias" { |
| 2532 |
t.Fatalf("caller's aliased element %d overwritten: %q", i, got.V) |
| 2533 |
} |
| 2534 |
} |
| 2535 |
if len(c.Items) != 4 || c.Items[0].V != "keep" || c.Items[3].V != "new" { |
| 2536 |
t.Fatalf("unexpected decode result: %+v", c.Items) |
| 2537 |
} |
| 2538 |
if c.Items[1].V != "" || c.Items[2].V != "" { |
| 2539 |
t.Fatalf("gap elements should be zero: %+v", c.Items) |
| 2540 |
} |
| 2541 |
} |
| 2542 |
|
| 2543 |
// The same struct type at two places in a tree means two different slices; |
| 2544 |
// growing one must never be mistaken for growing the other. |
| 2545 |
func TestSliceGrowthKeepsSiblingSlicesApart(t *testing.T) { |
| 2546 |
t.Parallel() |
| 2547 |
|
| 2548 |
type inner struct { |
| 2549 |
V string `schema:"v"` |
| 2550 |
} |
| 2551 |
type mid struct { |
| 2552 |
Items []inner `schema:"items"` |
| 2553 |
} |
| 2554 |
type outer struct { |
| 2555 |
X mid `schema:"x"` |
| 2556 |
Y mid `schema:"y"` |
| 2557 |
} |
| 2558 |
|
| 2559 |
d := NewDecoder() |
| 2560 |
for i := 0; i < 200; i++ { // map order varies, so repeat |
| 2561 |
var o outer |
| 2562 |
if err := d.Decode(&o, map[string][]string{ |
| 2563 |
"x.items.0.v": {"x0"}, |
| 2564 |
"x.items.4.v": {"x4"}, |
| 2565 |
"y.items.1.v": {"y1"}, |
| 2566 |
"y.items.2.v": {"y2"}, |
| 2567 |
}); err != nil { |
| 2568 |
t.Fatal(err) |
| 2569 |
} |
| 2570 |
if len(o.X.Items) != 5 || o.X.Items[0].V != "x0" || o.X.Items[4].V != "x4" { |
| 2571 |
t.Fatalf("X: %+v", o.X.Items) |
| 2572 |
} |
| 2573 |
if len(o.Y.Items) != 3 || o.Y.Items[1].V != "y1" || o.Y.Items[2].V != "y2" { |
| 2574 |
t.Fatalf("Y: %+v", o.Y.Items) |
| 2575 |
} |
| 2576 |
for _, e := range []string{o.X.Items[1].V, o.X.Items[2].V, o.X.Items[3].V, o.Y.Items[0].V} { |
| 2577 |
if e != "" { |
| 2578 |
t.Fatalf("gap element not zero: %+v %+v", o.X.Items, o.Y.Items) |
| 2579 |
} |
| 2580 |
} |
| 2581 |
} |
| 2582 |
} |
| 2583 |
|
| 2584 |
// Every index lands in the right element whatever order the map hands them |
| 2585 |
// over, with the gaps between them left zero. |
| 2586 |
func TestSliceGrowthFillsEveryIndex(t *testing.T) { |
| 2587 |
t.Parallel() |
| 2588 |
|
| 2589 |
type item struct { |
| 2590 |
Name string `schema:"name"` |
| 2591 |
Price int `schema:"price"` |
| 2592 |
} |
| 2593 |
type cart struct { |
| 2594 |
Items []item `schema:"items"` |
| 2595 |
} |
| 2596 |
|
| 2597 |
const n = 60 |
| 2598 |
src := map[string][]string{} |
| 2599 |
for i := 0; i < n; i += 2 { // leave every other index empty |
| 2600 |
idx := strconv.Itoa(i) |
| 2601 |
src["items."+idx+".name"] = []string{"n" + idx} |
| 2602 |
src["items."+idx+".price"] = []string{idx} |
| 2603 |
} |
| 2604 |
|
| 2605 |
d := NewDecoder() |
| 2606 |
for round := 0; round < 50; round++ { |
| 2607 |
var c cart |
| 2608 |
if err := d.Decode(&c, src); err != nil { |
| 2609 |
t.Fatal(err) |
| 2610 |
} |
| 2611 |
if len(c.Items) != n-1 { |
| 2612 |
t.Fatalf("len = %d, want %d", len(c.Items), n-1) |
| 2613 |
} |
| 2614 |
for i, got := range c.Items { |
| 2615 |
want := item{} |
| 2616 |
if i%2 == 0 { |
| 2617 |
want = item{Name: "n" + strconv.Itoa(i), Price: i} |
| 2618 |
} |
| 2619 |
if got != want { |
| 2620 |
t.Fatalf("element %d = %+v, want %+v", i, got, want) |
| 2621 |
} |
| 2622 |
} |
| 2623 |
} |
| 2624 |
} |
| 2625 |
|
| 2626 |
func BenchmarkSliceManyIndicesDecode(b *testing.B) { |
| 2627 |
type item struct { |
| 2628 |
Name string `schema:"name"` |
| 2629 |
Price int `schema:"price"` |
| 2630 |
} |
| 2631 |
type cart struct { |
| 2632 |
Items []item `schema:"items"` |
| 2633 |
} |
| 2634 |
src := map[string][]string{} |
| 2635 |
for i := 0; i < 100; i++ { |
| 2636 |
idx := strconv.Itoa(i) |
| 2637 |
src["items."+idx+".name"] = []string{"x"} |
| 2638 |
src["items."+idx+".price"] = []string{idx} |
| 2639 |
} |
| 2640 |
d := NewDecoder() |
| 2641 |
b.ReportAllocs() |
| 2642 |
for b.Loop() { |
| 2643 |
var c cart |
| 2644 |
if err := d.Decode(&c, src); err != nil { |
| 2645 |
b.Fatal(err) |
| 2646 |
} |
| 2647 |
} |
| 2648 |
} |
| 2649 |
|
| 2650 |
func TestDefaultValuesAreSet(t *testing.T) { |
| 2651 |
type N struct { |
| 2652 |
S1 string `schema:"s1,default:test1"` |
| 2653 |
I2 int `schema:"i2,default:22"` |
| 2654 |
R2 []float64 `schema:"r2,default:2|3.5|11.01"` |
| 2655 |
} |
| 2656 |
|
| 2657 |
type D struct { |
| 2658 |
N |
| 2659 |
S string `schema:"s,default:test1"` |
| 2660 |
I int `schema:"i,default:21"` |
| 2661 |
J int8 `schema:"j,default:2"` |
| 2662 |
K int16 `schema:"k,default:-455"` |
| 2663 |
L int32 `schema:"l,default:899"` |
| 2664 |
M int64 `schema:"m,default:12455"` |
| 2665 |
B bool `schema:"b,default:false"` |
| 2666 |
F float64 `schema:"f,default:3.14"` |
| 2667 |
G float32 `schema:"g,default:19.12"` |
| 2668 |
U uint `schema:"u,default:1"` |
| 2669 |
V uint8 `schema:"v,default:190"` |
| 2670 |
W uint16 `schema:"w,default:20000"` |
| 2671 |
Y uint32 `schema:"y,default:156666666"` |
| 2672 |
Z uint64 `schema:"z,default:1545465465465546"` |
| 2673 |
X []string `schema:"x,default:x1|x2"` |
| 2674 |
} |
| 2675 |
|
| 2676 |
data := map[string][]string{} |
| 2677 |
|
| 2678 |
d := D{} |
| 2679 |
|
| 2680 |
decoder := NewDecoder() |
| 2681 |
|
| 2682 |
if err := decoder.Decode(&d, data); err != nil { |
| 2683 |
t.Fatal("Error while decoding:", err) |
| 2684 |
} |
| 2685 |
|
| 2686 |
expected := D{ |
| 2687 |
N: N{ |
| 2688 |
S1: "test1", |
| 2689 |
I2: 22, |
| 2690 |
R2: []float64{2, 3.5, 11.01}, |
| 2691 |
}, |
| 2692 |
S: "test1", |
| 2693 |
I: 21, |
| 2694 |
J: 2, |
| 2695 |
K: -455, |
| 2696 |
L: 899, |
| 2697 |
M: 12455, |
| 2698 |
B: false, |
| 2699 |
F: 3.14, |
| 2700 |
G: 19.12, |
| 2701 |
U: 1, |
| 2702 |
V: 190, |
| 2703 |
W: 20000, |
| 2704 |
Y: 156666666, |
| 2705 |
Z: 1545465465465546, |
| 2706 |
X: []string{"x1", "x2"}, |
| 2707 |
} |
| 2708 |
|
| 2709 |
if !reflect.DeepEqual(expected, d) { |
| 2710 |
t.Errorf("Expected %v, got %v", expected, d) |
| 2711 |
} |
| 2712 |
|
| 2713 |
type P struct { |
| 2714 |
*N |
| 2715 |
S *string `schema:"s,default:test1"` |
| 2716 |
I *int `schema:"i,default:21"` |
| 2717 |
J *int8 `schema:"j,default:2"` |
| 2718 |
K *int16 `schema:"k,default:-455"` |
| 2719 |
L *int32 `schema:"l,default:899"` |
| 2720 |
M *int64 `schema:"m,default:12455"` |
| 2721 |
B *bool `schema:"b,default:false"` |
| 2722 |
F *float64 `schema:"f,default:3.14"` |
| 2723 |
G *float32 `schema:"g,default:19.12"` |
| 2724 |
U *uint `schema:"u,default:1"` |
| 2725 |
V *uint8 `schema:"v,default:190"` |
| 2726 |
W *uint16 `schema:"w,default:20000"` |
| 2727 |
Y *uint32 `schema:"y,default:156666666"` |
| 2728 |
Z *uint64 `schema:"z,default:1545465465465546"` |
| 2729 |
X []string `schema:"x,default:x1|x2"` |
| 2730 |
} |
| 2731 |
|
| 2732 |
p := P{N: &N{}} |
| 2733 |
|
| 2734 |
if err := decoder.Decode(&p, data); err != nil { |
| 2735 |
t.Fatal("Error while decoding:", err) |
| 2736 |
} |
| 2737 |
|
| 2738 |
vExpected := reflect.ValueOf(expected) |
| 2739 |
vActual := reflect.ValueOf(p) |
| 2740 |
|
| 2741 |
i := 0 |
| 2742 |
|
| 2743 |
for i < vExpected.NumField() { |
| 2744 |
if !reflect.DeepEqual(vExpected.Field(i).Interface(), reflect.Indirect(vActual.Field(i)).Interface()) { |
| 2745 |
t.Errorf("Expected %v, got %v", vExpected.Field(i).Interface(), reflect.Indirect(vActual.Field(i)).Interface()) |
| 2746 |
} |
| 2747 |
i++ |
| 2748 |
} |
| 2749 |
} |
| 2750 |
|
| 2751 |
func TestDefaultValuesAreIgnoredIfValuesAreProvided(t *testing.T) { |
| 2752 |
type D struct { |
| 2753 |
S string `schema:"s,default:test1"` |
| 2754 |
I int `schema:"i,default:21"` |
| 2755 |
B bool `schema:"b,default:false"` |
| 2756 |
F float64 `schema:"f,default:3.14"` |
| 2757 |
U uint `schema:"u,default:1"` |
| 2758 |
} |
| 2759 |
|
| 2760 |
data := map[string][]string{"s": {"s"}, "i": {"1"}, "b": {"true"}, "f": {"0.22"}, "u": {"14"}} |
| 2761 |
|
| 2762 |
d := D{} |
| 2763 |
|
| 2764 |
decoder := NewDecoder() |
| 2765 |
|
| 2766 |
if err := decoder.Decode(&d, data); err != nil { |
| 2767 |
t.Fatal("Error while decoding:", err) |
| 2768 |
} |
| 2769 |
|
| 2770 |
expected := D{ |
| 2771 |
S: "s", |
| 2772 |
I: 1, |
| 2773 |
B: true, |
| 2774 |
F: 0.22, |
| 2775 |
U: 14, |
| 2776 |
} |
| 2777 |
|
| 2778 |
if !reflect.DeepEqual(expected, d) { |
| 2779 |
t.Errorf("Expected %v, got %v", expected, d) |
| 2780 |
} |
| 2781 |
} |
| 2782 |
|
| 2783 |
func TestRequiredFieldsCannotHaveDefaults(t *testing.T) { |
| 2784 |
type D struct { |
| 2785 |
S string `schema:"s,required,default:test1"` |
| 2786 |
I int `schema:"i,required,default:21"` |
| 2787 |
B bool `schema:"b,required,default:false"` |
| 2788 |
F float64 `schema:"f,required,default:3.14"` |
| 2789 |
U uint `schema:"u,required,default:1"` |
| 2790 |
} |
| 2791 |
|
| 2792 |
data := map[string][]string{"s": {"s"}, "i": {"1"}, "b": {"true"}, "f": {"0.22"}, "u": {"14"}} |
| 2793 |
|
| 2794 |
d := D{} |
| 2795 |
|
| 2796 |
decoder := NewDecoder() |
| 2797 |
|
| 2798 |
err := decoder.Decode(&d, data) |
| 2799 |
|
| 2800 |
expected := "required fields cannot have a default value" |
| 2801 |
|
| 2802 |
if err == nil || !strings.Contains(err.Error(), expected) { |
| 2803 |
t.Errorf("decoding should fail with error msg %s got %q", expected, err) |
| 2804 |
} |
| 2805 |
} |
| 2806 |
|
| 2807 |
func TestNestedDefaultErrorsDoNotPanic(t *testing.T) { |
| 2808 |
assertNestedDefaultErrors := func(t *testing.T, err error) { |
| 2809 |
t.Helper() |
| 2810 |
|
| 2811 |
if err == nil { |
| 2812 |
t.Fatal("expected decode error") |
| 2813 |
} |
| 2814 |
|
| 2815 |
multiErr, ok := err.(MultiError) |
| 2816 |
if !ok { |
| 2817 |
t.Fatalf("expected MultiError, got %T: %v", err, err) |
| 2818 |
} |
| 2819 |
|
| 2820 |
var foundDefaultError bool |
| 2821 |
for _, itemErr := range multiErr { |
| 2822 |
if itemErr == nil { |
| 2823 |
continue |
| 2824 |
} |
| 2825 |
if itemErr.Error() == "required fields cannot have a default value" { |
| 2826 |
foundDefaultError = true |
| 2827 |
} |
| 2828 |
} |
| 2829 |
|
| 2830 |
if !foundDefaultError { |
| 2831 |
t.Fatalf("unexpected errors: %#v", multiErr) |
| 2832 |
} |
| 2833 |
} |
| 2834 |
|
| 2835 |
t.Run("struct field", func(t *testing.T) { |
| 2836 |
type Inner struct { |
| 2837 |
Value string `schema:"value,required,default:test"` |
| 2838 |
} |
| 2839 |
type Outer struct { |
| 2840 |
Inner Inner `schema:"inner"` |
| 2841 |
} |
| 2842 |
|
| 2843 |
var dst Outer |
| 2844 |
err := NewDecoder().Decode(&dst, map[string][]string{}) |
| 2845 |
assertNestedDefaultErrors(t, err) |
| 2846 |
}) |
| 2847 |
|
| 2848 |
t.Run("pointer field", func(t *testing.T) { |
| 2849 |
type Inner struct { |
| 2850 |
Value string `schema:"value,required,default:test"` |
| 2851 |
} |
| 2852 |
type Outer struct { |
| 2853 |
Inner *Inner `schema:"inner"` |
| 2854 |
} |
| 2855 |
|
| 2856 |
dst := Outer{Inner: &Inner{}} |
| 2857 |
err := NewDecoder().Decode(&dst, map[string][]string{}) |
| 2858 |
assertNestedDefaultErrors(t, err) |
| 2859 |
}) |
| 2860 |
} |
| 2861 |
|
| 2862 |
func TestUnsupportedDefaultTypeDoesNotPanic(t *testing.T) { |
| 2863 |
type D struct { |
| 2864 |
Value [1]string `schema:"value,default:test"` |
| 2865 |
} |
| 2866 |
|
| 2867 |
var dst D |
| 2868 |
err := NewDecoder().Decode(&dst, map[string][]string{}) |
| 2869 |
if err == nil { |
| 2870 |
t.Fatal("expected decode error") |
| 2871 |
} |
| 2872 |
|
| 2873 |
multiErr, ok := err.(MultiError) |
| 2874 |
if !ok { |
| 2875 |
t.Fatalf("expected MultiError, got %T: %v", err, err) |
| 2876 |
} |
| 2877 |
|
| 2878 |
itemErr := multiErr["default-Value"] |
| 2879 |
if itemErr == nil { |
| 2880 |
t.Fatalf("expected default-Value error, got %#v", multiErr) |
| 2881 |
} |
| 2882 |
|
| 2883 |
const want = "default option is supported only on: bool, float variants, string, unit variants types or their corresponding pointers or slices" |
| 2884 |
if itemErr.Error() != want { |
| 2885 |
t.Fatalf("expected %q, got %q", want, itemErr.Error()) |
| 2886 |
} |
| 2887 |
} |
| 2888 |
|
| 2889 |
func TestInvalidDefaultElementInSliceRaiseError(t *testing.T) { |
| 2890 |
type D struct { |
| 2891 |
A []int `schema:"a,default:0|notInt"` |
| 2892 |
B []bool `schema:"b,default:true|notInt"` |
| 2893 |
// //uint types |
| 2894 |
D []uint `schema:"d,default:1|notInt"` |
| 2895 |
E []uint8 `schema:"e,default:2|notInt"` |
| 2896 |
F []uint16 `schema:"f,default:3|notInt"` |
| 2897 |
G []uint32 `schema:"g,default:4|notInt"` |
| 2898 |
H []uint64 `schema:"h,default:5|notInt"` |
| 2899 |
// // int types |
| 2900 |
N []int `schema:"n,default:11|notInt"` |
| 2901 |
O []int8 `schema:"o,default:12|notInt"` |
| 2902 |
P []int16 `schema:"p,default:13|notInt"` |
| 2903 |
Q []int32 `schema:"q,default:14|notInt"` |
| 2904 |
R []int64 `schema:"r,default:15|notInt"` |
| 2905 |
// // float |
| 2906 |
X []float32 `schema:"c,default:2.2|notInt"` |
| 2907 |
Y []float64 `schema:"c,default:3.3|notInt"` |
| 2908 |
} |
| 2909 |
d := D{} |
| 2910 |
|
| 2911 |
data := map[string][]string{} |
| 2912 |
|
| 2913 |
decoder := NewDecoder() |
| 2914 |
|
| 2915 |
err := decoder.Decode(&d, data) |
| 2916 |
|
| 2917 |
if err == nil { |
| 2918 |
t.Error("if a different type exists, error should be raised") |
| 2919 |
} |
| 2920 |
|
| 2921 |
dType := reflect.TypeOf(d) |
| 2922 |
|
| 2923 |
e, ok := err.(MultiError) |
| 2924 |
if !ok || len(e) != dType.NumField() { |
| 2925 |
t.Errorf("Expected %d errors, got %#v", dType.NumField(), err) |
| 2926 |
} |
| 2927 |
|
| 2928 |
for i := 0; i < dType.NumField(); i++ { |
| 2929 |
v := dType.Field(i) |
| 2930 |
fieldKey := "default-" + string(v.Name) |
| 2931 |
errMsg := fmt.Sprintf("failed setting default: notInt is not compatible with field %s type", string(v.Name)) |
| 2932 |
ferr := e[fieldKey] |
| 2933 |
if strings.Compare(ferr.Error(), errMsg) != 0 { |
| 2934 |
t.Errorf("%s: expected %s, got %#v\n", fieldKey, ferr.Error(), errMsg) |
| 2935 |
} |
| 2936 |
} |
| 2937 |
} |
| 2938 |
|
| 2939 |
func TestInvalidDefaultsValuesHaveNoEffect(t *testing.T) { |
| 2940 |
type D struct { |
| 2941 |
B bool `schema:"b,default:invalid"` |
| 2942 |
C *float32 `schema:"c,default:notAFloat"` |
| 2943 |
// uint types |
| 2944 |
D uint `schema:"d,default:notUint"` |
| 2945 |
E uint8 `schema:"e,default:notUint"` |
| 2946 |
F uint16 `schema:"f,default:notUint"` |
| 2947 |
G uint32 `schema:"g,default:notUint"` |
| 2948 |
H uint64 `schema:"h,default:notUint"` |
| 2949 |
// uint types pointers |
| 2950 |
I *uint `schema:"i,default:notUint"` |
| 2951 |
J *uint8 `schema:"j,default:notUint"` |
| 2952 |
K *uint16 `schema:"k,default:notUint"` |
| 2953 |
L *uint32 `schema:"l,default:notUint"` |
| 2954 |
M *uint64 `schema:"m,default:notUint"` |
| 2955 |
// int types |
| 2956 |
N int `schema:"n,default:notInt"` |
| 2957 |
O int8 `schema:"o,default:notInt"` |
| 2958 |
P int16 `schema:"p,default:notInt"` |
| 2959 |
Q int32 `schema:"q,default:notInt"` |
| 2960 |
R int64 `schema:"r,default:notInt"` |
| 2961 |
// int types pointers |
| 2962 |
S *int `schema:"s,default:notInt"` |
| 2963 |
T *int8 `schema:"t,default:notInt"` |
| 2964 |
U *int16 `schema:"u,default:notInt"` |
| 2965 |
V *int32 `schema:"v,default:notInt"` |
| 2966 |
W *int64 `schema:"w,default:notInt"` |
| 2967 |
// float |
| 2968 |
X float32 `schema:"c,default:notAFloat"` |
| 2969 |
Y float64 `schema:"c,default:notAFloat"` |
| 2970 |
Z *float64 `schema:"c,default:notAFloat"` |
| 2971 |
} |
| 2972 |
|
| 2973 |
d := D{} |
| 2974 |
|
| 2975 |
expected := D{} |
| 2976 |
|
| 2977 |
data := map[string][]string{} |
| 2978 |
|
| 2979 |
decoder := NewDecoder() |
| 2980 |
|
| 2981 |
err := decoder.Decode(&d, data) |
| 2982 |
if err != nil { |
| 2983 |
t.Errorf("decoding should succeed but got error: %q", err) |
| 2984 |
} |
| 2985 |
|
| 2986 |
if !reflect.DeepEqual(expected, d) { |
| 2987 |
t.Errorf("expected %v but got %v", expected, d) |
| 2988 |
} |
| 2989 |
} |
| 2990 |
|
| 2991 |
func TestDefaultsAreNotSupportedForStructsAndStructSlices(t *testing.T) { |
| 2992 |
type C struct { |
| 2993 |
C string `schema:"c"` |
| 2994 |
} |
| 2995 |
|
| 2996 |
type D struct { |
| 2997 |
S S1 `schema:"s,default:{f1:0}"` |
| 2998 |
A []C `schema:"a,default:{c:test1}|{c:test2}"` |
| 2999 |
B []*int `schema:"b,default:12"` |
| 3000 |
E *C `schema:"e,default:{c:test3}"` |
| 3001 |
} |
| 3002 |
|
| 3003 |
d := D{} |
| 3004 |
|
| 3005 |
data := map[string][]string{} |
| 3006 |
|
| 3007 |
decoder := NewDecoder() |
| 3008 |
|
| 3009 |
err := decoder.Decode(&d, data) |
| 3010 |
|
| 3011 |
expected := "default option is supported only on: bool, float variants, string, unit variants types or their corresponding pointers or slices" |
| 3012 |
|
| 3013 |
if err == nil || !strings.Contains(err.Error(), expected) { |
| 3014 |
t.Errorf("decoding should fail with error msg %s got %q", expected, err) |
| 3015 |
} |
| 3016 |
} |
| 3017 |
|
| 3018 |
func TestDefaultValueWithColon(t *testing.T) { |
| 3019 |
t.Parallel() |
| 3020 |
type D struct { |
| 3021 |
URL string `schema:"url,default:http://localhost:8080"` |
| 3022 |
} |
| 3023 |
|
| 3024 |
var d D |
| 3025 |
decoder := NewDecoder() |
| 3026 |
if err := decoder.Decode(&d, map[string][]string{}); err != nil { |
| 3027 |
t.Fatalf("unexpected error: %v", err) |
| 3028 |
} |
| 3029 |
|
| 3030 |
if d.URL != "http://localhost:8080" { |
| 3031 |
t.Errorf("expected default url to be http://localhost:8080, got %s", d.URL) |
| 3032 |
} |
| 3033 |
} |
| 3034 |
|
| 3035 |
func TestDecoder_MaxSize(t *testing.T) { |
| 3036 |
t.Parallel() |
| 3037 |
|
| 3038 |
type Nested struct { |
| 3039 |
Val int |
| 3040 |
NestedValues []struct { |
| 3041 |
NVal int |
| 3042 |
} |
| 3043 |
} |
| 3044 |
type NestedSlices struct { |
| 3045 |
Values []Nested |
| 3046 |
} |
| 3047 |
|
| 3048 |
testcases := []struct { |
| 3049 |
name string |
| 3050 |
maxSize int |
| 3051 |
decoderInput func() (dst NestedSlices, src map[string][]string) |
| 3052 |
expectedDecoded NestedSlices |
| 3053 |
expectedErr MultiError |
| 3054 |
}{ |
| 3055 |
{ |
| 3056 |
name: "no error on decoding under max size", |
| 3057 |
maxSize: 10, |
| 3058 |
decoderInput: func() (dst NestedSlices, src map[string][]string) { |
| 3059 |
return dst, map[string][]string{ |
| 3060 |
"Values.1.Val": {"132"}, |
| 3061 |
"Values.1.NestedValues.1.NVal": {"1"}, |
| 3062 |
"Values.1.NestedValues.2.NVal": {"2"}, |
| 3063 |
"Values.1.NestedValues.3.NVal": {"3"}, |
| 3064 |
} |
| 3065 |
}, |
| 3066 |
expectedDecoded: NestedSlices{ |
| 3067 |
Values: []Nested{ |
| 3068 |
{ |
| 3069 |
Val: 0, |
| 3070 |
NestedValues: nil, |
| 3071 |
}, |
| 3072 |
{ |
| 3073 |
Val: 132, NestedValues: []struct{ NVal int }{ |
| 3074 |
{NVal: 0}, |
| 3075 |
{NVal: 1}, |
| 3076 |
{NVal: 2}, |
| 3077 |
{NVal: 3}, |
| 3078 |
}, |
| 3079 |
}, |
| 3080 |
}, |
| 3081 |
}, |
| 3082 |
expectedErr: nil, |
| 3083 |
}, |
| 3084 |
{ |
| 3085 |
name: "error on decoding above max size", |
| 3086 |
maxSize: 1, |
| 3087 |
decoderInput: func() (dst NestedSlices, src map[string][]string) { |
| 3088 |
return dst, map[string][]string{ |
| 3089 |
"Values.1.Val": {"132"}, |
| 3090 |
"Values.1.NestedValues.1.NVal": {"1"}, |
| 3091 |
"Values.1.NestedValues.2.NVal": {"2"}, |
| 3092 |
"Values.1.NestedValues.3.NVal": {"3"}, |
| 3093 |
} |
| 3094 |
}, |
| 3095 |
expectedErr: MultiError{ |
| 3096 |
"Values.1.NestedValues.2.NVal": errors.New("slice index 2 is larger than the configured maxSize 1"), |
| 3097 |
"Values.1.NestedValues.3.NVal": errors.New("slice index 3 is larger than the configured maxSize 1"), |
| 3098 |
}, |
| 3099 |
}, |
| 3100 |
} |
| 3101 |
|
| 3102 |
for _, tc := range testcases { |
| 3103 |
tc := tc |
| 3104 |
t.Run(tc.name, func(t *testing.T) { |
| 3105 |
t.Parallel() |
| 3106 |
dec := NewDecoder() |
| 3107 |
dec.MaxSize(tc.maxSize) |
| 3108 |
dst, src := tc.decoderInput() |
| 3109 |
err := dec.Decode(&dst, src) |
| 3110 |
|
| 3111 |
if tc.expectedErr != nil { |
| 3112 |
var gotErr MultiError |
| 3113 |
if !errors.As(err, &gotErr) { |
| 3114 |
t.Errorf("decoder error is not of type %T", gotErr) |
| 3115 |
} |
| 3116 |
if !reflect.DeepEqual(gotErr, tc.expectedErr) { |
| 3117 |
t.Errorf("expected %v, got %v", tc.expectedErr, gotErr) |
| 3118 |
} |
| 3119 |
} else { |
| 3120 |
if !reflect.DeepEqual(dst, tc.expectedDecoded) { |
| 3121 |
t.Errorf("expected %v, got %v", tc.expectedDecoded, dst) |
| 3122 |
} |
| 3123 |
} |
| 3124 |
}) |
| 3125 |
} |
| 3126 |
} |
| 3127 |
|
| 3128 |
func TestDefaultsAppliedOnlyWhenMissing(t *testing.T) { |
| 3129 |
t.Parallel() |
| 3130 |
|
| 3131 |
type Data struct { |
| 3132 |
B bool `schema:"b,default:true"` |
| 3133 |
I int `schema:"i,default:5"` |
| 3134 |
F float64 `schema:"f,default:1.5"` |
| 3135 |
S []int `schema:"s,default:1|2"` |
| 3136 |
} |
| 3137 |
|
| 3138 |
dec := NewDecoder() |
| 3139 |
|
| 3140 |
// Values are explicitly set – no defaults should be applied |
| 3141 |
withVals := Data{} |
| 3142 |
if err := dec.Decode(&withVals, map[string][]string{ |
| 3143 |
"b": {"false"}, |
| 3144 |
"i": {"0"}, |
| 3145 |
"f": {"0"}, |
| 3146 |
"s": {}, |
| 3147 |
}); err != nil { |
| 3148 |
t.Fatalf("unexpected error: %v", err) |
| 3149 |
} |
| 3150 |
if withVals.B { |
| 3151 |
t.Errorf("B should be false when the value is set") |
| 3152 |
} |
| 3153 |
if withVals.I != 0 { |
| 3154 |
t.Errorf("I should be 0 when the value is set, got %d", withVals.I) |
| 3155 |
} |
| 3156 |
if withVals.F != 0 { |
| 3157 |
t.Errorf("F should be 0 when the value is set, got %f", withVals.F) |
| 3158 |
} |
| 3159 |
if len(withVals.S) != 0 { |
| 3160 |
t.Errorf("S should be empty when the value is set, got %v", withVals.S) |
| 3161 |
} |
| 3162 |
|
| 3163 |
// No values provided – defaults should be applied |
| 3164 |
withoutVals := Data{} |
| 3165 |
if err := dec.Decode(&withoutVals, map[string][]string{}); err != nil { |
| 3166 |
t.Fatalf("unexpected error: %v", err) |
| 3167 |
} |
| 3168 |
if !withoutVals.B { |
| 3169 |
t.Errorf("B should default to true when missing") |
| 3170 |
} |
| 3171 |
if withoutVals.I != 5 { |
| 3172 |
t.Errorf("Default I should be 5, got %d", withoutVals.I) |
| 3173 |
} |
| 3174 |
if withoutVals.F != 1.5 { |
| 3175 |
t.Errorf("Default F should be 1.5, got %f", withoutVals.F) |
| 3176 |
} |
| 3177 |
if !reflect.DeepEqual(withoutVals.S, []int{1, 2}) { |
| 3178 |
t.Errorf("Default S should be [1 2], got %v", withoutVals.S) |
| 3179 |
} |
| 3180 |
} |
| 3181 |
|
| 3182 |
func TestDecoder_SetMaxSize(t *testing.T) { |
| 3183 |
t.Run("default maxsize should be equal to given constant", func(t *testing.T) { |
| 3184 |
t.Parallel() |
| 3185 |
dec := NewDecoder() |
| 3186 |
if !reflect.DeepEqual(dec.maxSize, defaultMaxSize) { |
| 3187 |
t.Errorf("unexpected default max size") |
| 3188 |
} |
| 3189 |
}) |
| 3190 |
|
| 3191 |
t.Run("configured maxsize should be set properly", func(t *testing.T) { |
| 3192 |
t.Parallel() |
| 3193 |
configuredMaxSize := 50 |
| 3194 |
limitedMaxSizeDecoder := NewDecoder() |
| 3195 |
limitedMaxSizeDecoder.MaxSize(configuredMaxSize) |
| 3196 |
if !reflect.DeepEqual(limitedMaxSizeDecoder.maxSize, configuredMaxSize) { |
| 3197 |
t.Errorf("invalid decoder maxsize, expected: %d, got: %d", |
| 3198 |
configuredMaxSize, limitedMaxSizeDecoder.maxSize) |
| 3199 |
} |
| 3200 |
}) |
| 3201 |
} |
| 3202 |
|
| 3203 |
func TestTimeDurationDecoding(t *testing.T) { |
| 3204 |
type DurationStruct struct { |
| 3205 |
Timeout time.Duration `schema:"timeout"` |
| 3206 |
} |
| 3207 |
|
| 3208 |
// Prepare the input data |
| 3209 |
input := map[string][]string{ |
| 3210 |
"timeout": {"2s"}, |
| 3211 |
} |
| 3212 |
|
| 3213 |
// Create a decoder with a converter for time.Duration |
| 3214 |
decoder := NewDecoder() |
| 3215 |
decoder.RegisterConverter(time.Duration(0), func(s string) reflect.Value { |
| 3216 |
d, err := time.ParseDuration(s) |
| 3217 |
if err != nil { |
| 3218 |
return reflect.Value{} |
| 3219 |
} |
| 3220 |
return reflect.ValueOf(d) |
| 3221 |
}) |
| 3222 |
|
| 3223 |
var result DurationStruct |
| 3224 |
err := decoder.Decode(&result, input) |
| 3225 |
if err != nil { |
| 3226 |
t.Fatalf("Failed to decode duration: %v", err) |
| 3227 |
} |
| 3228 |
|
| 3229 |
// Expect 2 seconds |
| 3230 |
if result.Timeout != 2*time.Second { |
| 3231 |
t.Errorf("Expected 2s, got %v", result.Timeout) |
| 3232 |
} |
| 3233 |
} |
| 3234 |
|
| 3235 |
func TestTimeDurationDecodingInvalid(t *testing.T) { |
| 3236 |
type DurationStruct struct { |
| 3237 |
Timeout time.Duration `schema:"timeout"` |
| 3238 |
} |
| 3239 |
|
| 3240 |
// Prepare the input data |
| 3241 |
input := map[string][]string{ |
| 3242 |
"timeout": {"invalid-duration"}, |
| 3243 |
} |
| 3244 |
|
| 3245 |
// Create a decoder with a converter for time.Duration |
| 3246 |
decoder := NewDecoder() |
| 3247 |
decoder.RegisterConverter(time.Duration(0), func(s string) reflect.Value { |
| 3248 |
// Attempt to parse the duration |
| 3249 |
d, err := time.ParseDuration(s) |
| 3250 |
if err != nil { |
| 3251 |
// Return an invalid reflect.Value to trigger a conversion error |
| 3252 |
return reflect.Value{} |
| 3253 |
} |
| 3254 |
return reflect.ValueOf(d) |
| 3255 |
}) |
| 3256 |
|
| 3257 |
var result DurationStruct |
| 3258 |
err := decoder.Decode(&result, input) |
| 3259 |
if err == nil { |
| 3260 |
t.Error("Expected an error decoding invalid duration, got nil") |
| 3261 |
} |
| 3262 |
} |
| 3263 |
|
| 3264 |
func TestMultipleConversionErrors(t *testing.T) { |
| 3265 |
type Fields struct { |
| 3266 |
IntField int `schema:"int_field"` |
| 3267 |
BoolField bool `schema:"bool_field"` |
| 3268 |
Duration time.Duration `schema:"duration_field"` |
| 3269 |
} |
| 3270 |
|
| 3271 |
input := map[string][]string{ |
| 3272 |
"int_field": {"invalid-int"}, |
| 3273 |
"bool_field": {"invalid-bool"}, |
| 3274 |
"duration_field": {"invalid-duration"}, |
| 3275 |
} |
| 3276 |
|
| 3277 |
decoder := NewDecoder() |
| 3278 |
decoder.RegisterConverter(time.Duration(0), func(s string) reflect.Value { |
| 3279 |
d, err := time.ParseDuration(s) |
| 3280 |
if err != nil { |
| 3281 |
return reflect.Value{} |
| 3282 |
} |
| 3283 |
return reflect.ValueOf(d) |
| 3284 |
}) |
| 3285 |
|
| 3286 |
var s Fields |
| 3287 |
err := decoder.Decode(&s, input) |
| 3288 |
if err == nil { |
| 3289 |
t.Fatal("Expected multiple conversion errors, got nil") |
| 3290 |
} |
| 3291 |
|
| 3292 |
// Check that all errors are reported (at least 3). |
| 3293 |
mErr, ok := err.(MultiError) |
| 3294 |
if !ok { |
| 3295 |
t.Fatalf("Expected MultiError, got %T", err) |
| 3296 |
} |
| 3297 |
if len(mErr) < 3 { |
| 3298 |
t.Errorf("Expected at least 3 errors, got %d: %v", len(mErr), mErr) |
| 3299 |
} |
| 3300 |
} |
| 3301 |
|
| 3302 |
func TestDecoderMultipartFiles(t *testing.T) { |
| 3303 |
type S struct { |
| 3304 |
A string `schema:"a,required"` |
| 3305 |
B int `schema:"b,required"` |
| 3306 |
C bool `schema:"c,required"` |
| 3307 |
D struct { |
| 3308 |
E float64 `schema:"e,required"` |
| 3309 |
F *multipart.FileHeader `schema:"f,required"` |
| 3310 |
F2 []*multipart.FileHeader `schema:"f2,required"` |
| 3311 |
F3 *[]*multipart.FileHeader `schema:"f3,required"` |
| 3312 |
F4 *multipart.FileHeader `schema:"f4,required"` |
| 3313 |
} `schema:"d,required"` |
| 3314 |
G *[]*multipart.FileHeader `schema:"g,required"` |
| 3315 |
J []struct { |
| 3316 |
K *[]*multipart.FileHeader `schema:"k,required"` |
| 3317 |
} `schema:"j,required"` |
| 3318 |
} |
| 3319 |
s := S{} |
| 3320 |
data := map[string][]string{ |
| 3321 |
"a": {"abc"}, |
| 3322 |
"b": {"123"}, |
| 3323 |
"c": {"true"}, |
| 3324 |
"d.e": {"3.14"}, |
| 3325 |
} |
| 3326 |
|
| 3327 |
// Create dummy file headers for testing |
| 3328 |
dummyFile := &multipart.FileHeader{ |
| 3329 |
Filename: "test.txt", |
| 3330 |
Size: 4, |
| 3331 |
} |
| 3332 |
|
| 3333 |
dummyFile2 := &multipart.FileHeader{ |
| 3334 |
Filename: "test2.txt", |
| 3335 |
Size: 4, |
| 3336 |
} |
| 3337 |
|
| 3338 |
dummyFile3 := &multipart.FileHeader{ |
| 3339 |
Filename: "test3.txt", |
| 3340 |
Size: 4, |
| 3341 |
} |
| 3342 |
|
| 3343 |
// Create slice for file headers |
| 3344 |
fileHeaders := map[string][]*multipart.FileHeader{ |
| 3345 |
"d.f": {dummyFile, dummyFile2}, |
| 3346 |
"d.f2": {dummyFile2, dummyFile3}, |
| 3347 |
"d.f3": {dummyFile, dummyFile2, dummyFile3}, |
| 3348 |
"d.f4": {}, |
| 3349 |
"g": {dummyFile, dummyFile2}, |
| 3350 |
"j.0.k": {dummyFile, dummyFile2}, |
| 3351 |
"j.1.k": {dummyFile2, dummyFile3}, |
| 3352 |
} |
| 3353 |
|
| 3354 |
decoder := NewDecoder() |
| 3355 |
err := decoder.Decode(&s, data, fileHeaders) |
| 3356 |
if err != nil { |
| 3357 |
t.Fatalf("Failed to decode: %v", err) |
| 3358 |
} |
| 3359 |
|
| 3360 |
if s.A != "abc" { |
| 3361 |
t.Errorf("Expected A to be 'abc', got %s", s.A) |
| 3362 |
} |
| 3363 |
|
| 3364 |
if s.B != 123 { |
| 3365 |
t.Errorf("Expected B to be 123, got %d", s.B) |
| 3366 |
} |
| 3367 |
|
| 3368 |
if s.C != true { |
| 3369 |
t.Errorf("Expected C to be true, got %t", s.C) |
| 3370 |
} |
| 3371 |
|
| 3372 |
if s.D.E != 3.14 { |
| 3373 |
t.Errorf("Expected D.E to be 3.14, got %f", s.D.E) |
| 3374 |
} |
| 3375 |
|
| 3376 |
if s.D.F == nil { |
| 3377 |
t.Error("Expected D.F to be a file header, got nil") |
| 3378 |
} |
| 3379 |
|
| 3380 |
if s.D.F2 == nil { |
| 3381 |
t.Error("Expected D.F2 to be a slice of file headers, got nil") |
| 3382 |
} |
| 3383 |
|
| 3384 |
if s.D.F3 == nil { |
| 3385 |
t.Error("Expected D.F3 to be a pointer to a slice of file headers, got nil") |
| 3386 |
} |
| 3387 |
|
| 3388 |
if s.D.F4 != nil { |
| 3389 |
fmt.Print(s.D.F4) |
| 3390 |
t.Error("Expected D.F4 to be nil, got a file header") |
| 3391 |
} |
| 3392 |
|
| 3393 |
if s.G == nil { |
| 3394 |
t.Error("Expected G to be a pointer to a slice of file headers, got nil") |
| 3395 |
} |
| 3396 |
|
| 3397 |
if len(s.D.F2) != 2 { |
| 3398 |
t.Errorf("Expected D.F2 to have 2 file headers, got %d", len(s.D.F2)) |
| 3399 |
} |
| 3400 |
|
| 3401 |
if len(*s.D.F3) != 3 { |
| 3402 |
t.Errorf("Expected D.F3 to have 3 file headers, got %d", len(*s.D.F3)) |
| 3403 |
} |
| 3404 |
|
| 3405 |
if len(*s.G) != 2 { |
| 3406 |
t.Errorf("Expected G to have 2 file headers, got %d", len(*s.G)) |
| 3407 |
} |
| 3408 |
|
| 3409 |
if s.D.F.Filename != "test.txt" { |
| 3410 |
t.Errorf("Expected D.F.Filename to be 'test.txt', got %s", s.D.F.Filename) |
| 3411 |
} |
| 3412 |
|
| 3413 |
if s.D.F2[0].Filename != "test2.txt" { |
| 3414 |
t.Errorf("Expected D.F2[0].Filename to be 'test2.txt', got %s", s.D.F2[0].Filename) |
| 3415 |
} |
| 3416 |
|
| 3417 |
if s.D.F2[1].Filename != "test3.txt" { |
| 3418 |
t.Errorf("Expected D.F2[1].Filename to be 'test3.txt', got %s", s.D.F2[1].Filename) |
| 3419 |
} |
| 3420 |
|
| 3421 |
if (*s.D.F3)[0].Filename != "test.txt" { |
| 3422 |
t.Errorf("Expected D.F3[0].Filename to be 'test.txt', got %s", (*s.D.F3)[0].Filename) |
| 3423 |
} |
| 3424 |
|
| 3425 |
if (*s.D.F3)[1].Filename != "test2.txt" { |
| 3426 |
t.Errorf("Expected D.F3[1].Filename to be 'test2.txt', got %s", (*s.D.F3)[1].Filename) |
| 3427 |
} |
| 3428 |
|
| 3429 |
if (*s.D.F3)[2].Filename != "test3.txt" { |
| 3430 |
t.Errorf("Expected D.F3[2].Filename to be 'test3.txt', got %s", (*s.D.F3)[2].Filename) |
| 3431 |
} |
| 3432 |
|
| 3433 |
if (*s.G)[0].Filename != "test.txt" { |
| 3434 |
t.Errorf("Expected G[0].Filename to be 'test.txt', got %s", (*s.G)[0].Filename) |
| 3435 |
} |
| 3436 |
|
| 3437 |
if (*s.G)[1].Filename != "test2.txt" { |
| 3438 |
t.Errorf("Expected G[1].Filename to be 'test2.txt', got %s", (*s.G)[1].Filename) |
| 3439 |
} |
| 3440 |
|
| 3441 |
if s.J[0].K == nil { |
| 3442 |
t.Error("Expected J[0].K to be a pointer to a slice of file headers, got nil") |
| 3443 |
} |
| 3444 |
|
| 3445 |
if s.J[1].K == nil { |
| 3446 |
t.Error("Expected J[1].K to be a pointer to a slice of file headers, got nil") |
| 3447 |
} |
| 3448 |
|
| 3449 |
if len(*s.J[0].K) != 2 { |
| 3450 |
t.Errorf("Expected J[0].K to have 2 file headers, got %d", len(*s.J[0].K)) |
| 3451 |
} |
| 3452 |
|
| 3453 |
if len(*s.J[1].K) != 2 { |
| 3454 |
t.Errorf("Expected J[1].K to have 2 file headers, got %d", len(*s.J[1].K)) |
| 3455 |
} |
| 3456 |
|
| 3457 |
if (*s.J[0].K)[0].Filename != "test.txt" { |
| 3458 |
t.Errorf("Expected J[0].K[0].Filename to be 'test.txt', got %s", (*s.J[0].K)[0].Filename) |
| 3459 |
} |
| 3460 |
|
| 3461 |
if (*s.J[0].K)[1].Filename != "test2.txt" { |
| 3462 |
t.Errorf("Expected J[0].K[1].Filename to be 'test2.txt', got %s", (*s.J[0].K)[1].Filename) |
| 3463 |
} |
| 3464 |
|
| 3465 |
if (*s.J[1].K)[0].Filename != "test2.txt" { |
| 3466 |
t.Errorf("Expected J[1].K[0].Filename to be 'test2.txt', got %s", (*s.J[1].K)[0].Filename) |
| 3467 |
} |
| 3468 |
|
| 3469 |
if (*s.J[1].K)[1].Filename != "test3.txt" { |
| 3470 |
t.Errorf("Expected J[1].K[1].Filename to be 'test3.txt', got %s", (*s.J[1].K)[1].Filename) |
| 3471 |
} |
| 3472 |
} |
| 3473 |
|
| 3474 |
func BenchmarkDecoderMultipartFiles(b *testing.B) { |
| 3475 |
type S struct { |
| 3476 |
A string `schema:"a,required"` |
| 3477 |
B int `schema:"b,required"` |
| 3478 |
C bool `schema:"c,required"` |
| 3479 |
D struct { |
| 3480 |
E float64 `schema:"e,required"` |
| 3481 |
F *multipart.FileHeader `schema:"f,required"` |
| 3482 |
F2 []*multipart.FileHeader `schema:"f2,required"` |
| 3483 |
} `schema:"d,required"` |
| 3484 |
G *[]*multipart.FileHeader `schema:"g,required"` |
| 3485 |
} |
| 3486 |
s := S{} |
| 3487 |
data := map[string][]string{ |
| 3488 |
"a": {"abc"}, |
| 3489 |
"b": {"123"}, |
| 3490 |
"c": {"true"}, |
| 3491 |
"d.e": {"3.14"}, |
| 3492 |
} |
| 3493 |
|
| 3494 |
// Create dummy file headers for testing |
| 3495 |
dummyFile := &multipart.FileHeader{ |
| 3496 |
Filename: "test.txt", |
| 3497 |
Size: 4, |
| 3498 |
} |
| 3499 |
|
| 3500 |
dummyFile2 := &multipart.FileHeader{ |
| 3501 |
Filename: "test2.txt", |
| 3502 |
Size: 4, |
| 3503 |
} |
| 3504 |
|
| 3505 |
dummyFile3 := &multipart.FileHeader{ |
| 3506 |
Filename: "test3.txt", |
| 3507 |
Size: 4, |
| 3508 |
} |
| 3509 |
|
| 3510 |
// Create slice for file headers |
| 3511 |
fileHeaders := map[string][]*multipart.FileHeader{ |
| 3512 |
"d.f": {dummyFile, dummyFile2}, |
| 3513 |
"d.f2": {dummyFile2, dummyFile3}, |
| 3514 |
"g": {dummyFile, dummyFile2}, |
| 3515 |
} |
| 3516 |
|
| 3517 |
decoder := NewDecoder() |
| 3518 |
var err error |
| 3519 |
for b.Loop() { |
| 3520 |
err = decoder.Decode(&s, data, fileHeaders) |
| 3521 |
} |
| 3522 |
|
| 3523 |
if err != nil { |
| 3524 |
b.Fatalf("Failed to decode: %v", err) |
| 3525 |
} |
| 3526 |
} |
| 3527 |
|
| 3528 |
func TestIsMultipartFile(t *testing.T) { |
| 3529 |
t.Parallel() |
| 3530 |
|
| 3531 |
tc := []struct { |
| 3532 |
typ reflect.Type |
| 3533 |
input map[string][]string |
| 3534 |
expected bool |
| 3535 |
}{ |
| 3536 |
{ |
| 3537 |
typ: reflect.TypeOf(string("")), |
| 3538 |
expected: false, |
| 3539 |
}, |
| 3540 |
{ |
| 3541 |
typ: reflect.TypeOf([]string{}), |
| 3542 |
expected: false, |
| 3543 |
}, |
| 3544 |
{ |
| 3545 |
typ: reflect.TypeOf([]*multipart.FileHeader{}), |
| 3546 |
expected: true, |
| 3547 |
}, |
| 3548 |
{ |
| 3549 |
typ: reflect.TypeOf(multipart.FileHeader{}), |
| 3550 |
expected: false, |
| 3551 |
}, |
| 3552 |
{ |
| 3553 |
typ: reflect.TypeOf(&multipart.FileHeader{}), |
| 3554 |
expected: true, |
| 3555 |
}, |
| 3556 |
{ |
| 3557 |
typ: reflect.TypeOf([]multipart.FileHeader{}), |
| 3558 |
expected: false, |
| 3559 |
}, |
| 3560 |
{ |
| 3561 |
typ: reflect.TypeOf(&[]*multipart.FileHeader{}), |
| 3562 |
expected: true, |
| 3563 |
}, |
| 3564 |
} |
| 3565 |
|
| 3566 |
for _, tt := range tc { |
| 3567 |
if isMultipartField(tt.typ) != tt.expected { |
| 3568 |
t.Errorf("Expected %v, got %v", tt.expected, isMultipartField(tt.typ)) |
| 3569 |
} |
| 3570 |
} |
| 3571 |
} |
| 3572 |
|
| 3573 |
func BenchmarkIsMultipartFile(b *testing.B) { |
| 3574 |
cases := []struct { |
| 3575 |
typ reflect.Type |
| 3576 |
}{ |
| 3577 |
{ |
| 3578 |
typ: reflect.TypeOf(string("")), |
| 3579 |
}, |
| 3580 |
{ |
| 3581 |
typ: reflect.TypeOf([]string{}), |
| 3582 |
}, |
| 3583 |
{ |
| 3584 |
typ: reflect.TypeOf([]*multipart.FileHeader{}), |
| 3585 |
}, |
| 3586 |
{ |
| 3587 |
typ: reflect.TypeOf(multipart.FileHeader{}), |
| 3588 |
}, |
| 3589 |
{ |
| 3590 |
typ: reflect.TypeOf(&multipart.FileHeader{}), |
| 3591 |
}, |
| 3592 |
{ |
| 3593 |
typ: reflect.TypeOf([]multipart.FileHeader{}), |
| 3594 |
}, |
| 3595 |
{ |
| 3596 |
typ: reflect.TypeOf(&[]*multipart.FileHeader{}), |
| 3597 |
}, |
| 3598 |
} |
| 3599 |
|
| 3600 |
for i, bc := range cases { |
| 3601 |
b.Run(fmt.Sprintf("IsMultipartFile-%d", i), func(b *testing.B) { |
| 3602 |
for b.Loop() { |
| 3603 |
isMultipartField(bc.typ) |
| 3604 |
} |
| 3605 |
}) |
| 3606 |
} |
| 3607 |
} |
| 3608 |
|
| 3609 |
func TestHandleMultipartField(t *testing.T) { |
| 3610 |
t.Parallel() |
| 3611 |
|
| 3612 |
// Create dummy file headers for testing |
| 3613 |
dummyFile := &multipart.FileHeader{ |
| 3614 |
Filename: "test.txt", |
| 3615 |
Size: 4, |
| 3616 |
} |
| 3617 |
|
| 3618 |
files := map[string][]*multipart.FileHeader{ |
| 3619 |
"f": {dummyFile}, |
| 3620 |
} |
| 3621 |
|
| 3622 |
type S struct { |
| 3623 |
F *multipart.FileHeader `schema:"f,required"` |
| 3624 |
F2 []*multipart.FileHeader `schema:"f2,required"` |
| 3625 |
F3 *[]*multipart.FileHeader `schema:"f3,required"` |
| 3626 |
F4 string `schema:"f4,required"` |
| 3627 |
} |
| 3628 |
|
| 3629 |
s := S{} |
| 3630 |
rv := reflect.ValueOf(&s).Elem() |
| 3631 |
|
| 3632 |
ok := handleMultipartField(rv.FieldByName("F"), files["f"]) |
| 3633 |
if !ok { |
| 3634 |
t.Error("Expected handleMultipartField to return true") |
| 3635 |
} |
| 3636 |
|
| 3637 |
ok = handleMultipartField(rv.FieldByName("F2"), files["f"]) |
| 3638 |
if !ok { |
| 3639 |
t.Error("Expected handleMultipartField to return true") |
| 3640 |
} |
| 3641 |
|
| 3642 |
ok = handleMultipartField(rv.FieldByName("F3"), files["f"]) |
| 3643 |
if !ok { |
| 3644 |
t.Error("Expected handleMultipartField to return true") |
| 3645 |
} |
| 3646 |
|
| 3647 |
ok = handleMultipartField(rv.FieldByName("F4"), files["f"]) |
| 3648 |
if ok { |
| 3649 |
t.Error("Expected handleMultipartField to return false") |
| 3650 |
} |
| 3651 |
|
| 3652 |
if s.F == nil { |
| 3653 |
t.Error("Expected F to be a file header, got nil") |
| 3654 |
} |
| 3655 |
|
| 3656 |
if s.F2 == nil { |
| 3657 |
t.Error("Expected F2 to be a slice of file headers, got nil") |
| 3658 |
} |
| 3659 |
|
| 3660 |
if s.F3 == nil { |
| 3661 |
t.Error("Expected F3 to be a pointer to a slice of file headers, got nil") |
| 3662 |
} |
| 3663 |
|
| 3664 |
if len(s.F2) != 1 { |
| 3665 |
t.Errorf("Expected F2 to have 1 file header, got %d", len(s.F2)) |
| 3666 |
} |
| 3667 |
|
| 3668 |
if len(*s.F3) != 1 { |
| 3669 |
t.Errorf("Expected F3 to have 1 file header, got %d", len(*s.F3)) |
| 3670 |
} |
| 3671 |
|
| 3672 |
if s.F.Filename != "test.txt" { |
| 3673 |
t.Errorf("Expected F.Filename to be 'test.txt', got %s", s.F.Filename) |
| 3674 |
} |
| 3675 |
|
| 3676 |
if s.F2[0].Filename != "test.txt" { |
| 3677 |
t.Errorf("Expected F2[0].Filename to be 'test.txt', got %s", s.F2[0].Filename) |
| 3678 |
} |
| 3679 |
|
| 3680 |
if (*s.F3)[0].Filename != "test.txt" { |
| 3681 |
t.Errorf("Expected F3[0].Filename to be 'test.txt', got %s", (*s.F3)[0].Filename) |
| 3682 |
} |
| 3683 |
} |
| 3684 |
|
| 3685 |
func TestDecodePanicIsCaughtAndReturnedAsError(t *testing.T) { |
| 3686 |
type R struct { |
| 3687 |
N1 []*struct { |
| 3688 |
Value string |
| 3689 |
} |
| 3690 |
} |
| 3691 |
// Simulate a path that uses an invalid (e.g. negative) slice index, |
| 3692 |
// which can trigger a panic (e.g. reflect: slice index out of range). |
| 3693 |
data := map[string][]string{ |
| 3694 |
"n1.-1.value": {"Foo"}, |
| 3695 |
} |
| 3696 |
|
| 3697 |
s := new(R) |
| 3698 |
decoder := NewDecoder() |
| 3699 |
err := decoder.Decode(s, data) |
| 3700 |
if err == nil { |
| 3701 |
t.Fatal("Expected an error when a panic occurs") |
| 3702 |
} |
| 3703 |
|
| 3704 |
expected := "schema: panic while decoding: reflect: slice index out of range" |
| 3705 |
if err.Error() != expected { |
| 3706 |
t.Fatalf("Expected panic error message %q, got: %v", expected, err) |
| 3707 |
} |
| 3708 |
} |
| 3709 |
|
| 3710 |
func TestDecodeIndexExceedsParserLimit(t *testing.T) { |
| 3711 |
type R struct { |
| 3712 |
N1 []*struct { |
| 3713 |
Value string |
| 3714 |
} |
| 3715 |
} |
| 3716 |
data := map[string][]string{ |
| 3717 |
"n1.1001.value": {"Foo"}, |
| 3718 |
} |
| 3719 |
|
| 3720 |
s := new(R) |
| 3721 |
decoder := NewDecoder() |
| 3722 |
err := decoder.Decode(s, data) |
| 3723 |
if err == nil { |
| 3724 |
t.Fatal("Expected an error when index exceeds parser limit") |
| 3725 |
} |
| 3726 |
|
| 3727 |
expected := MultiError{"n1.1001.value": errIndexTooLarge} |
| 3728 |
if !reflect.DeepEqual(err, expected) { |
| 3729 |
t.Fatalf("Expected %v, got: %v", expected, err) |
| 3730 |
} |
| 3731 |
} |
| 3732 |
|
| 3733 |
func BenchmarkHandleMultipartField(b *testing.B) { |
| 3734 |
// Create dummy file headers for testing |
| 3735 |
dummyFile := &multipart.FileHeader{ |
| 3736 |
Filename: "test.txt", |
| 3737 |
Size: 4, |
| 3738 |
} |
| 3739 |
|
| 3740 |
files := map[string][]*multipart.FileHeader{ |
| 3741 |
"f": {dummyFile}, |
| 3742 |
} |
| 3743 |
|
| 3744 |
type S struct { |
| 3745 |
F *multipart.FileHeader `schema:"f,required"` |
| 3746 |
F2 []*multipart.FileHeader `schema:"f2,required"` |
| 3747 |
F3 *[]*multipart.FileHeader `schema:"f3,required"` |
| 3748 |
F4 string `schema:"f4,required"` |
| 3749 |
} |
| 3750 |
|
| 3751 |
s := S{} |
| 3752 |
rv := reflect.ValueOf(&s).Elem() |
| 3753 |
|
| 3754 |
f := rv.FieldByName("F") |
| 3755 |
f2 := rv.FieldByName("F2") |
| 3756 |
f3 := rv.FieldByName("F3") |
| 3757 |
f4 := rv.FieldByName("F4") |
| 3758 |
|
| 3759 |
for b.Loop() { |
| 3760 |
handleMultipartField(f, files["f"]) |
| 3761 |
handleMultipartField(f2, files["f"]) |
| 3762 |
handleMultipartField(f3, files["f"]) |
| 3763 |
handleMultipartField(f4, files["f"]) |
| 3764 |
} |
| 3765 |
} |
| 3766 |
|
| 3767 |
func BenchmarkLargeStructDecode(b *testing.B) { |
| 3768 |
data := map[string][]string{ |
| 3769 |
"f1": {"Lorem"}, |
| 3770 |
"f2": {"Ipsum"}, |
| 3771 |
"f3": {"123"}, |
| 3772 |
"f4": {"456"}, |
| 3773 |
"f5": {"A", "B", "C", "D"}, |
| 3774 |
"f6": {"10", "20", "30", "40"}, |
| 3775 |
"f7": {"3.14159"}, |
| 3776 |
"f8": {"true"}, |
| 3777 |
"f9.n2": {"NestedStringValue"}, |
| 3778 |
} |
| 3779 |
|
| 3780 |
decoder := NewDecoder() |
| 3781 |
s := &LargeStructForBenchmark{} |
| 3782 |
for b.Loop() { |
| 3783 |
_ = decoder.Decode(s, data) |
| 3784 |
} |
| 3785 |
} |
| 3786 |
|
| 3787 |
func BenchmarkLargeStructDecodeParallel(b *testing.B) { |
| 3788 |
data := map[string][]string{ |
| 3789 |
"f1": {"Lorem"}, |
| 3790 |
"f2": {"Ipsum"}, |
| 3791 |
"f3": {"123"}, |
| 3792 |
"f4": {"456"}, |
| 3793 |
"f5": {"A", "B", "C", "D"}, |
| 3794 |
"f6": {"10", "20", "30", "40"}, |
| 3795 |
"f7": {"3.14159"}, |
| 3796 |
"f8": {"true"}, |
| 3797 |
"f9.n2": {"NestedStringValue"}, |
| 3798 |
} |
| 3799 |
|
| 3800 |
decoder := NewDecoder() |
| 3801 |
s := &LargeStructForBenchmark{} |
| 3802 |
b.ResetTimer() |
| 3803 |
|
| 3804 |
b.RunParallel(func(pb *testing.PB) { |
| 3805 |
for pb.Next() { |
| 3806 |
_ = decoder.Decode(s, data) |
| 3807 |
} |
| 3808 |
}) |
| 3809 |
} |
| 3810 |
|
| 3811 |
func BenchmarkSimpleStructDecode(b *testing.B) { |
| 3812 |
type S struct { |
| 3813 |
A string `schema:"a"` |
| 3814 |
B int `schema:"b"` |
| 3815 |
C bool `schema:"c"` |
| 3816 |
D float64 `schema:"d"` |
| 3817 |
E struct { |
| 3818 |
F float64 `schema:"f"` |
| 3819 |
} `schema:"e"` |
| 3820 |
} |
| 3821 |
s := S{} |
| 3822 |
data := map[string][]string{ |
| 3823 |
"a": {"abc"}, |
| 3824 |
"b": {"123"}, |
| 3825 |
"c": {"true"}, |
| 3826 |
"d": {"3.14"}, |
| 3827 |
"e.f": {"3.14"}, |
| 3828 |
} |
| 3829 |
decoder := NewDecoder() |
| 3830 |
for b.Loop() { |
| 3831 |
_ = decoder.Decode(&s, data) |
| 3832 |
} |
| 3833 |
} |
| 3834 |
|
| 3835 |
func BenchmarkCheckRequiredFields(b *testing.B) { |
| 3836 |
type S struct { |
| 3837 |
A string `schema:"a,required"` |
| 3838 |
B int `schema:"b,required"` |
| 3839 |
C bool `schema:"c,required"` |
| 3840 |
D struct { |
| 3841 |
E float64 `schema:"e,required"` |
| 3842 |
} `schema:"d,required"` |
| 3843 |
} |
| 3844 |
s := S{} |
| 3845 |
data := map[string][]string{ |
| 3846 |
"a": {"abc"}, |
| 3847 |
"b": {"123"}, |
| 3848 |
"c": {"true"}, |
| 3849 |
"d.e": {"3.14"}, |
| 3850 |
} |
| 3851 |
decoder := NewDecoder() |
| 3852 |
v := reflect.ValueOf(s) |
| 3853 |
// v = v.Elem() |
| 3854 |
info := decoder.cache.get(v.Type()) |
| 3855 |
|
| 3856 |
for b.Loop() { |
| 3857 |
_ = decoder.checkRequired(info, data) |
| 3858 |
} |
| 3859 |
} |
| 3860 |
|
| 3861 |
// referenceCheckRequired is the pre-rewrite required-field check: a linear |
| 3862 |
// scan of the whole source map per group and field path. The bitset and |
| 3863 |
// prefix index that replaced it must agree with it on every input. |
| 3864 |
func referenceCheckRequired(info *structInfo, src map[string][]string) map[string]bool { |
| 3865 |
missing := map[string]bool{} |
| 3866 |
for _, group := range info.requiredGroups { |
| 3867 |
empty := true |
| 3868 |
scan: |
| 3869 |
for _, f := range group.fields { |
| 3870 |
for i, path := range f.searchPaths { |
| 3871 |
if v, ok := src[path]; ok && !isEmpty(f.typ, v) { |
| 3872 |
empty = false |
| 3873 |
break scan |
| 3874 |
} |
| 3875 |
pathDot := f.searchPathDots[i] |
| 3876 |
for key, val := range src { |
| 3877 |
if len(val) == 0 { |
| 3878 |
continue |
| 3879 |
} |
| 3880 |
if strings.HasPrefix(key, pathDot) && !isEmpty(f.typ, val) { |
| 3881 |
empty = false |
| 3882 |
break scan |
| 3883 |
} |
| 3884 |
} |
| 3885 |
} |
| 3886 |
} |
| 3887 |
if empty { |
| 3888 |
missing[group.key] = true |
| 3889 |
} |
| 3890 |
} |
| 3891 |
return missing |
| 3892 |
} |
| 3893 |
|
| 3894 |
func TestCheckRequiredMatchesReference(t *testing.T) { |
| 3895 |
t.Parallel() |
| 3896 |
|
| 3897 |
type leaf struct { |
| 3898 |
X string `schema:"x,required"` |
| 3899 |
Y int `schema:"y"` |
| 3900 |
} |
| 3901 |
type mid struct { |
| 3902 |
L leaf `schema:"l,required"` |
| 3903 |
M string `schema:"m,required"` |
| 3904 |
} |
| 3905 |
type embedded struct { |
| 3906 |
E string `schema:"e,required"` |
| 3907 |
} |
| 3908 |
type outer struct { |
| 3909 |
embedded |
| 3910 |
A string `schema:"a,required"` |
| 3911 |
B []string `schema:"b,required"` |
| 3912 |
Mid mid `schema:"mid,required"` |
| 3913 |
Free string `schema:"free"` |
| 3914 |
} |
| 3915 |
type deep struct { |
| 3916 |
One mid `schema:"one,required"` |
| 3917 |
Two mid `schema:"two"` |
| 3918 |
} |
| 3919 |
|
| 3920 |
types := []reflect.Type{ |
| 3921 |
reflect.TypeOf(leaf{}), reflect.TypeOf(mid{}), |
| 3922 |
reflect.TypeOf(outer{}), reflect.TypeOf(deep{}), |
| 3923 |
} |
| 3924 |
|
| 3925 |
// Every key the shapes above can be addressed by, plus lookalikes. |
| 3926 |
keys := []string{ |
| 3927 |
"a", "b", "e", "free", "x", "y", "m", "l", "l.x", "l.y", |
| 3928 |
"mid", "mid.m", "mid.l", "mid.l.x", "mid.l.y", |
| 3929 |
"one", "one.m", "one.l.x", "two.m", "two.l.x", |
| 3930 |
"ab", "midx", "l.", "one.l", "unrelated", "a.b.c", |
| 3931 |
} |
| 3932 |
values := [][]string{nil, {}, {""}, {"v"}, {"", "v"}} |
| 3933 |
|
| 3934 |
d := NewDecoder() |
| 3935 |
r := rand.New(rand.NewPCG(11, 13)) |
| 3936 |
for _, typ := range types { |
| 3937 |
info := d.cache.get(typ) |
| 3938 |
for iter := 0; iter < 4000; iter++ { |
| 3939 |
src := make(map[string][]string) |
| 3940 |
for _, k := range keys { |
| 3941 |
switch r.IntN(4) { |
| 3942 |
case 0: |
| 3943 |
src[k] = values[r.IntN(len(values))] |
| 3944 |
case 1: |
| 3945 |
src[k] = values[len(values)-1] |
| 3946 |
} |
| 3947 |
} |
| 3948 |
want := referenceCheckRequired(info, src) |
| 3949 |
got := map[string]bool{} |
| 3950 |
for key := range d.checkRequired(info, src) { |
| 3951 |
got[key] = true |
| 3952 |
} |
| 3953 |
if len(got) != len(want) { |
| 3954 |
t.Fatalf("%s with %v: got missing %v, want %v", typ, src, got, want) |
| 3955 |
} |
| 3956 |
for key := range want { |
| 3957 |
if !got[key] { |
| 3958 |
t.Fatalf("%s with %v: got missing %v, want %v", typ, src, got, want) |
| 3959 |
} |
| 3960 |
} |
| 3961 |
} |
| 3962 |
} |
| 3963 |
} |
| 3964 |
|
| 3965 |
// requiredFormStruct mirrors a typical form payload: a few required scalars |
| 3966 |
// plus a required nested struct, which no direct lookup can settle. |
| 3967 |
type requiredAddress struct { |
| 3968 |
Street string `schema:"street,required"` |
| 3969 |
City string `schema:"city,required"` |
| 3970 |
Zip string `schema:"zip"` |
| 3971 |
} |
| 3972 |
|
| 3973 |
type requiredFormStruct struct { |
| 3974 |
Name string `schema:"name,required"` |
| 3975 |
Email string `schema:"email,required"` |
| 3976 |
Age int `schema:"age,required"` |
| 3977 |
Address requiredAddress `schema:"address,required"` |
| 3978 |
Note string `schema:"note"` |
| 3979 |
} |
| 3980 |
|
| 3981 |
// wideRequiredSrc carries the required fields plus the unrelated parameters a |
| 3982 |
// real query string comes with. |
| 3983 |
func wideRequiredSrc() map[string][]string { |
| 3984 |
src := map[string][]string{ |
| 3985 |
"name": {"Grace"}, |
| 3986 |
"email": {"[email protected]"}, |
| 3987 |
"age": {"85"}, |
| 3988 |
"address.street": {"1 Navy Yard"}, |
| 3989 |
"address.city": {"Arlington"}, |
| 3990 |
"address.zip": {"22202"}, |
| 3991 |
} |
| 3992 |
for i := 0; i < 20; i++ { |
| 3993 |
src["filter"+strconv.Itoa(i)] = []string{"v" + strconv.Itoa(i)} |
| 3994 |
} |
| 3995 |
return src |
| 3996 |
} |
| 3997 |
|
| 3998 |
func BenchmarkCheckRequiredFieldsWideSrc(b *testing.B) { |
| 3999 |
src := wideRequiredSrc() |
| 4000 |
decoder := NewDecoder() |
| 4001 |
info := decoder.cache.get(reflect.TypeOf(requiredFormStruct{})) |
| 4002 |
b.ReportAllocs() |
| 4003 |
for b.Loop() { |
| 4004 |
if errs := decoder.checkRequired(info, src); errs != nil { |
| 4005 |
b.Fatal(errs) |
| 4006 |
} |
| 4007 |
} |
| 4008 |
} |
| 4009 |
|
| 4010 |
// The same shape with a required key missing, so nothing short-circuits and |
| 4011 |
// every group has to be resolved. |
| 4012 |
func BenchmarkCheckRequiredFieldsWideSrcMissing(b *testing.B) { |
| 4013 |
src := wideRequiredSrc() |
| 4014 |
delete(src, "address.street") |
| 4015 |
delete(src, "address.city") |
| 4016 |
delete(src, "address.zip") |
| 4017 |
decoder := NewDecoder() |
| 4018 |
info := decoder.cache.get(reflect.TypeOf(requiredFormStruct{})) |
| 4019 |
b.ReportAllocs() |
| 4020 |
for b.Loop() { |
| 4021 |
if errs := decoder.checkRequired(info, src); errs == nil { |
| 4022 |
b.Fatal("expected missing required fields") |
| 4023 |
} |
| 4024 |
} |
| 4025 |
} |
| 4026 |
|
| 4027 |
func BenchmarkDecodeRequiredForm(b *testing.B) { |
| 4028 |
src := wideRequiredSrc() |
| 4029 |
decoder := NewDecoder() |
| 4030 |
decoder.IgnoreUnknownKeys(true) |
| 4031 |
s := &requiredFormStruct{} |
| 4032 |
b.ReportAllocs() |
| 4033 |
for b.Loop() { |
| 4034 |
if err := decoder.Decode(s, src); err != nil { |
| 4035 |
b.Fatal(err) |
| 4036 |
} |
| 4037 |
} |
| 4038 |
} |
| 4039 |
|
| 4040 |
// The fallbacks for keys too long for the stack buffers, the guards that only |
| 4041 |
// an extreme MaxSize can reach, and the walk that gives up behind an |
| 4042 |
// unsettable embedded pointer are all live paths; cover them here. |
| 4043 |
|
| 4044 |
// An alias longer than maxDirectKeyLen skips the fold, so a mixed-case key |
| 4045 |
// reaches the generic parser and resolves through the allocating lookup. |
| 4046 |
func TestLongAliasResolvesCaseInsensitively(t *testing.T) { |
| 4047 |
t.Parallel() |
| 4048 |
|
| 4049 |
const long = "averyveryverylongfieldaliasthatexceedssixtyfourbytesinlengthforsure" |
| 4050 |
if len(long) <= maxDirectKeyLen { |
| 4051 |
t.Fatalf("alias is %d bytes, must exceed %d for this test", len(long), maxDirectKeyLen) |
| 4052 |
} |
| 4053 |
type S struct { |
| 4054 |
V string `schema:"averyveryverylongfieldaliasthatexceedssixtyfourbytesinlengthforsure"` |
| 4055 |
} |
| 4056 |
var s S |
| 4057 |
if err := NewDecoder().Decode(&s, map[string][]string{strings.ToUpper(long): {"x"}}); err != nil { |
| 4058 |
t.Fatal(err) |
| 4059 |
} |
| 4060 |
if s.V != "x" { |
| 4061 |
t.Fatalf("V = %q, want x", s.V) |
| 4062 |
} |
| 4063 |
} |
| 4064 |
|
| 4065 |
// A prefixed key longer than the stack buffer falls back to concatenating, |
| 4066 |
// and the default must still see that the request provided the field. |
| 4067 |
func TestLongPrefixedKeySuppressesDefault(t *testing.T) { |
| 4068 |
t.Parallel() |
| 4069 |
|
| 4070 |
type inner struct { |
| 4071 |
AVeryLongFieldNameThatHelpsPushUsPastTheBuffer string `schema:"averylongfieldnamethathelpsuspastthebuffer,default:fallback"` |
| 4072 |
} |
| 4073 |
type outer struct { |
| 4074 |
AnEquallyLongNestedStructAlias inner `schema:"anequallylongnestedstructalias"` |
| 4075 |
} |
| 4076 |
const key = "anequallylongnestedstructalias.averylongfieldnamethathelpsuspastthebuffer" |
| 4077 |
if len(key) <= maxDirectKeyLen { |
| 4078 |
t.Fatalf("key is %d bytes, must exceed %d for this test", len(key), maxDirectKeyLen) |
| 4079 |
} |
| 4080 |
|
| 4081 |
d := NewDecoder() |
| 4082 |
var provided outer |
| 4083 |
if err := d.Decode(&provided, map[string][]string{key: {"given"}}); err != nil { |
| 4084 |
t.Fatal(err) |
| 4085 |
} |
| 4086 |
if got := provided.AnEquallyLongNestedStructAlias.AVeryLongFieldNameThatHelpsPushUsPastTheBuffer; got != "given" { |
| 4087 |
t.Fatalf("provided value = %q, want given", got) |
| 4088 |
} |
| 4089 |
|
| 4090 |
var absent outer |
| 4091 |
if err := d.Decode(&absent, map[string][]string{}); err != nil { |
| 4092 |
t.Fatal(err) |
| 4093 |
} |
| 4094 |
if got := absent.AnEquallyLongNestedStructAlias.AVeryLongFieldNameThatHelpsPushUsPastTheBuffer; got != "fallback" { |
| 4095 |
t.Fatalf("absent value = %q, want fallback", got) |
| 4096 |
} |
| 4097 |
} |
| 4098 |
|
| 4099 |
// growCap doubles the reservation, but maxSize+1 overflows at the extreme; |
| 4100 |
// the slice must still come out the length the indices call for. |
| 4101 |
func TestSliceGrowthWithExtremeMaxSize(t *testing.T) { |
| 4102 |
t.Parallel() |
| 4103 |
|
| 4104 |
type item struct { |
| 4105 |
V string `schema:"v"` |
| 4106 |
} |
| 4107 |
type cart struct { |
| 4108 |
Items []item `schema:"items"` |
| 4109 |
} |
| 4110 |
d := NewDecoder() |
| 4111 |
d.MaxSize(math.MaxInt) |
| 4112 |
|
| 4113 |
var c cart |
| 4114 |
if err := d.Decode(&c, map[string][]string{ |
| 4115 |
"items.0.v": {"a"}, |
| 4116 |
"items.5.v": {"f"}, |
| 4117 |
"items.2.v": {"c"}, |
| 4118 |
}); err != nil { |
| 4119 |
t.Fatal(err) |
| 4120 |
} |
| 4121 |
if len(c.Items) != 6 { |
| 4122 |
t.Fatalf("len = %d, want 6", len(c.Items)) |
| 4123 |
} |
| 4124 |
if c.Items[0].V != "a" || c.Items[2].V != "c" || c.Items[5].V != "f" { |
| 4125 |
t.Fatalf("unexpected result: %+v", c.Items) |
| 4126 |
} |
| 4127 |
if d.growCap(4, true) != 4 { |
| 4128 |
t.Fatalf("growCap must not return less than the length asked for") |
| 4129 |
} |
| 4130 |
} |
| 4131 |
|
| 4132 |
// checkRequired is also called for struct types that require nothing. |
| 4133 |
func TestCheckRequiredWithoutRequiredFields(t *testing.T) { |
| 4134 |
t.Parallel() |
| 4135 |
|
| 4136 |
type S struct { |
| 4137 |
A string `schema:"a"` |
| 4138 |
} |
| 4139 |
d := NewDecoder() |
| 4140 |
info := d.cache.get(reflect.TypeOf(S{})) |
| 4141 |
if errs := d.checkRequired(info, map[string][]string{"a": {"x"}}); errs != nil { |
| 4142 |
t.Fatalf("expected no errors, got %v", errs) |
| 4143 |
} |
| 4144 |
} |
| 4145 |
|
| 4146 |
// Past 256 required keys the satisfied-group bitset is allocated rather than |
| 4147 |
// taken from the inline array; every key must still be reported. |
| 4148 |
func TestCheckRequiredBeyondInlineBitset(t *testing.T) { |
| 4149 |
t.Parallel() |
| 4150 |
|
| 4151 |
const n = requiredBitWords*64 + 8 |
| 4152 |
fields := make([]reflect.StructField, 0, n) |
| 4153 |
for i := 0; i < n; i++ { |
| 4154 |
name := "F" + strconv.Itoa(i) |
| 4155 |
fields = append(fields, reflect.StructField{ |
| 4156 |
Name: name, |
| 4157 |
Type: reflect.TypeOf(""), |
| 4158 |
Tag: reflect.StructTag(`schema:"f` + strconv.Itoa(i) + `,required"`), |
| 4159 |
}) |
| 4160 |
} |
| 4161 |
typ := reflect.StructOf(fields) |
| 4162 |
|
| 4163 |
d := NewDecoder() |
| 4164 |
// Nothing provided: every required key is reported missing. |
| 4165 |
dst := reflect.New(typ) |
| 4166 |
err := d.Decode(dst.Interface(), map[string][]string{}) |
| 4167 |
multi, ok := err.(MultiError) |
| 4168 |
if !ok { |
| 4169 |
t.Fatalf("expected MultiError, got %#v", err) |
| 4170 |
} |
| 4171 |
if len(multi) != n { |
| 4172 |
t.Fatalf("got %d missing keys, want %d", len(multi), n) |
| 4173 |
} |
| 4174 |
|
| 4175 |
// All provided: nothing is reported. |
| 4176 |
src := make(map[string][]string, n) |
| 4177 |
for i := 0; i < n; i++ { |
| 4178 |
src["f"+strconv.Itoa(i)] = []string{"v"} |
| 4179 |
} |
| 4180 |
dst = reflect.New(typ) |
| 4181 |
if err := d.Decode(dst.Interface(), src); err != nil { |
| 4182 |
t.Fatalf("expected no errors, got %v", err) |
| 4183 |
} |
| 4184 |
if got := dst.Elem().Field(n - 1).String(); got != "v" { |
| 4185 |
t.Fatalf("last field = %q, want v", got) |
| 4186 |
} |
| 4187 |
} |
| 4188 |
|
| 4189 |
// A field promoted through an unexported embedded pointer cannot be reached: |
| 4190 |
// the pointer is nil and unsettable, so the walk stops and the key is a no-op. |
| 4191 |
func TestWalkStopsAtUnsettableEmbeddedPointer(t *testing.T) { |
| 4192 |
t.Parallel() |
| 4193 |
|
| 4194 |
var s unreachableOuter |
| 4195 |
d := NewDecoder() |
| 4196 |
d.IgnoreUnknownKeys(true) |
| 4197 |
if err := d.Decode(&s, map[string][]string{ |
| 4198 |
"nested.v": {"x"}, |
| 4199 |
"visible": {"seen"}, |
| 4200 |
}); err != nil { |
| 4201 |
t.Fatal(err) |
| 4202 |
} |
| 4203 |
if s.hiddenReach != nil { |
| 4204 |
t.Fatal("unexported embedded pointer must stay nil") |
| 4205 |
} |
| 4206 |
if s.Visible != "seen" { |
| 4207 |
t.Fatalf("Visible = %q, want seen", s.Visible) |
| 4208 |
} |
| 4209 |
} |
| 4210 |
|
| 4211 |
type reachInner struct { |
| 4212 |
V string `schema:"v"` |
| 4213 |
} |
| 4214 |
|
| 4215 |
type hiddenReach struct { |
| 4216 |
Nested reachInner `schema:"nested"` |
| 4217 |
} |
| 4218 |
|
| 4219 |
type unreachableOuter struct { |
| 4220 |
*hiddenReach |
| 4221 |
Visible string `schema:"visible"` |
| 4222 |
} |
| 4223 |
|
| 4224 |
// A typical listing request: pagination and sorting fields carry defaults, a |
| 4225 |
// nested filter struct carries its own, and the request supplies only some. |
| 4226 |
type defaultsPage struct { |
| 4227 |
Size int `schema:"size,default:20"` |
| 4228 |
Sort string `schema:"sort,default:created"` |
| 4229 |
Order string `schema:"order,default:desc"` |
| 4230 |
} |
| 4231 |
|
| 4232 |
type defaultsRequest struct { |
| 4233 |
Query string `schema:"q"` |
| 4234 |
Page defaultsPage `schema:"page"` |
| 4235 |
Verbose bool `schema:"verbose,default:false"` |
| 4236 |
Limit int `schema:"limit,default:100"` |
| 4237 |
Tags []string `schema:"tags,default:a|b"` |
| 4238 |
} |
| 4239 |
|
| 4240 |
// Defaults are resolved once per struct type, so what each Decode hands out |
| 4241 |
// must still be its own: a slice default mutated by one caller must not turn |
| 4242 |
// up in the next result, a pointer default must be a fresh pointee, and a |
| 4243 |
// nested struct's defaults must respect the keys provided under its prefix. |
| 4244 |
func TestDefaultsAreFreshPerDecode(t *testing.T) { |
| 4245 |
t.Parallel() |
| 4246 |
|
| 4247 |
d := NewDecoder() |
| 4248 |
src := map[string][]string{"q": {"shoes"}, "page.size": {"50"}, "limit": {"10"}} |
| 4249 |
|
| 4250 |
var first defaultsRequest |
| 4251 |
if err := d.Decode(&first, src); err != nil { |
| 4252 |
t.Fatal(err) |
| 4253 |
} |
| 4254 |
want := defaultsRequest{ |
| 4255 |
Query: "shoes", Page: defaultsPage{Size: 50, Sort: "created", Order: "desc"}, |
| 4256 |
Limit: 10, Tags: []string{"a", "b"}, |
| 4257 |
} |
| 4258 |
if first.Query != want.Query || first.Page != want.Page || first.Limit != want.Limit || |
| 4259 |
first.Verbose || len(first.Tags) != 2 || first.Tags[0] != "a" || first.Tags[1] != "b" { |
| 4260 |
t.Fatalf("first decode = %+v, want %+v", first, want) |
| 4261 |
} |
| 4262 |
|
| 4263 |
// Scribble over everything the first decode handed out. |
| 4264 |
first.Tags[0], first.Tags[1] = "x", "y" |
| 4265 |
first.Tags = append(first.Tags, "z") |
| 4266 |
|
| 4267 |
var second defaultsRequest |
| 4268 |
if err := d.Decode(&second, map[string][]string{}); err != nil { |
| 4269 |
t.Fatal(err) |
| 4270 |
} |
| 4271 |
if len(second.Tags) != 2 || second.Tags[0] != "a" || second.Tags[1] != "b" { |
| 4272 |
t.Fatalf("second decode saw the first caller's edits: %v", second.Tags) |
| 4273 |
} |
| 4274 |
if &second.Tags[0] == &first.Tags[0] { |
| 4275 |
t.Fatal("decoded slices share a backing array") |
| 4276 |
} |
| 4277 |
if second.Page != (defaultsPage{Size: 20, Sort: "created", Order: "desc"}) || second.Limit != 100 { |
| 4278 |
t.Fatalf("second decode = %+v", second) |
| 4279 |
} |
| 4280 |
|
| 4281 |
type ptrs struct { |
| 4282 |
N *int `schema:"n,default:7"` |
| 4283 |
S *string `schema:"s,default:hi"` |
| 4284 |
} |
| 4285 |
var p1, p2 ptrs |
| 4286 |
for _, p := range []*ptrs{&p1, &p2} { |
| 4287 |
if err := d.Decode(p, map[string][]string{}); err != nil { |
| 4288 |
t.Fatal(err) |
| 4289 |
} |
| 4290 |
} |
| 4291 |
if p1.N == p2.N || p1.S == p2.S { |
| 4292 |
t.Fatal("pointer defaults share a pointee") |
| 4293 |
} |
| 4294 |
*p1.N, *p1.S = 99, "changed" |
| 4295 |
var p3 ptrs |
| 4296 |
if err := d.Decode(&p3, map[string][]string{}); err != nil { |
| 4297 |
t.Fatal(err) |
| 4298 |
} |
| 4299 |
if *p3.N != 7 || *p3.S != "hi" { |
| 4300 |
t.Fatalf("pointer default saw the first caller's edits: %d %q", *p3.N, *p3.S) |
| 4301 |
} |
| 4302 |
} |
| 4303 |
|
| 4304 |
// A wide request struct in which only two fields carry defaults: the walk |
| 4305 |
// must not pay for the twenty-odd plain fields around them. |
| 4306 |
type defaultsWide struct { |
| 4307 |
F01, F02, F03, F04, F05, F06, F07, F08 string `schema:"f01"` |
| 4308 |
F09, F10, F11, F12, F13, F14, F15, F16 string `schema:"f09"` |
| 4309 |
F17, F18, F19, F20, F21, F22, F23, F24 int `schema:"f17"` |
| 4310 |
Size int `schema:"size,default:20"` |
| 4311 |
Sort string `schema:"sort,default:created"` |
| 4312 |
} |
| 4313 |
|
| 4314 |
func BenchmarkDecodeWithDefaultsWide(b *testing.B) { |
| 4315 |
src := map[string][]string{"f01": {"a"}, "f09": {"b"}, "f17": {"3"}} |
| 4316 |
d := NewDecoder() |
| 4317 |
b.ReportAllocs() |
| 4318 |
for b.Loop() { |
| 4319 |
var r defaultsWide |
| 4320 |
if err := d.Decode(&r, src); err != nil { |
| 4321 |
b.Fatal(err) |
| 4322 |
} |
| 4323 |
} |
| 4324 |
} |
| 4325 |
|
| 4326 |
func BenchmarkDecodeWithDefaults(b *testing.B) { |
| 4327 |
src := map[string][]string{ |
| 4328 |
"q": {"shoes"}, |
| 4329 |
"page.size": {"50"}, |
| 4330 |
"limit": {"10"}, |
| 4331 |
} |
| 4332 |
d := NewDecoder() |
| 4333 |
b.ReportAllocs() |
| 4334 |
for b.Loop() { |
| 4335 |
var r defaultsRequest |
| 4336 |
if err := d.Decode(&r, src); err != nil { |
| 4337 |
b.Fatal(err) |
| 4338 |
} |
| 4339 |
} |
| 4340 |
} |
| 4341 |
|
| 4342 |
func BenchmarkTimeDurationDecoding(b *testing.B) { |
| 4343 |
type DurationStruct struct { |
| 4344 |
Timeout time.Duration `schema:"timeout"` |
| 4345 |
} |
| 4346 |
|
| 4347 |
// Sample input for decoding |
| 4348 |
input := map[string][]string{ |
| 4349 |
"timeout": {"2s"}, |
| 4350 |
} |
| 4351 |
|
| 4352 |
decoder := NewDecoder() |
| 4353 |
decoder.RegisterConverter(time.Duration(0), func(s string) reflect.Value { |
| 4354 |
d, _ := time.ParseDuration(s) |
| 4355 |
return reflect.ValueOf(d) |
| 4356 |
}) |
| 4357 |
|
| 4358 |
var ds DurationStruct |
| 4359 |
for b.Loop() { |
| 4360 |
_ = decoder.Decode(&ds, input) |
| 4361 |
} |
| 4362 |
} |
| 4363 |
|
| 4364 |
func TestConversionErrorError(t *testing.T) { |
| 4365 |
t.Parallel() |
| 4366 |
e := ConversionError{Key: "f", Index: -1} |
| 4367 |
if got := e.Error(); got != "schema: error converting value for \"f\"" { |
| 4368 |
t.Errorf("unexpected message %q", got) |
| 4369 |
} |
| 4370 |
e = ConversionError{Key: "f", Index: 2, Err: errors.New("boom")} |
| 4371 |
msg := e.Error() |
| 4372 |
if !strings.Contains(msg, "index 2 of \"f\"") || !strings.Contains(msg, "boom") { |
| 4373 |
t.Errorf("unexpected message %q", msg) |
| 4374 |
} |
| 4375 |
} |
| 4376 |
|
| 4377 |
// The error messages are assembled by concatenation rather than fmt.Sprintf: |
| 4378 |
// quoting, index rendering and the wrapped-error suffix all have to stay |
| 4379 |
// byte-identical to the formatter they replaced. |
| 4380 |
func TestErrorMessagesMatchSprintf(t *testing.T) { |
| 4381 |
t.Parallel() |
| 4382 |
keys := []string{"", "f", "a.b.0.c", `we"ird`, "tab\there", "ünïcøde", "a\x00b"} |
| 4383 |
indices := []int{-1, 0, 1, 9, 99, 100, 1234567} |
| 4384 |
errs := []error{nil, errors.New("boom"), errors.New("")} |
| 4385 |
|
| 4386 |
for _, key := range keys { |
| 4387 |
for _, idx := range indices { |
| 4388 |
for _, inner := range errs { |
| 4389 |
want := "" |
| 4390 |
if idx < 0 { |
| 4391 |
want = fmt.Sprintf("schema: error converting value for %q", key) |
| 4392 |
} else { |
| 4393 |
want = fmt.Sprintf("schema: error converting value for index %d of %q", idx, key) |
| 4394 |
} |
| 4395 |
if inner != nil { |
| 4396 |
want = fmt.Sprintf("%s. Details: %s", want, inner) |
| 4397 |
} |
| 4398 |
if got := (ConversionError{Key: key, Index: idx, Err: inner}).Error(); got != want { |
| 4399 |
t.Fatalf("ConversionError(%q, %d, %v) = %q, want %q", key, idx, inner, got, want) |
| 4400 |
} |
| 4401 |
} |
| 4402 |
} |
| 4403 |
if got, want := (UnknownKeyError{Key: key}).Error(), fmt.Sprintf("schema: invalid path %q", key); got != want { |
| 4404 |
t.Fatalf("UnknownKeyError(%q) = %q, want %q", key, got, want) |
| 4405 |
} |
| 4406 |
if got, want := (EmptyFieldError{Key: key}).Error(), fmt.Sprintf("%v is empty", key); got != want { |
| 4407 |
t.Fatalf("EmptyFieldError(%q) = %q, want %q", key, got, want) |
| 4408 |
} |
| 4409 |
} |
| 4410 |
|
| 4411 |
// MultiError reports the count of the errors it does not render. |
| 4412 |
me := MultiError{} |
| 4413 |
for i := 0; i < 130; i++ { |
| 4414 |
me[strconv.Itoa(i)] = errors.New("only") |
| 4415 |
got := me.Error() |
| 4416 |
switch n := len(me); n { |
| 4417 |
case 1: |
| 4418 |
if got != "only" { |
| 4419 |
t.Fatalf("MultiError(1) = %q, want %q", got, "only") |
| 4420 |
} |
| 4421 |
case 2: |
| 4422 |
if got != "only (and 1 other error)" { |
| 4423 |
t.Fatalf("MultiError(2) = %q", got) |
| 4424 |
} |
| 4425 |
default: |
| 4426 |
if want := fmt.Sprintf("%s (and %d other errors)", "only", n-1); got != want { |
| 4427 |
t.Fatalf("MultiError(%d) = %q, want %q", n, got, want) |
| 4428 |
} |
| 4429 |
} |
| 4430 |
} |
| 4431 |
if got := (MultiError{}).Error(); got != "(0 errors)" { |
| 4432 |
t.Fatalf("MultiError(0) = %q", got) |
| 4433 |
} |
| 4434 |
} |
| 4435 |
|
| 4436 |
type sliceValue []byte |
| 4437 |
|
| 4438 |
func (sliceValue) UnmarshalText([]byte) error { return nil } |
| 4439 |
|
| 4440 |
type valueUM string |
| 4441 |
|
| 4442 |
func (valueUM) UnmarshalText([]byte) error { return nil } |
| 4443 |
|
| 4444 |
type ptrUM string |
| 4445 |
|
| 4446 |
func (*ptrUM) UnmarshalText([]byte) error { return nil } |
| 4447 |
|
| 4448 |
type elemUM struct{} |
| 4449 |
|
| 4450 |
func (*elemUM) UnmarshalText([]byte) error { return nil } |
| 4451 |
|
| 4452 |
func TestIsTextUnmarshaler(t *testing.T) { |
| 4453 |
t.Parallel() |
| 4454 |
cases := []struct { |
| 4455 |
name string |
| 4456 |
val interface{} |
| 4457 |
check func(t *testing.T, u unmarshaler) |
| 4458 |
}{ |
| 4459 |
{"value", valueUM(""), func(t *testing.T, u unmarshaler) { |
| 4460 |
if !u.IsValid || u.IsPtr { |
| 4461 |
t.Fatalf("wrong flags: %+v", u) |
| 4462 |
} |
| 4463 |
}}, |
| 4464 |
{"ptr", ptrUM(""), func(t *testing.T, u unmarshaler) { |
| 4465 |
if !u.IsValid || !u.IsPtr { |
| 4466 |
t.Fatalf("wrong flags: %+v", u) |
| 4467 |
} |
| 4468 |
}}, |
| 4469 |
{"sliceValue", sliceValue{}, func(t *testing.T, u unmarshaler) { |
| 4470 |
if !u.IsValid { |
| 4471 |
t.Fatalf("not valid") |
| 4472 |
} |
| 4473 |
}}, |
| 4474 |
{"sliceElemPtr", []*elemUM{}, func(t *testing.T, u unmarshaler) { |
| 4475 |
if !u.IsValid || !u.IsSliceElement || !u.IsSliceElementPtr { |
| 4476 |
t.Fatalf("wrong flags: %+v", u) |
| 4477 |
} |
| 4478 |
}}, |
| 4479 |
{"invalid", 42, func(t *testing.T, u unmarshaler) { |
| 4480 |
if u.IsValid { |
| 4481 |
t.Fatalf("expected invalid") |
| 4482 |
} |
| 4483 |
}}, |
| 4484 |
} |
| 4485 |
for _, c := range cases { |
| 4486 |
t.Run(c.name, func(t *testing.T) { |
| 4487 |
t.Parallel() |
| 4488 |
c.check(t, isTextUnmarshaler(reflect.ValueOf(c.val))) |
| 4489 |
}) |
| 4490 |
} |
| 4491 |
} |
| 4492 |
|
| 4493 |
func TestHandleMultipartFieldAdditional(t *testing.T) { |
| 4494 |
t.Parallel() |
| 4495 |
fh1 := &multipart.FileHeader{Filename: "f1"} |
| 4496 |
fh2 := &multipart.FileHeader{Filename: "f2"} |
| 4497 |
|
| 4498 |
var a *multipart.FileHeader |
| 4499 |
if !handleMultipartField(reflect.ValueOf(&a).Elem(), []*multipart.FileHeader{fh1}) || a != fh1 { |
| 4500 |
t.Errorf("single header not set") |
| 4501 |
} |
| 4502 |
|
| 4503 |
var b []*multipart.FileHeader |
| 4504 |
if !handleMultipartField(reflect.ValueOf(&b).Elem(), []*multipart.FileHeader{fh1, fh2}) || len(b) != 2 || b[1] != fh2 { |
| 4505 |
t.Errorf("slice headers not set") |
| 4506 |
} |
| 4507 |
|
| 4508 |
var c *[]*multipart.FileHeader |
| 4509 |
if !handleMultipartField(reflect.ValueOf(&c).Elem(), []*multipart.FileHeader{fh1}) || c == nil || len(*c) != 1 || (*c)[0] != fh1 { |
| 4510 |
t.Errorf("pointer slice not set") |
| 4511 |
} |
| 4512 |
|
| 4513 |
var d *multipart.FileHeader |
| 4514 |
if !handleMultipartField(reflect.ValueOf(&d).Elem(), nil) || d != nil { |
| 4515 |
t.Errorf("empty files not handled") |
| 4516 |
} |
| 4517 |
|
| 4518 |
x := 0 |
| 4519 |
if handleMultipartField(reflect.ValueOf(&x).Elem(), []*multipart.FileHeader{fh1}) { |
| 4520 |
t.Errorf("non multipart field handled") |
| 4521 |
} |
| 4522 |
} |
| 4523 |
|
| 4524 |
type unsupported struct { |
| 4525 |
C complex64 `schema:"c"` |
| 4526 |
} |
| 4527 |
|
| 4528 |
type textErr struct{} |
| 4529 |
|
| 4530 |
func (*textErr) UnmarshalText([]byte) error { return errors.New("bad") } |
| 4531 |
|
| 4532 |
type withSlice struct { |
| 4533 |
A []struct { |
| 4534 |
B int `schema:"b"` |
| 4535 |
} `schema:"a"` |
| 4536 |
} |
| 4537 |
|
| 4538 |
type withText struct { |
| 4539 |
T textErr `schema:"t"` |
| 4540 |
} |
| 4541 |
|
| 4542 |
type valueErrUM string |
| 4543 |
|
| 4544 |
func (valueErrUM) UnmarshalText([]byte) error { return errors.New("bad") } |
| 4545 |
|
| 4546 |
type sliceUM struct{} |
| 4547 |
|
| 4548 |
func (*sliceUM) UnmarshalText([]byte) error { return errors.New("bad") } |
| 4549 |
|
| 4550 |
type panicType int |
| 4551 |
|
| 4552 |
func TestDecodeErrors(t *testing.T) { |
| 4553 |
t.Parallel() |
| 4554 |
t.Run("invalid pointer", func(t *testing.T) { |
| 4555 |
t.Parallel() |
| 4556 |
var s unsupported |
| 4557 |
if err := NewDecoder().Decode(s, nil); err == nil { |
| 4558 |
t.Fatalf("expected error") |
| 4559 |
} |
| 4560 |
}) |
| 4561 |
|
| 4562 |
t.Run("panic converter", func(t *testing.T) { |
| 4563 |
t.Parallel() |
| 4564 |
dec := NewDecoder() |
| 4565 |
dec.RegisterConverter(panicType(0), func(string) reflect.Value { panic("boom") }) |
| 4566 |
var target struct { |
| 4567 |
P panicType `schema:"p"` |
| 4568 |
} |
| 4569 |
if err := dec.Decode(&target, map[string][]string{"p": {"x"}}); err == nil { |
| 4570 |
t.Fatalf("expected panic error") |
| 4571 |
} |
| 4572 |
}) |
| 4573 |
|
| 4574 |
t.Run("panic error converter", func(t *testing.T) { |
| 4575 |
t.Parallel() |
| 4576 |
dec := NewDecoder() |
| 4577 |
dec.RegisterConverter(panicType(0), func(string) reflect.Value { panic(errors.New("x")) }) |
| 4578 |
var target struct { |
| 4579 |
P panicType `schema:"p"` |
| 4580 |
} |
| 4581 |
if err := dec.Decode(&target, map[string][]string{"p": {"x"}}); err == nil { |
| 4582 |
t.Fatalf("expected panic error") |
| 4583 |
} |
| 4584 |
}) |
| 4585 |
|
| 4586 |
t.Run("unsupported type", func(t *testing.T) { |
| 4587 |
t.Parallel() |
| 4588 |
var u unsupported |
| 4589 |
if err := NewDecoder().Decode(&u, map[string][]string{"c": {"1"}}); err == nil { |
| 4590 |
t.Fatalf("expected error") |
| 4591 |
} |
| 4592 |
}) |
| 4593 |
|
| 4594 |
t.Run("text unmarshaler error", func(t *testing.T) { |
| 4595 |
t.Parallel() |
| 4596 |
var w withText |
| 4597 |
err := NewDecoder().Decode(&w, map[string][]string{"t": {"x"}}) |
| 4598 |
if err == nil { |
| 4599 |
t.Fatalf("expected error") |
| 4600 |
} |
| 4601 |
if _, ok := err.(MultiError)["t"].(ConversionError); !ok { |
| 4602 |
t.Fatalf("wrong error type: %v", err) |
| 4603 |
} |
| 4604 |
}) |
| 4605 |
|
| 4606 |
t.Run("index larger", func(t *testing.T) { |
| 4607 |
t.Parallel() |
| 4608 |
dec := NewDecoder() |
| 4609 |
dec.MaxSize(0) |
| 4610 |
var s withSlice |
| 4611 |
err := dec.Decode(&s, map[string][]string{"a.1.b": {"5"}}) |
| 4612 |
if err == nil || !strings.Contains(err.(MultiError)["a.1.b"].Error(), "maxSize") { |
| 4613 |
t.Fatalf("unexpected error: %v", err) |
| 4614 |
} |
| 4615 |
}) |
| 4616 |
|
| 4617 |
t.Run("slice converter missing", func(t *testing.T) { |
| 4618 |
t.Parallel() |
| 4619 |
var s struct { |
| 4620 |
C []complex64 `schema:"c"` |
| 4621 |
} |
| 4622 |
if err := NewDecoder().Decode(&s, map[string][]string{"c": {"1"}}); err == nil { |
| 4623 |
t.Fatalf("expected error") |
| 4624 |
} |
| 4625 |
}) |
| 4626 |
|
| 4627 |
t.Run("slice textunmarshal error", func(t *testing.T) { |
| 4628 |
t.Parallel() |
| 4629 |
var s struct { |
| 4630 |
S []sliceUM `schema:"s"` |
| 4631 |
} |
| 4632 |
if err := NewDecoder().Decode(&s, map[string][]string{"s": {"a"}}); err == nil { |
| 4633 |
t.Fatalf("expected error") |
| 4634 |
} |
| 4635 |
}) |
| 4636 |
|
| 4637 |
t.Run("value unmarshal error", func(t *testing.T) { |
| 4638 |
t.Parallel() |
| 4639 |
var s struct { |
| 4640 |
V valueErrUM `schema:"v"` |
| 4641 |
} |
| 4642 |
if err := NewDecoder().Decode(&s, map[string][]string{"v": {"a"}}); err == nil { |
| 4643 |
t.Fatalf("expected error") |
| 4644 |
} |
| 4645 |
}) |
| 4646 |
} |
| 4647 |
|
| 4648 |
func TestDecodeMultipartFiles(t *testing.T) { |
| 4649 |
type payload struct { |
| 4650 |
Single *multipart.FileHeader `schema:"single"` |
| 4651 |
Multiple []*multipart.FileHeader `schema:"multi"` |
| 4652 |
PtrSlice *[]*multipart.FileHeader `schema:"ptr"` |
| 4653 |
} |
| 4654 |
|
| 4655 |
fh1 := &multipart.FileHeader{Filename: "a"} |
| 4656 |
fh2 := &multipart.FileHeader{Filename: "b"} |
| 4657 |
|
| 4658 |
src := map[string][]string{} |
| 4659 |
files := map[string][]*multipart.FileHeader{ |
| 4660 |
"single": {fh1}, |
| 4661 |
"multi": {fh1, fh2}, |
| 4662 |
"ptr": {fh2}, |
| 4663 |
} |
| 4664 |
|
| 4665 |
var p payload |
| 4666 |
if err := NewDecoder().Decode(&p, src, files); err != nil { |
| 4667 |
t.Fatalf("unexpected error: %v", err) |
| 4668 |
} |
| 4669 |
if p.Single != fh1 { |
| 4670 |
t.Fatalf("single not set") |
| 4671 |
} |
| 4672 |
if len(p.Multiple) != 2 || p.Multiple[0] != fh1 || p.Multiple[1] != fh2 { |
| 4673 |
t.Fatalf("multi not set") |
| 4674 |
} |
| 4675 |
if p.PtrSlice == nil || len(*p.PtrSlice) != 1 || (*p.PtrSlice)[0] != fh2 { |
| 4676 |
t.Fatalf("ptr slice not set") |
| 4677 |
} |
| 4678 |
} |
| 4679 |
|
| 4680 |
func TestDecodeSliceTextUnmarshalerError(t *testing.T) { |
| 4681 |
type target struct { |
| 4682 |
B []rudeBool `schema:"b"` |
| 4683 |
} |
| 4684 |
|
| 4685 |
var s target |
| 4686 |
if err := NewDecoder().Decode(&s, map[string][]string{"b": {"maybe"}}); err == nil { |
| 4687 |
t.Fatalf("expected error") |
| 4688 |
} |
| 4689 |
} |
| 4690 |
|
| 4691 |
func TestDecodeCommaSeparatedZeroEmpty(t *testing.T) { |
| 4692 |
type target struct { |
| 4693 |
N []int `schema:"n"` |
| 4694 |
} |
| 4695 |
dec := NewDecoder() |
| 4696 |
dec.ZeroEmpty(true) |
| 4697 |
var s target |
| 4698 |
if err := dec.Decode(&s, map[string][]string{"n": {"1,,2"}}); err != nil { |
| 4699 |
t.Fatalf("unexpected error: %v", err) |
| 4700 |
} |
| 4701 |
if !reflect.DeepEqual(s.N, []int{1, 0, 2}) { |
| 4702 |
t.Fatalf("unexpected slice: %v", s.N) |
| 4703 |
} |
| 4704 |
} |
| 4705 |
|
| 4706 |
func TestDecodeCommaSeparatedPointerSlice(t *testing.T) { |
| 4707 |
type target struct { |
| 4708 |
N []*int `schema:"n"` |
| 4709 |
} |
| 4710 |
var s target |
| 4711 |
if err := NewDecoder().Decode(&s, map[string][]string{"n": {"1,2"}}); err != nil { |
| 4712 |
t.Fatalf("unexpected error: %v", err) |
| 4713 |
} |
| 4714 |
if len(s.N) != 2 || *s.N[0] != 1 || *s.N[1] != 2 { |
| 4715 |
t.Fatalf("unexpected values: %v %v", s.N[0], s.N[1]) |
| 4716 |
} |
| 4717 |
} |
| 4718 |
|
| 4719 |
func TestDecodeSliceReplacesPreviousValues(t *testing.T) { |
| 4720 |
type target struct { |
| 4721 |
N []int `schema:"n"` |
| 4722 |
} |
| 4723 |
|
| 4724 |
dec := NewDecoder() |
| 4725 |
var s target |
| 4726 |
|
| 4727 |
if err := dec.Decode(&s, map[string][]string{"n": {"1,2,3,4,5,6,7,8,9"}}); err != nil { |
| 4728 |
t.Fatalf("unexpected error: %v", err) |
| 4729 |
} |
| 4730 |
if !reflect.DeepEqual(s.N, []int{1, 2, 3, 4, 5, 6, 7, 8, 9}) { |
| 4731 |
t.Fatalf("unexpected initial slice: %v", s.N) |
| 4732 |
} |
| 4733 |
|
| 4734 |
if err := dec.Decode(&s, map[string][]string{"n": {"4"}}); err != nil { |
| 4735 |
t.Fatalf("unexpected error on second decode: %v", err) |
| 4736 |
} |
| 4737 |
if !reflect.DeepEqual(s.N, []int{4}) { |
| 4738 |
t.Fatalf("unexpected slice after second decode: %v", s.N) |
| 4739 |
} |
| 4740 |
} |
| 4741 |
|
| 4742 |
func TestDecodeCommaSeparatedAliasSliceError(t *testing.T) { |
| 4743 |
type target struct { |
| 4744 |
A []IntAlias `schema:"a"` |
| 4745 |
} |
| 4746 |
|
| 4747 |
var s target |
| 4748 |
if err := NewDecoder().Decode(&s, map[string][]string{"a": {"1,a"}}); err == nil { |
| 4749 |
t.Fatalf("expected error") |
| 4750 |
} |
| 4751 |
} |
| 4752 |
|
| 4753 |
func TestDecodeSliceErrorLeavesPooledBufferReusable(t *testing.T) { |
| 4754 |
type target struct { |
| 4755 |
N []int `schema:"n"` |
| 4756 |
} |
| 4757 |
|
| 4758 |
dec := NewDecoder() |
| 4759 |
var s target |
| 4760 |
|
| 4761 |
err := dec.Decode(&s, map[string][]string{"n": {"1,nope"}}) |
| 4762 |
if err == nil { |
| 4763 |
t.Fatal("expected error") |
| 4764 |
} |
| 4765 |
multi, ok := err.(MultiError) |
| 4766 |
if !ok { |
| 4767 |
t.Fatalf("unexpected error type: %T", err) |
| 4768 |
} |
| 4769 |
if _, ok := multi["n"].(ConversionError); !ok { |
| 4770 |
t.Fatalf("unexpected field error: %v", multi["n"]) |
| 4771 |
} |
| 4772 |
if strings.Contains(err.Error(), "panic") { |
| 4773 |
t.Fatalf("unexpected panic-style error: %v", err) |
| 4774 |
} |
| 4775 |
|
| 4776 |
if err := dec.Decode(&s, map[string][]string{"n": {"2,3"}}); err != nil { |
| 4777 |
t.Fatalf("unexpected error after failed decode: %v", err) |
| 4778 |
} |
| 4779 |
if !reflect.DeepEqual(s.N, []int{2, 3}) { |
| 4780 |
t.Fatalf("unexpected slice after retry: %v", s.N) |
| 4781 |
} |
| 4782 |
} |
| 4783 |
|
| 4784 |
func TestDecodeTextUnmarshalerSliceReplacesPreviousValues(t *testing.T) { |
| 4785 |
type target struct { |
| 4786 |
B []rudeBool `schema:"b"` |
| 4787 |
} |
| 4788 |
|
| 4789 |
dec := NewDecoder() |
| 4790 |
var s target |
| 4791 |
|
| 4792 |
if err := dec.Decode(&s, map[string][]string{"b": {"Yup", "Nope", "Yup", "Nope", "Yup", "Nope", "Yup", "Nope", "Yup"}}); err != nil { |
| 4793 |
t.Fatalf("unexpected error: %v", err) |
| 4794 |
} |
| 4795 |
if !reflect.DeepEqual(s.B, []rudeBool{true, false, true, false, true, false, true, false, true}) { |
| 4796 |
t.Fatalf("unexpected initial slice: %v", s.B) |
| 4797 |
} |
| 4798 |
|
| 4799 |
if err := dec.Decode(&s, map[string][]string{"b": {"Nope"}}); err != nil { |
| 4800 |
t.Fatalf("unexpected error on second decode: %v", err) |
| 4801 |
} |
| 4802 |
if !reflect.DeepEqual(s.B, []rudeBool{false}) { |
| 4803 |
t.Fatalf("unexpected slice after second decode: %v", s.B) |
| 4804 |
} |
| 4805 |
} |
| 4806 |
|
| 4807 |
// Malformed path keys must all surface as invalid-path/unknown-key errors, |
| 4808 |
// covering the parser's error branches including the SWAR word-scan hitting |
| 4809 |
// a separator at the segment start. |
| 4810 |
func TestDecodeMalformedPathKeys(t *testing.T) { |
| 4811 |
type Inner struct { |
| 4812 |
V string `schema:"v"` |
| 4813 |
} |
| 4814 |
type S struct { |
| 4815 |
A string `schema:"a"` |
| 4816 |
Items []Inner `schema:"items"` |
| 4817 |
} |
| 4818 |
for _, key := range []string{ |
| 4819 |
"", // empty key |
| 4820 |
".a", // leading separator |
| 4821 |
"a.", // trailing separator |
| 4822 |
"a..b", // empty middle segment |
| 4823 |
"..abcdefghij", // leading separator, long enough for the word scan |
| 4824 |
"items.", // slice index missing |
| 4825 |
"items.x.v", // slice index not a number |
| 4826 |
"items.0.", // trailing separator after index |
| 4827 |
"a.b", // path continues past a scalar field |
| 4828 |
"nope", // unknown field |
| 4829 |
} { |
| 4830 |
var s S |
| 4831 |
err := NewDecoder().Decode(&s, map[string][]string{key: {"x"}}) |
| 4832 |
if err == nil { |
| 4833 |
t.Errorf("key %q: expected error, got nil", key) |
| 4834 |
continue |
| 4835 |
} |
| 4836 |
me, ok := err.(MultiError) |
| 4837 |
if !ok { |
| 4838 |
t.Errorf("key %q: expected MultiError, got %T %v", key, err, err) |
| 4839 |
continue |
| 4840 |
} |
| 4841 |
if _, ok := me[key].(UnknownKeyError); !ok { |
| 4842 |
t.Errorf("key %q: expected UnknownKeyError, got %v", key, me[key]) |
| 4843 |
} |
| 4844 |
} |
| 4845 |
// With unknown keys ignored, the same keys must decode to no error. |
| 4846 |
for _, key := range []string{"", ".a", "a..b", "items.x.v"} { |
| 4847 |
var s S |
| 4848 |
dec := NewDecoder() |
| 4849 |
dec.IgnoreUnknownKeys(true) |
| 4850 |
if err := dec.Decode(&s, map[string][]string{key: {"x"}}); err != nil { |
| 4851 |
t.Errorf("key %q with IgnoreUnknownKeys: unexpected error %v", key, err) |
| 4852 |
} |
| 4853 |
} |
| 4854 |
} |
| 4855 |
|
| 4856 |
// Pointer-element slices exercise the pooled decode path: comma splitting, |
| 4857 |
// empty values with and without ZeroEmpty, and conversion errors. |
| 4858 |
func TestDecodePointerElemSlices(t *testing.T) { |
| 4859 |
type S struct { |
| 4860 |
P []*int `schema:"p"` |
| 4861 |
} |
| 4862 |
|
| 4863 |
deref := func(ps []*int) []int { |
| 4864 |
out := make([]int, len(ps)) |
| 4865 |
for i, p := range ps { |
| 4866 |
if p != nil { |
| 4867 |
out[i] = *p |
| 4868 |
} else { |
| 4869 |
out[i] = -999 |
| 4870 |
} |
| 4871 |
} |
| 4872 |
return out |
| 4873 |
} |
| 4874 |
|
| 4875 |
var s S |
| 4876 |
if err := NewDecoder().Decode(&s, map[string][]string{"p": {"1", "2,3", "4"}}); err != nil { |
| 4877 |
t.Fatal(err) |
| 4878 |
} |
| 4879 |
if got := deref(s.P); !reflect.DeepEqual(got, []int{1, 2, 3, 4}) { |
| 4880 |
t.Errorf("expected [1 2 3 4], got %v", got) |
| 4881 |
} |
| 4882 |
|
| 4883 |
s = S{} |
| 4884 |
if err := NewDecoder().Decode(&s, map[string][]string{"p": {"", "5"}}); err != nil { |
| 4885 |
t.Fatal(err) |
| 4886 |
} |
| 4887 |
if got := deref(s.P); !reflect.DeepEqual(got, []int{5}) { |
| 4888 |
t.Errorf("expected [5], got %v", got) |
| 4889 |
} |
| 4890 |
|
| 4891 |
// ZeroEmpty with pointer elements produces nil elements for empty items |
| 4892 |
// (this used to panic with "int is not assignable to *int"). |
| 4893 |
s = S{} |
| 4894 |
dec := NewDecoder() |
| 4895 |
dec.ZeroEmpty(true) |
| 4896 |
if err := dec.Decode(&s, map[string][]string{"p": {"", "6,,7"}}); err != nil { |
| 4897 |
t.Fatal(err) |
| 4898 |
} |
| 4899 |
if len(s.P) != 4 || s.P[0] != nil || *s.P[1] != 6 || s.P[2] != nil || *s.P[3] != 7 { |
| 4900 |
t.Errorf("unexpected zeroEmpty result: %v", deref(s.P)) |
| 4901 |
} |
| 4902 |
|
| 4903 |
for _, vals := range [][]string{{"x"}, {"1,x"}} { |
| 4904 |
s = S{} |
| 4905 |
err := NewDecoder().Decode(&s, map[string][]string{"p": vals}) |
| 4906 |
me, ok := err.(MultiError) |
| 4907 |
if !ok { |
| 4908 |
t.Errorf("values %v: expected MultiError, got %v", vals, err) |
| 4909 |
continue |
| 4910 |
} |
| 4911 |
if _, ok := me["p"].(ConversionError); !ok { |
| 4912 |
t.Errorf("values %v: expected ConversionError, got %v", vals, me["p"]) |
| 4913 |
} |
| 4914 |
} |
| 4915 |
} |
| 4916 |
|
| 4917 |
// Custom converters on slice element types route through the pooled path, |
| 4918 |
// including the comma-split fallback and its error cases. |
| 4919 |
func TestDecodeCustomConverterElemSlice(t *testing.T) { |
| 4920 |
type CV string |
| 4921 |
type S struct { |
| 4922 |
C []CV `schema:"c"` |
| 4923 |
} |
| 4924 |
dec := NewDecoder() |
| 4925 |
dec.RegisterConverter(CV(""), func(v string) reflect.Value { |
| 4926 |
if v == "bad" || strings.Contains(v, ",") { |
| 4927 |
return reflect.Value{} |
| 4928 |
} |
| 4929 |
// Returns the underlying kind, exercising the Convert-to-element |
| 4930 |
// branch of the pooled slice path. |
| 4931 |
return reflect.ValueOf("cv:" + v) |
| 4932 |
}) |
| 4933 |
|
| 4934 |
var s S |
| 4935 |
if err := dec.Decode(&s, map[string][]string{"c": {"a", "b,c"}}); err != nil { |
| 4936 |
t.Fatal(err) |
| 4937 |
} |
| 4938 |
if len(s.C) != 3 || s.C[0] != "cv:a" || s.C[1] != "cv:b" || s.C[2] != "cv:c" { |
| 4939 |
t.Errorf("unexpected result: %+v", s.C) |
| 4940 |
} |
| 4941 |
|
| 4942 |
s = S{} |
| 4943 |
err := dec.Decode(&s, map[string][]string{"c": {"bad"}}) |
| 4944 |
if err == nil { |
| 4945 |
t.Error("expected error for whole bad value") |
| 4946 |
} |
| 4947 |
|
| 4948 |
s = S{} |
| 4949 |
err = dec.Decode(&s, map[string][]string{"c": {"a,bad,c"}}) |
| 4950 |
if err == nil { |
| 4951 |
t.Error("expected error for bad comma item") |
| 4952 |
} |
| 4953 |
} |
| 4954 |
|
| 4955 |
func TestHandleMultipartFieldNonMultipart(t *testing.T) { |
| 4956 |
// Pointer fields that are not multipart shapes must fall through. |
| 4957 |
type S struct { |
| 4958 |
P *[]int |
| 4959 |
} |
| 4960 |
v := reflect.ValueOf(&S{}).Elem().Field(0) |
| 4961 |
files := []*multipart.FileHeader{{Filename: "f"}} |
| 4962 |
if handleMultipartField(v, files) { |
| 4963 |
t.Error("expected false for *[]int field") |
| 4964 |
} |
| 4965 |
if handleMultipartField(reflect.ValueOf(&S{}).Elem(), files) { |
| 4966 |
t.Error("expected false for struct field") |
| 4967 |
} |
| 4968 |
} |
| 4969 |
|
| 4970 |
func TestIsMultipartFieldShapes(t *testing.T) { |
| 4971 |
cases := []struct { |
| 4972 |
typ reflect.Type |
| 4973 |
want bool |
| 4974 |
}{ |
| 4975 |
{reflect.TypeOf(&multipart.FileHeader{}), true}, |
| 4976 |
{reflect.TypeOf([]*multipart.FileHeader{}), true}, |
| 4977 |
{reflect.TypeOf(&[]*multipart.FileHeader{}), true}, |
| 4978 |
{reflect.TypeOf(multipart.FileHeader{}), false}, |
| 4979 |
{reflect.TypeOf(0), false}, |
| 4980 |
{reflect.TypeOf(new(int)), false}, |
| 4981 |
{reflect.TypeOf([]int{}), false}, |
| 4982 |
} |
| 4983 |
for _, c := range cases { |
| 4984 |
if got := isMultipartField(c.typ); got != c.want { |
| 4985 |
t.Errorf("isMultipartField(%v) = %v, want %v", c.typ, got, c.want) |
| 4986 |
} |
| 4987 |
} |
| 4988 |
} |
| 4989 |
|
| 4990 |
func TestAppendErrorNil(t *testing.T) { |
| 4991 |
m := MultiError{"a": errors.New("a")} |
| 4992 |
if got := appendError(m, "b", nil); len(got) != 1 { |
| 4993 |
t.Errorf("nil error must not be appended: %v", got) |
| 4994 |
} |
| 4995 |
if got := appendError(nil, "b", nil); got != nil { |
| 4996 |
t.Errorf("nil error on nil map must return nil, got %v", got) |
| 4997 |
} |
| 4998 |
} |
| 4999 |
|
| 5000 |
// Struct fields containing arrays of pointers must be walked during cache |
| 5001 |
// building without dropping the surrounding struct's other fields. |
| 5002 |
func TestArrayOfPointersFieldWalk(t *testing.T) { |
| 5003 |
type S struct { |
| 5004 |
A [2]*int `schema:"a"` |
| 5005 |
B string `schema:"b"` |
| 5006 |
} |
| 5007 |
var s S |
| 5008 |
if err := NewDecoder().Decode(&s, map[string][]string{"b": {"ok"}}); err != nil { |
| 5009 |
t.Fatal(err) |
| 5010 |
} |
| 5011 |
if s.B != "ok" { |
| 5012 |
t.Errorf("expected ok, got %q", s.B) |
| 5013 |
} |
| 5014 |
} |
| 5015 |
|
| 5016 |
// Reconfiguring a decoder concurrently with Decode must never latch stale |
| 5017 |
// metadata: once SetAliasTag returns, subsequent decodes observe the new tag. |
| 5018 |
func TestDecoderReconfigureDuringDecode(t *testing.T) { |
| 5019 |
type T1 struct { |
| 5020 |
A string `schema:"schemaname" url:"urlname"` |
| 5021 |
} |
| 5022 |
for i := 0; i < 300; i++ { |
| 5023 |
d := NewDecoder() |
| 5024 |
done := make(chan struct{}) |
| 5025 |
go func() { |
| 5026 |
defer close(done) |
| 5027 |
var dst T1 |
| 5028 |
_ = d.Decode(&dst, map[string][]string{"schemaname": {"x"}}) |
| 5029 |
}() |
| 5030 |
d.SetAliasTag("url") |
| 5031 |
<-done |
| 5032 |
|
| 5033 |
var dst T1 |
| 5034 |
if err := d.Decode(&dst, map[string][]string{"urlname": {"y"}}); err != nil { |
| 5035 |
t.Fatalf("iteration %d: decode after SetAliasTag failed: %v", i, err) |
| 5036 |
} |
| 5037 |
if dst.A != "y" { |
| 5038 |
t.Fatalf("iteration %d: stale metadata: %+v", i, dst) |
| 5039 |
} |
| 5040 |
} |
| 5041 |
} |
| 5042 |
|
| 5043 |
// Concurrent decodes of the same fresh path exercise the parse cache's |
| 5044 |
// lost-race insertion path; results must be identical either way. |
| 5045 |
func TestConcurrentSamePathDecode(t *testing.T) { |
| 5046 |
type S struct { |
| 5047 |
A string `schema:"a"` |
| 5048 |
B int `schema:"b"` |
| 5049 |
} |
| 5050 |
for i := 0; i < 50; i++ { |
| 5051 |
d := NewDecoder() |
| 5052 |
var wg sync.WaitGroup |
| 5053 |
for g := 0; g < 4; g++ { |
| 5054 |
wg.Add(1) |
| 5055 |
go func() { |
| 5056 |
defer wg.Done() |
| 5057 |
var s S |
| 5058 |
if err := d.Decode(&s, map[string][]string{"a": {"x"}, "b": {"7"}}); err != nil { |
| 5059 |
t.Errorf("decode failed: %v", err) |
| 5060 |
} else if s.A != "x" || s.B != 7 { |
| 5061 |
t.Errorf("wrong result: %+v", s) |
| 5062 |
} |
| 5063 |
}() |
| 5064 |
} |
| 5065 |
wg.Wait() |
| 5066 |
} |
| 5067 |
} |
| 5068 |
|
| 5069 |
// Unexported embedded pointers are not settable; decoding must skip them |
| 5070 |
// instead of panicking, and sibling fields must still decode. |
| 5071 |
func TestUnexportedEmbeddedPointerSkipped(t *testing.T) { |
| 5072 |
type inner struct { |
| 5073 |
X string `schema:"x"` |
| 5074 |
} |
| 5075 |
type outer struct { |
| 5076 |
*inner |
| 5077 |
A string `schema:"a"` |
| 5078 |
} |
| 5079 |
var o outer |
| 5080 |
if err := NewDecoder().Decode(&o, map[string][]string{"a": {"ok"}}); err != nil { |
| 5081 |
t.Fatal(err) |
| 5082 |
} |
| 5083 |
if o.A != "ok" { |
| 5084 |
t.Errorf("sibling field not decoded: %+v", o) |
| 5085 |
} |
| 5086 |
if o.inner != nil { |
| 5087 |
t.Errorf("unsettable embedded pointer unexpectedly allocated") |
| 5088 |
} |
| 5089 |
|
| 5090 |
// Keys targeting fields promoted through the unsettable pointer are |
| 5091 |
// skipped silently once the path parses (the field exists in metadata). |
| 5092 |
// Default unknown-key behavior is used deliberately: if "x" ever fell |
| 5093 |
// out of the metadata, Decode would return an UnknownKeyError here. |
| 5094 |
var o2 outer |
| 5095 |
dec := NewDecoder() |
| 5096 |
if err := dec.Decode(&o2, map[string][]string{"x": {"v"}, "a": {"ok"}}); err != nil { |
| 5097 |
t.Fatal(err) |
| 5098 |
} |
| 5099 |
if o2.A != "ok" { |
| 5100 |
t.Errorf("sibling field not decoded: %+v", o2) |
| 5101 |
} |
| 5102 |
|
| 5103 |
// Defaults walks must also skip unreachable chains. |
| 5104 |
type outerDefaults struct { |
| 5105 |
*inner |
| 5106 |
B string `schema:"b,default:zz"` |
| 5107 |
} |
| 5108 |
var o3 outerDefaults |
| 5109 |
if err := NewDecoder().Decode(&o3, map[string][]string{}); err != nil { |
| 5110 |
t.Fatal(err) |
| 5111 |
} |
| 5112 |
if o3.B != "zz" { |
| 5113 |
t.Errorf("default not applied: %+v", o3) |
| 5114 |
} |
| 5115 |
} |
| 5116 |
|
| 5117 |
// A structInfo stored by a build that raced a reconfiguration carries the |
| 5118 |
// old generation and must never be served after the reconfiguration |
| 5119 |
// returned, even if it lands in the cache. |
| 5120 |
func TestDecoderStaleCacheEntryIgnored(t *testing.T) { |
| 5121 |
type T1 struct { |
| 5122 |
A string `schema:"schemaname" url:"urlname"` |
| 5123 |
} |
| 5124 |
d := NewDecoder() |
| 5125 |
typ := reflect.TypeOf(T1{}) |
| 5126 |
|
| 5127 |
var dst T1 |
| 5128 |
if err := d.Decode(&dst, map[string][]string{"schemaname": {"x"}}); err != nil { |
| 5129 |
t.Fatal(err) |
| 5130 |
} |
| 5131 |
staleEntry, ok := d.cache.m.Load(typ) |
| 5132 |
if !ok { |
| 5133 |
t.Fatal("expected cached structInfo") |
| 5134 |
} |
| 5135 |
|
| 5136 |
d.SetAliasTag("url") |
| 5137 |
// Simulate a delayed store from a build that raced the reconfiguration. |
| 5138 |
d.cache.m.Store(typ, staleEntry) |
| 5139 |
|
| 5140 |
dst = T1{} |
| 5141 |
if err := d.Decode(&dst, map[string][]string{"urlname": {"y"}}); err != nil { |
| 5142 |
t.Fatalf("stale entry served: %v", err) |
| 5143 |
} |
| 5144 |
if dst.A != "y" { |
| 5145 |
t.Fatalf("stale entry served: %+v", dst) |
| 5146 |
} |
| 5147 |
} |
| 5148 |
|
| 5149 |
// Registering converters concurrently with decoding must be safe and take |
| 5150 |
// effect once registration returns. |
| 5151 |
func TestDecoderRegisterConverterDuringDecode(t *testing.T) { |
| 5152 |
type CV string |
| 5153 |
type S struct { |
| 5154 |
C CV `schema:"c"` |
| 5155 |
A string `schema:"a"` |
| 5156 |
} |
| 5157 |
conv := func(v string) reflect.Value { return reflect.ValueOf(CV("conv:" + v)) } |
| 5158 |
for i := 0; i < 200; i++ { |
| 5159 |
d := NewDecoder() |
| 5160 |
done := make(chan error, 1) |
| 5161 |
go func() { |
| 5162 |
var s S |
| 5163 |
done <- d.Decode(&s, map[string][]string{"a": {"x"}}) |
| 5164 |
}() |
| 5165 |
d.RegisterConverter(CV(""), conv) |
| 5166 |
if err := <-done; err != nil { |
| 5167 |
t.Fatalf("iteration %d: concurrent decode failed: %v", i, err) |
| 5168 |
} |
| 5169 |
|
| 5170 |
var s S |
| 5171 |
if err := d.Decode(&s, map[string][]string{"c": {"v"}, "a": {"x"}}); err != nil { |
| 5172 |
t.Fatalf("iteration %d: %v", i, err) |
| 5173 |
} |
| 5174 |
if s.C != "conv:v" { |
| 5175 |
t.Fatalf("iteration %d: converter not effective: %+v", i, s) |
| 5176 |
} |
| 5177 |
} |
| 5178 |
} |
| 5179 |
|
| 5180 |
// Decoding with a nil src map and multipart files used to panic before the |
| 5181 |
// recovery handler was installed, crashing the caller. |
| 5182 |
func TestDecodeNilSrcWithMultipartFiles(t *testing.T) { |
| 5183 |
type S struct { |
| 5184 |
F *multipart.FileHeader `schema:"f"` |
| 5185 |
} |
| 5186 |
var s S |
| 5187 |
files := map[string][]*multipart.FileHeader{"f": {{Filename: "x"}}} |
| 5188 |
if err := NewDecoder().Decode(&s, nil, files); err != nil { |
| 5189 |
t.Fatal(err) |
| 5190 |
} |
| 5191 |
if s.F == nil || s.F.Filename != "x" { |
| 5192 |
t.Errorf("file not decoded: %+v", s.F) |
| 5193 |
} |
| 5194 |
|
| 5195 |
// Plain nil src still decodes to nothing without error. |
| 5196 |
type P struct { |
| 5197 |
A string `schema:"a"` |
| 5198 |
} |
| 5199 |
var p P |
| 5200 |
if err := NewDecoder().Decode(&p, nil); err != nil { |
| 5201 |
t.Fatal(err) |
| 5202 |
} |
| 5203 |
} |
| 5204 |
|
| 5205 |
type namedIntElem int |
| 5206 |
|
| 5207 |
type myStr string |
| 5208 |
|
| 5209 |
// Slices of pointers to named builtin types must decode without panicking: |
| 5210 |
// the converter yields the underlying kind, which must be Converted to the |
| 5211 |
// named element type before being stored into the *Named pointer. |
| 5212 |
func TestDecodeNamedPointerElemSlice(t *testing.T) { |
| 5213 |
type S struct { |
| 5214 |
P []*namedIntElem `schema:"p"` |
| 5215 |
PS []*myStr `schema:"ps"` |
| 5216 |
} |
| 5217 |
var s S |
| 5218 |
if err := NewDecoder().Decode(&s, map[string][]string{ |
| 5219 |
"p": {"1", "2,3"}, |
| 5220 |
"ps": {"a", "b"}, |
| 5221 |
}); err != nil { |
| 5222 |
t.Fatal(err) |
| 5223 |
} |
| 5224 |
if len(s.P) != 3 || *s.P[0] != 1 || *s.P[1] != 2 || *s.P[2] != 3 { |
| 5225 |
got := make([]namedIntElem, len(s.P)) |
| 5226 |
for i, p := range s.P { |
| 5227 |
got[i] = *p |
| 5228 |
} |
| 5229 |
t.Errorf("[]*namedIntElem: expected [1 2 3], got %v", got) |
| 5230 |
} |
| 5231 |
if len(s.PS) != 2 || *s.PS[0] != "a" || *s.PS[1] != "b" { |
| 5232 |
t.Errorf("[]*myStr: unexpected result %v", s.PS) |
| 5233 |
} |
| 5234 |
} |
| 5235 |
|
| 5236 |
// A required int16 or uint field submitted empty must be reported empty |
| 5237 |
// (isEmpty must cover every builtin kind the decoder accepts). |
| 5238 |
func TestRequiredInt16AndUintEmpty(t *testing.T) { |
| 5239 |
type S struct { |
| 5240 |
A int16 `schema:"a,required"` |
| 5241 |
B uint `schema:"b,required"` |
| 5242 |
C string `schema:"c,required"` |
| 5243 |
} |
| 5244 |
err := NewDecoder().Decode(&S{}, map[string][]string{ |
| 5245 |
"a": {""}, |
| 5246 |
"b": {""}, |
| 5247 |
"c": {""}, |
| 5248 |
}) |
| 5249 |
me, ok := err.(MultiError) |
| 5250 |
if !ok { |
| 5251 |
t.Fatalf("expected MultiError, got %T %v", err, err) |
| 5252 |
} |
| 5253 |
for _, key := range []string{"a", "b", "c"} { |
| 5254 |
if _, ok := me[key].(EmptyFieldError); !ok { |
| 5255 |
t.Errorf("required field %q empty value not reported: %v", key, me[key]) |
| 5256 |
} |
| 5257 |
} |
| 5258 |
} |
| 5259 |
|
| 5260 |
type ( |
| 5261 |
dfRole string |
| 5262 |
dfLevel int |
| 5263 |
dfFlag bool |
| 5264 |
dfRatio float64 |
| 5265 |
) |
| 5266 |
|
| 5267 |
// dfLevelPtr is a named pointer type: *int is NOT convertible to it, so the |
| 5268 |
// default must be built as a *dfLevel (which is assignable) rather than |
| 5269 |
// converted from a base-kind pointer. |
| 5270 |
type dfLevelPtr *dfLevel |
| 5271 |
|
| 5272 |
// Defaults on named types (scalar, pointer-to-named, and named-element slice) |
| 5273 |
// must be applied, not panic. The builtin converters return the underlying |
| 5274 |
// kind, which must be converted to the named target before Set/Append. |
| 5275 |
func TestDefaultsOnNamedTypes(t *testing.T) { |
| 5276 |
type S struct { |
| 5277 |
R dfRole `schema:"r,default:admin"` |
| 5278 |
L dfLevel `schema:"l,default:7"` |
| 5279 |
F dfFlag `schema:"f,default:true"` |
| 5280 |
X dfRatio `schema:"x,default:1.5"` |
| 5281 |
P *dfLevel `schema:"p,default:9"` |
| 5282 |
NP dfLevelPtr `schema:"np,default:12"` |
| 5283 |
SL []dfLevel `schema:"sl,default:1|2|3"` |
| 5284 |
SS []dfRole `schema:"ss,default:a|b"` |
| 5285 |
} |
| 5286 |
var s S |
| 5287 |
if err := NewDecoder().Decode(&s, map[string][]string{}); err != nil { |
| 5288 |
t.Fatalf("decode with named-type defaults failed: %v", err) |
| 5289 |
} |
| 5290 |
if s.R != "admin" { |
| 5291 |
t.Errorf("R: got %q want admin", s.R) |
| 5292 |
} |
| 5293 |
if s.L != 7 { |
| 5294 |
t.Errorf("L: got %d want 7", s.L) |
| 5295 |
} |
| 5296 |
if s.F != true { |
| 5297 |
t.Errorf("F: got %v want true", s.F) |
| 5298 |
} |
| 5299 |
if s.X != 1.5 { |
| 5300 |
t.Errorf("X: got %v want 1.5", s.X) |
| 5301 |
} |
| 5302 |
if s.P == nil || *s.P != 9 { |
| 5303 |
t.Errorf("P: got %v want *9", s.P) |
| 5304 |
} |
| 5305 |
if s.NP == nil || *s.NP != 12 { |
| 5306 |
t.Errorf("NP (named pointer type): got %v want *12", s.NP) |
| 5307 |
} |
| 5308 |
if len(s.SL) != 3 || s.SL[0] != 1 || s.SL[1] != 2 || s.SL[2] != 3 { |
| 5309 |
t.Errorf("SL: got %v want [1 2 3]", s.SL) |
| 5310 |
} |
| 5311 |
if len(s.SS) != 2 || s.SS[0] != "a" || s.SS[1] != "b" { |
| 5312 |
t.Errorf("SS: got %v want [a b]", s.SS) |
| 5313 |
} |
| 5314 |
} |
| 5315 |
|
| 5316 |
// Decode must not mutate the caller's src map when multipart files are |
| 5317 |
// passed: file keys are merged into an internal copy, and a caller-provided |
| 5318 |
// value under the same key stays intact in the caller's map. |
| 5319 |
func TestDecodeDoesNotMutateCallerSrc(t *testing.T) { |
| 5320 |
type S struct { |
| 5321 |
F *multipart.FileHeader `schema:"f"` |
| 5322 |
A string `schema:"a"` |
| 5323 |
} |
| 5324 |
src := map[string][]string{"a": {"x"}, "f": {"caller-value"}} |
| 5325 |
files := map[string][]*multipart.FileHeader{"f": {{Filename: "fn"}}} |
| 5326 |
|
| 5327 |
var s S |
| 5328 |
if err := NewDecoder().Decode(&s, src, files); err != nil { |
| 5329 |
t.Fatal(err) |
| 5330 |
} |
| 5331 |
if s.F == nil || s.F.Filename != "fn" { |
| 5332 |
t.Errorf("file not decoded: %+v", s.F) |
| 5333 |
} |
| 5334 |
if s.A != "x" { |
| 5335 |
t.Errorf("sibling not decoded: %+v", s) |
| 5336 |
} |
| 5337 |
if len(src) != 2 { |
| 5338 |
t.Errorf("caller src gained/lost keys: %v", src) |
| 5339 |
} |
| 5340 |
if got := src["f"]; len(got) != 1 || got[0] != "caller-value" { |
| 5341 |
t.Errorf("caller src value overwritten: %v", src["f"]) |
| 5342 |
} |
| 5343 |
|
| 5344 |
// File-only keys must not appear in the caller's map either. |
| 5345 |
src2 := map[string][]string{"a": {"y"}} |
| 5346 |
files2 := map[string][]*multipart.FileHeader{"g": {{Filename: "gn"}}} |
| 5347 |
type S2 struct { |
| 5348 |
G *multipart.FileHeader `schema:"g"` |
| 5349 |
A string `schema:"a"` |
| 5350 |
} |
| 5351 |
var s2 S2 |
| 5352 |
if err := NewDecoder().Decode(&s2, src2, files2); err != nil { |
| 5353 |
t.Fatal(err) |
| 5354 |
} |
| 5355 |
if s2.G == nil || s2.G.Filename != "gn" { |
| 5356 |
t.Errorf("file not decoded: %+v", s2.G) |
| 5357 |
} |
| 5358 |
if _, ok := src2["g"]; ok || len(src2) != 1 { |
| 5359 |
t.Errorf("caller src mutated with file key: %v", src2) |
| 5360 |
} |
| 5361 |
} |