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