| 1 | package schema |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "reflect" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | "time" |
| 9 | ) |
| 10 | |
| 11 | type E1 struct { |
| 12 | F01 int `schema:"f01"` |
| 13 | F02 int `schema:"-"` |
| 14 | F03 string `schema:"f03"` |
| 15 | F04 string `schema:"f04,omitempty"` |
| 16 | F05 bool `schema:"f05"` |
| 17 | F06 bool `schema:"f06"` |
| 18 | F07 *string `schema:"f07"` |
| 19 | F08 *int8 `schema:"f08"` |
| 20 | F09 float64 `schema:"f09"` |
| 21 | F10 func() `schema:"f10"` |
| 22 | F11 inner |
| 23 | } |
| 24 | type inner struct { |
| 25 | F12 int |
| 26 | } |
| 27 | |
| 28 | type SimpleStructForBenchmarkEncode struct { |
| 29 | A string `schema:"a"` |
| 30 | B int `schema:"b"` |
| 31 | C bool `schema:"c"` |
| 32 | D float64 `schema:"d"` |
| 33 | E struct { |
| 34 | F float64 `schema:"f"` |
| 35 | } `schema:"e"` |
| 36 | } |
| 37 | |
| 38 | func TestFilled(t *testing.T) { |
| 39 | f07 := "seven" |
| 40 | var f08 int8 = 8 |
| 41 | s := &E1{ |
| 42 | F01: 1, |
| 43 | F02: 2, |
| 44 | F03: "three", |
| 45 | F04: "four", |
| 46 | F05: true, |
| 47 | F06: false, |
| 48 | F07: &f07, |
| 49 | F08: &f08, |
| 50 | F09: 1.618, |
| 51 | F10: func() {}, |
| 52 | F11: inner{12}, |
| 53 | } |
| 54 | |
| 55 | vals := make(map[string][]string) |
| 56 | errs := NewEncoder().Encode(s, vals) |
| 57 | |
| 58 | valExists(t, "f01", "1", vals) |
| 59 | valNotExists(t, "f02", vals) |
| 60 | valExists(t, "f03", "three", vals) |
| 61 | valExists(t, "f05", "true", vals) |
| 62 | valExists(t, "f06", "false", vals) |
| 63 | valExists(t, "f07", "seven", vals) |
| 64 | valExists(t, "f08", "8", vals) |
| 65 | valExists(t, "f09", "1.618000", vals) |
| 66 | valExists(t, "F12", "12", vals) |
| 67 | |
| 68 | emptyErr := MultiError{} |
| 69 | if errs.Error() == emptyErr.Error() { |
| 70 | t.Errorf("Expected error got %v", errs) |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | type Aa int |
| 75 | |
| 76 | type E3 struct { |
| 77 | F01 bool `schema:"f01"` |
| 78 | F02 float32 `schema:"f02"` |
| 79 | F03 float64 `schema:"f03"` |
| 80 | F04 int `schema:"f04"` |
| 81 | F05 int8 `schema:"f05"` |
| 82 | F06 int16 `schema:"f06"` |
| 83 | F07 int32 `schema:"f07"` |
| 84 | F08 int64 `schema:"f08"` |
| 85 | F09 string `schema:"f09"` |
| 86 | F10 uint `schema:"f10"` |
| 87 | F11 uint8 `schema:"f11"` |
| 88 | F12 uint16 `schema:"f12"` |
| 89 | F13 uint32 `schema:"f13"` |
| 90 | F14 uint64 `schema:"f14"` |
| 91 | F15 Aa `schema:"f15"` |
| 92 | } |
| 93 | |
| 94 | // Test compatibility with default decoder types. |
| 95 | func TestCompat(t *testing.T) { |
| 96 | src := &E3{ |
| 97 | F01: true, |
| 98 | F02: 4.2, |
| 99 | F03: 4.3, |
| 100 | F04: -42, |
| 101 | F05: -43, |
| 102 | F06: -44, |
| 103 | F07: -45, |
| 104 | F08: -46, |
| 105 | F09: "foo", |
| 106 | F10: 42, |
| 107 | F11: 43, |
| 108 | F12: 44, |
| 109 | F13: 45, |
| 110 | F14: 46, |
| 111 | F15: 1, |
| 112 | } |
| 113 | dst := &E3{} |
| 114 | |
| 115 | vals := make(map[string][]string) |
| 116 | encoder := NewEncoder() |
| 117 | decoder := NewDecoder() |
| 118 | |
| 119 | encoder.RegisterEncoder(src.F15, func(reflect.Value) string { return "1" }) |
| 120 | decoder.RegisterConverter(src.F15, func(string) reflect.Value { return reflect.ValueOf(1) }) |
| 121 | |
| 122 | err := encoder.Encode(src, vals) |
| 123 | if err != nil { |
| 124 | t.Errorf("Encoder has non-nil error: %v", err) |
| 125 | } |
| 126 | err = decoder.Decode(dst, vals) |
| 127 | if err != nil { |
| 128 | t.Errorf("Decoder has non-nil error: %v", err) |
| 129 | } |
| 130 | |
| 131 | if *src != *dst { |
| 132 | t.Errorf("Decoder-Encoder compatibility: expected %v, got %v\n", src, dst) |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | func TestEmpty(t *testing.T) { |
| 137 | s := &E1{ |
| 138 | F01: 1, |
| 139 | F02: 2, |
| 140 | F03: "three", |
| 141 | } |
| 142 | |
| 143 | estr := "schema: encoder not found for <nil>" |
| 144 | vals := make(map[string][]string) |
| 145 | err := NewEncoder().Encode(s, vals) |
| 146 | if err.Error() != estr { |
| 147 | t.Errorf("Expected: %s, got %v", estr, err) |
| 148 | } |
| 149 | |
| 150 | valExists(t, "f03", "three", vals) |
| 151 | valNotExists(t, "f04", vals) |
| 152 | } |
| 153 | |
| 154 | func TestStruct(t *testing.T) { |
| 155 | estr := "schema: interface must be a struct" |
| 156 | vals := make(map[string][]string) |
| 157 | err := NewEncoder().Encode("hello world", vals) |
| 158 | |
| 159 | if err.Error() != estr { |
| 160 | t.Errorf("Expected: %s, got %v", estr, err) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | func TestSlices(t *testing.T) { |
| 165 | type oneAsWord int |
| 166 | ones := []oneAsWord{1, 2} |
| 167 | s1 := &struct { |
| 168 | ones []oneAsWord `schema:"ones"` |
| 169 | ints []int `schema:"ints"` |
| 170 | nonempty []int `schema:"nonempty"` |
| 171 | empty []int `schema:"empty,omitempty"` |
| 172 | }{ones, []int{1, 1}, []int{}, []int{}} |
| 173 | vals := make(map[string][]string) |
| 174 | |
| 175 | encoder := NewEncoder() |
| 176 | encoder.RegisterEncoder(ones[0], func(v reflect.Value) string { return "one" }) |
| 177 | err := encoder.Encode(s1, vals) |
| 178 | if err != nil { |
| 179 | t.Errorf("Encoder has non-nil error: %v", err) |
| 180 | } |
| 181 | |
| 182 | valsExist(t, "ones", []string{"one", "one"}, vals) |
| 183 | valsExist(t, "ints", []string{"1", "1"}, vals) |
| 184 | valsExist(t, "nonempty", []string{}, vals) |
| 185 | valNotExists(t, "empty", vals) |
| 186 | } |
| 187 | |
| 188 | func TestCompatSlices(t *testing.T) { |
| 189 | type oneAsWord int |
| 190 | type s1 struct { |
| 191 | Ones []oneAsWord `schema:"ones"` |
| 192 | Ints []int `schema:"ints"` |
| 193 | } |
| 194 | ones := []oneAsWord{1, 1} |
| 195 | src := &s1{ones, []int{1, 1}} |
| 196 | vals := make(map[string][]string) |
| 197 | dst := &s1{} |
| 198 | |
| 199 | encoder := NewEncoder() |
| 200 | encoder.RegisterEncoder(ones[0], func(v reflect.Value) string { return "one" }) |
| 201 | |
| 202 | decoder := NewDecoder() |
| 203 | decoder.RegisterConverter(ones[0], func(s string) reflect.Value { |
| 204 | if s == "one" { |
| 205 | return reflect.ValueOf(1) |
| 206 | } |
| 207 | return reflect.ValueOf(2) |
| 208 | }) |
| 209 | |
| 210 | err := encoder.Encode(src, vals) |
| 211 | if err != nil { |
| 212 | t.Errorf("Encoder has non-nil error: %v", err) |
| 213 | } |
| 214 | err = decoder.Decode(dst, vals) |
| 215 | if err != nil { |
| 216 | t.Errorf("Dncoder has non-nil error: %v", err) |
| 217 | } |
| 218 | |
| 219 | if len(src.Ints) != len(dst.Ints) || len(src.Ones) != len(dst.Ones) { |
| 220 | t.Fatalf("Expected %v, got %v", src, dst) |
| 221 | } |
| 222 | |
| 223 | for i, v := range src.Ones { |
| 224 | if dst.Ones[i] != v { |
| 225 | t.Fatalf("Expected %v, got %v", v, dst.Ones[i]) |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | for i, v := range src.Ints { |
| 230 | if dst.Ints[i] != v { |
| 231 | t.Fatalf("Expected %v, got %v", v, dst.Ints[i]) |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | func TestRegisterEncoder(t *testing.T) { |
| 237 | type oneAsWord int |
| 238 | type twoAsWord int |
| 239 | type oneSliceAsWord []int |
| 240 | |
| 241 | s1 := &struct { |
| 242 | oneAsWord |
| 243 | twoAsWord |
| 244 | oneSliceAsWord |
| 245 | }{1, 2, []int{1, 1}} |
| 246 | v1 := make(map[string][]string) |
| 247 | |
| 248 | encoder := NewEncoder() |
| 249 | encoder.RegisterEncoder(s1.oneAsWord, func(v reflect.Value) string { return "one" }) |
| 250 | encoder.RegisterEncoder(s1.twoAsWord, func(v reflect.Value) string { return "two" }) |
| 251 | encoder.RegisterEncoder(s1.oneSliceAsWord, func(v reflect.Value) string { return "one" }) |
| 252 | |
| 253 | err := encoder.Encode(s1, v1) |
| 254 | if err != nil { |
| 255 | t.Errorf("Encoder has non-nil error: %v", err) |
| 256 | } |
| 257 | |
| 258 | valExists(t, "oneAsWord", "one", v1) |
| 259 | valExists(t, "twoAsWord", "two", v1) |
| 260 | valExists(t, "oneSliceAsWord", "one", v1) |
| 261 | } |
| 262 | |
| 263 | func TestEncoderOrder(t *testing.T) { |
| 264 | type builtinEncoderSimple int |
| 265 | type builtinEncoderSimpleOverridden int |
| 266 | type builtinEncoderSlice []int |
| 267 | type builtinEncoderSliceOverridden []int |
| 268 | type builtinEncoderStruct struct{ nr int } |
| 269 | type builtinEncoderStructOverridden struct{ nr int } |
| 270 | |
| 271 | s1 := &struct { |
| 272 | builtinEncoderSimple `schema:"simple"` |
| 273 | builtinEncoderSimpleOverridden `schema:"simple_overridden"` |
| 274 | builtinEncoderSlice `schema:"slice"` |
| 275 | builtinEncoderSliceOverridden `schema:"slice_overridden"` |
| 276 | builtinEncoderStruct `schema:"struct"` |
| 277 | builtinEncoderStructOverridden `schema:"struct_overridden"` |
| 278 | }{ |
| 279 | 1, |
| 280 | 1, |
| 281 | []int{2}, |
| 282 | []int{2}, |
| 283 | builtinEncoderStruct{3}, |
| 284 | builtinEncoderStructOverridden{3}, |
| 285 | } |
| 286 | v1 := make(map[string][]string) |
| 287 | |
| 288 | encoder := NewEncoder() |
| 289 | encoder.RegisterEncoder(s1.builtinEncoderSimpleOverridden, func(v reflect.Value) string { return "one" }) |
| 290 | encoder.RegisterEncoder(s1.builtinEncoderSliceOverridden, func(v reflect.Value) string { return "two" }) |
| 291 | encoder.RegisterEncoder(s1.builtinEncoderStructOverridden, func(v reflect.Value) string { return "three" }) |
| 292 | |
| 293 | err := encoder.Encode(s1, v1) |
| 294 | if err != nil { |
| 295 | t.Errorf("Encoder has non-nil error: %v", err) |
| 296 | } |
| 297 | |
| 298 | valExists(t, "simple", "1", v1) |
| 299 | valExists(t, "simple_overridden", "one", v1) |
| 300 | valExists(t, "slice", "2", v1) |
| 301 | valExists(t, "slice_overridden", "two", v1) |
| 302 | valExists(t, "nr", "3", v1) |
| 303 | valExists(t, "struct_overridden", "three", v1) |
| 304 | } |
| 305 | |
| 306 | func valExists(t *testing.T, key string, expect string, result map[string][]string) { |
| 307 | valsExist(t, key, []string{expect}, result) |
| 308 | } |
| 309 | |
| 310 | func valsExist(t *testing.T, key string, expect []string, result map[string][]string) { |
| 311 | vals, ok := result[key] |
| 312 | if !ok { |
| 313 | t.Fatalf("Key not found. Expected: %s", key) |
| 314 | } |
| 315 | |
| 316 | if len(expect) != len(vals) { |
| 317 | t.Fatalf("Expected: %v, got: %v", expect, vals) |
| 318 | } |
| 319 | |
| 320 | for i, v := range expect { |
| 321 | if vals[i] != v { |
| 322 | t.Fatalf("Unexpected value. Expected: %v, got %v", v, vals[i]) |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | func valNotExists(t *testing.T, key string, result map[string][]string) { |
| 328 | if val, ok := result[key]; ok { |
| 329 | t.Error("Key not omitted. Expected: empty; got: " + val[0] + ".") |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | func valsLength(t *testing.T, expectedLength int, result map[string][]string) { |
| 334 | length := len(result) |
| 335 | if length != expectedLength { |
| 336 | t.Errorf("Expected length of %v, but got %v", expectedLength, length) |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | func noError(t *testing.T, err error) { |
| 341 | if err != nil { |
| 342 | t.Errorf("Unexpected error. Got %v", err) |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | type E4 struct { |
| 347 | ID string `json:"id"` |
| 348 | } |
| 349 | |
| 350 | func TestEncoderSetAliasTag(t *testing.T) { |
| 351 | data := map[string][]string{} |
| 352 | |
| 353 | s := E4{ |
| 354 | ID: "foo", |
| 355 | } |
| 356 | encoder := NewEncoder() |
| 357 | encoder.SetAliasTag("json") |
| 358 | err := encoder.Encode(&s, data) |
| 359 | if err != nil { |
| 360 | t.Fatalf("Failed to encode: %v", err) |
| 361 | } |
| 362 | valExists(t, "id", "foo", data) |
| 363 | } |
| 364 | |
| 365 | type E5 struct { |
| 366 | F01 int `schema:"f01,omitempty"` |
| 367 | F02 string `schema:"f02,omitempty"` |
| 368 | F03 *string `schema:"f03,omitempty"` |
| 369 | F04 *int8 `schema:"f04,omitempty"` |
| 370 | F05 float64 `schema:"f05,omitempty"` |
| 371 | F06 E5F06 `schema:"f06,omitempty"` |
| 372 | F07 E5F06 `schema:"f07,omitempty"` |
| 373 | F08 []string `schema:"f08,omitempty"` |
| 374 | F09 []string `schema:"f09,omitempty"` |
| 375 | } |
| 376 | |
| 377 | type E5F06 struct { |
| 378 | F0601 string `schema:"f0601,omitempty"` |
| 379 | } |
| 380 | |
| 381 | func TestEncoderWithOmitempty(t *testing.T) { |
| 382 | vals := map[string][]string{} |
| 383 | |
| 384 | s := E5{ |
| 385 | F02: "test", |
| 386 | F07: E5F06{ |
| 387 | F0601: "test", |
| 388 | }, |
| 389 | F09: []string{"test"}, |
| 390 | } |
| 391 | |
| 392 | encoder := NewEncoder() |
| 393 | err := encoder.Encode(&s, vals) |
| 394 | if err != nil { |
| 395 | t.Fatalf("Failed to encode: %v", err) |
| 396 | } |
| 397 | |
| 398 | valNotExists(t, "f01", vals) |
| 399 | valExists(t, "f02", "test", vals) |
| 400 | valNotExists(t, "f03", vals) |
| 401 | valNotExists(t, "f04", vals) |
| 402 | valNotExists(t, "f05", vals) |
| 403 | valNotExists(t, "f06", vals) |
| 404 | valExists(t, "f0601", "test", vals) |
| 405 | valNotExists(t, "f08", vals) |
| 406 | valsExist(t, "f09", []string{"test"}, vals) |
| 407 | } |
| 408 | |
| 409 | type E6 struct { |
| 410 | F01 *inner |
| 411 | F02 *inner |
| 412 | F03 *inner `schema:",omitempty"` |
| 413 | } |
| 414 | |
| 415 | func TestStructPointer(t *testing.T) { |
| 416 | vals := map[string][]string{} |
| 417 | s := E6{ |
| 418 | F01: &inner{2}, |
| 419 | } |
| 420 | |
| 421 | encoder := NewEncoder() |
| 422 | err := encoder.Encode(&s, vals) |
| 423 | if err != nil { |
| 424 | t.Fatalf("Failed to encode: %v", err) |
| 425 | } |
| 426 | valExists(t, "F12", "2", vals) |
| 427 | valExists(t, "F02", "null", vals) |
| 428 | valNotExists(t, "F03", vals) |
| 429 | } |
| 430 | |
| 431 | func TestRegisterEncoderCustomArrayType(t *testing.T) { |
| 432 | type CustomInt []int |
| 433 | type S1 struct { |
| 434 | SomeInts CustomInt `schema:",omitempty"` |
| 435 | } |
| 436 | |
| 437 | ss := []S1{ |
| 438 | {}, |
| 439 | {CustomInt{}}, |
| 440 | {CustomInt{1, 2, 3}}, |
| 441 | } |
| 442 | |
| 443 | for s := range ss { |
| 444 | vals := map[string][]string{} |
| 445 | |
| 446 | encoder := NewEncoder() |
| 447 | encoder.RegisterEncoder(CustomInt{}, func(value reflect.Value) string { |
| 448 | return fmt.Sprint(value.Interface()) |
| 449 | }) |
| 450 | |
| 451 | err := encoder.Encode(ss[s], vals) |
| 452 | if err != nil { |
| 453 | t.Fatalf("Failed to encode: %v", err) |
| 454 | } |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | func TestRegisterEncoderStructIsZero(t *testing.T) { |
| 459 | type S1 struct { |
| 460 | SomeTime1 time.Time `schema:"tim1,omitempty"` |
| 461 | SomeTime2 time.Time `schema:"tim2,omitempty"` |
| 462 | } |
| 463 | |
| 464 | ss := []*S1{ |
| 465 | { |
| 466 | SomeTime1: time.Date(2020, 8, 4, 13, 30, 1, 0, time.UTC), |
| 467 | }, |
| 468 | } |
| 469 | |
| 470 | for s := range ss { |
| 471 | vals := map[string][]string{} |
| 472 | |
| 473 | encoder := NewEncoder() |
| 474 | encoder.RegisterEncoder(time.Time{}, func(value reflect.Value) string { |
| 475 | tv, _ := reflect.TypeAssert[time.Time](value) |
| 476 | return tv.Format(time.RFC3339Nano) |
| 477 | }) |
| 478 | |
| 479 | err := encoder.Encode(ss[s], vals) |
| 480 | if err != nil { |
| 481 | t.Errorf("Encoder has non-nil error: %v", err) |
| 482 | } |
| 483 | |
| 484 | ta, ok := vals["tim1"] |
| 485 | if !ok { |
| 486 | t.Error("expected tim1 to be present") |
| 487 | } |
| 488 | |
| 489 | if len(ta) != 1 { |
| 490 | t.Error("expected tim1 to be present") |
| 491 | } |
| 492 | |
| 493 | if ta[0] != "2020-08-04T13:30:01Z" { |
| 494 | t.Error("expected correct tim1 time") |
| 495 | } |
| 496 | |
| 497 | _, ok = vals["tim2"] |
| 498 | if ok { |
| 499 | t.Error("expected tim1 not to be present") |
| 500 | } |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | func TestRegisterEncoderWithPtrType(t *testing.T) { |
| 505 | type CustomTime struct { |
| 506 | time time.Time |
| 507 | } |
| 508 | |
| 509 | type S1 struct { |
| 510 | DateStart *CustomTime |
| 511 | DateEnd *CustomTime |
| 512 | Empty *CustomTime `schema:"empty,omitempty"` |
| 513 | } |
| 514 | |
| 515 | ss := S1{ |
| 516 | DateStart: &CustomTime{time: time.Now()}, |
| 517 | DateEnd: nil, |
| 518 | } |
| 519 | |
| 520 | encoder := NewEncoder() |
| 521 | encoder.RegisterEncoder(&CustomTime{}, func(value reflect.Value) string { |
| 522 | if value.IsNil() { |
| 523 | return "" |
| 524 | } |
| 525 | |
| 526 | custom, _ := reflect.TypeAssert[*CustomTime](value) |
| 527 | return custom.time.String() |
| 528 | }) |
| 529 | |
| 530 | vals := map[string][]string{} |
| 531 | err := encoder.Encode(ss, vals) |
| 532 | |
| 533 | noError(t, err) |
| 534 | valsLength(t, 2, vals) |
| 535 | valExists(t, "DateStart", ss.DateStart.time.String(), vals) |
| 536 | valExists(t, "DateEnd", "", vals) |
| 537 | } |
| 538 | |
| 539 | func TestTimeDurationEncoding(t *testing.T) { |
| 540 | type DurationStruct struct { |
| 541 | Timeout time.Duration `schema:"timeout"` |
| 542 | } |
| 543 | |
| 544 | vals := map[string][]string{} |
| 545 | testData := DurationStruct{ |
| 546 | Timeout: 3 * time.Minute, |
| 547 | } |
| 548 | |
| 549 | enc := NewEncoder() |
| 550 | enc.RegisterEncoder(time.Duration(0), func(v reflect.Value) string { |
| 551 | d, _ := reflect.TypeAssert[time.Duration](v) |
| 552 | return d.String() // "3m0s" |
| 553 | }) |
| 554 | |
| 555 | err := enc.Encode(&testData, vals) |
| 556 | if err != nil { |
| 557 | t.Fatalf("Failed to encode time.Duration: %v", err) |
| 558 | } |
| 559 | |
| 560 | got, ok := vals["timeout"] |
| 561 | if !ok || len(got) < 1 { |
| 562 | t.Fatalf("Encoded map missing key 'timeout'") |
| 563 | } |
| 564 | if got[0] != (3 * time.Minute).String() { |
| 565 | t.Errorf("Expected %q, got %q", (3 * time.Minute).String(), got[0]) |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | // Test for omitempty with zero time.Duration. |
| 570 | func TestTimeDurationOmitEmpty(t *testing.T) { |
| 571 | type DurationStruct struct { |
| 572 | Timeout time.Duration `schema:"timeout,omitempty"` |
| 573 | } |
| 574 | |
| 575 | vals := map[string][]string{} |
| 576 | testData := DurationStruct{ |
| 577 | Timeout: 0, |
| 578 | } |
| 579 | |
| 580 | enc := NewEncoder() |
| 581 | enc.RegisterEncoder(time.Duration(0), func(v reflect.Value) string { |
| 582 | d, _ := reflect.TypeAssert[time.Duration](v) |
| 583 | return d.String() |
| 584 | }) |
| 585 | |
| 586 | err := enc.Encode(&testData, vals) |
| 587 | if err != nil { |
| 588 | t.Fatalf("Failed to encode time.Duration: %v", err) |
| 589 | } |
| 590 | // Should be omitted since 0 for time.Duration is "zero" and tagged as omitempty |
| 591 | if _, found := vals["timeout"]; found { |
| 592 | t.Errorf("Expected 'timeout' to be omitted, but it was present: %v", vals["timeout"]) |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | func TestEncoderZeroAndNonZeroFields(t *testing.T) { |
| 597 | type ZeroTestStruct struct { |
| 598 | A string `schema:"a,omitempty"` |
| 599 | B int `schema:"b,omitempty"` |
| 600 | C float64 `schema:"c,omitempty"` |
| 601 | D bool `schema:"d,omitempty"` |
| 602 | E *int `schema:"e,omitempty"` |
| 603 | F *string `schema:"f,omitempty"` |
| 604 | G string `schema:"g"` // no omitempty |
| 605 | } |
| 606 | |
| 607 | vals := map[string][]string{} |
| 608 | intVal := 42 |
| 609 | strVal := "Hello" |
| 610 | s := ZeroTestStruct{ |
| 611 | A: "", |
| 612 | B: 0, |
| 613 | C: 0.0, |
| 614 | D: false, |
| 615 | E: &intVal, |
| 616 | F: &strVal, |
| 617 | G: "MustEncode", |
| 618 | } |
| 619 | |
| 620 | enc := NewEncoder() |
| 621 | err := enc.Encode(&s, vals) |
| 622 | if err != nil { |
| 623 | t.Fatalf("Encoding error: %v", err) |
| 624 | } |
| 625 | |
| 626 | // Fields A, B, C, D are zero and should be omitted |
| 627 | if _, found := vals["a"]; found { |
| 628 | t.Errorf("Expected 'a' to be omitted for zero string") |
| 629 | } |
| 630 | if _, found := vals["b"]; found { |
| 631 | t.Errorf("Expected 'b' to be omitted for zero int") |
| 632 | } |
| 633 | if _, found := vals["c"]; found { |
| 634 | t.Errorf("Expected 'c' to be omitted for zero float") |
| 635 | } |
| 636 | if _, found := vals["d"]; found { |
| 637 | t.Errorf("Expected 'd' to be omitted for false bool") |
| 638 | } |
| 639 | |
| 640 | // E is a pointer to an int, so it should appear |
| 641 | gotE, found := vals["e"] |
| 642 | if !found { |
| 643 | t.Error("Expected 'e' to be present") |
| 644 | } else if len(gotE) != 1 || gotE[0] != "42" { |
| 645 | t.Errorf("Expected '42', got %v", gotE) |
| 646 | } |
| 647 | |
| 648 | // F is a pointer to string, so it should appear |
| 649 | gotF, found := vals["f"] |
| 650 | if !found { |
| 651 | t.Error("Expected 'f' to be present") |
| 652 | } else if len(gotF) != 1 || gotF[0] != "Hello" { |
| 653 | t.Errorf("Expected 'Hello', got %v", gotF) |
| 654 | } |
| 655 | |
| 656 | // G has no omitempty tag and must be encoded |
| 657 | gotG, found := vals["g"] |
| 658 | if !found { |
| 659 | t.Error("Expected 'g' to be present") |
| 660 | } else if len(gotG) != 1 || gotG[0] != "MustEncode" { |
| 661 | t.Errorf("Expected 'MustEncode', got %v", gotG) |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | func BenchmarkSimpleStructEncode(b *testing.B) { |
| 666 | s := SimpleStructForBenchmarkEncode{ |
| 667 | A: "abc", |
| 668 | B: 123, |
| 669 | C: true, |
| 670 | D: 3.14, |
| 671 | E: struct { |
| 672 | F float64 `schema:"f"` |
| 673 | }{F: 6.28}, |
| 674 | } |
| 675 | enc := NewEncoder() |
| 676 | |
| 677 | vals := map[string][]string{} |
| 678 | for b.Loop() { |
| 679 | _ = enc.Encode(&s, vals) |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | func BenchmarkSimpleStructEncodeParallel(b *testing.B) { |
| 684 | s := SimpleStructForBenchmarkEncode{ |
| 685 | A: "abc", |
| 686 | B: 123, |
| 687 | C: true, |
| 688 | D: 3.14, |
| 689 | E: struct { |
| 690 | F float64 `schema:"f"` |
| 691 | }{F: 6.28}, |
| 692 | } |
| 693 | enc := NewEncoder() |
| 694 | |
| 695 | b.ResetTimer() |
| 696 | b.RunParallel(func(pb *testing.PB) { |
| 697 | vals := map[string][]string{} |
| 698 | for pb.Next() { |
| 699 | _ = enc.Encode(&s, vals) |
| 700 | } |
| 701 | }) |
| 702 | } |
| 703 | |
| 704 | type LargeStructForBenchmarkEncode struct { |
| 705 | F1 string `schema:"f1"` |
| 706 | F2 string `schema:"f2"` |
| 707 | F3 int `schema:"f3"` |
| 708 | F4 int `schema:"f4"` |
| 709 | F5 []string `schema:"f5"` |
| 710 | F6 []int `schema:"f6"` |
| 711 | F7 float64 `schema:"f7"` |
| 712 | F8 bool `schema:"f8"` |
| 713 | F9 struct { |
| 714 | N1 time.Time `schema:"n1"` |
| 715 | N2 string `schema:"n2"` |
| 716 | } `schema:"f9"` |
| 717 | } |
| 718 | |
| 719 | func BenchmarkLargeStructEncode(b *testing.B) { |
| 720 | s := LargeStructForBenchmarkEncode{ |
| 721 | F1: "Lorem", F2: "Ipsum", F3: 123, F4: 456, |
| 722 | F5: []string{"A", "B", "C", "D"}, |
| 723 | F6: []int{10, 20, 30, 40}, |
| 724 | F7: 3.14159, F8: true, |
| 725 | F9: struct { |
| 726 | N1 time.Time `schema:"n1"` |
| 727 | N2 string `schema:"n2"` |
| 728 | }{ |
| 729 | N1: time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC), |
| 730 | N2: "NestedStringValue", |
| 731 | }, |
| 732 | } |
| 733 | enc := NewEncoder() |
| 734 | |
| 735 | // Optionally register a custom encoder for time.Time |
| 736 | enc.RegisterEncoder(time.Time{}, func(v reflect.Value) string { |
| 737 | tVal, _ := reflect.TypeAssert[time.Time](v) |
| 738 | return tVal.Format(time.RFC3339) |
| 739 | }) |
| 740 | |
| 741 | vals := map[string][]string{} |
| 742 | for b.Loop() { |
| 743 | _ = enc.Encode(&s, vals) |
| 744 | } |
| 745 | } |
| 746 | |
| 747 | func BenchmarkLargeStructEncodeParallel(b *testing.B) { |
| 748 | s := LargeStructForBenchmarkEncode{ |
| 749 | F1: "Lorem", F2: "Ipsum", F3: 123, F4: 456, |
| 750 | F5: []string{"A", "B", "C", "D"}, |
| 751 | F6: []int{10, 20, 30, 40}, |
| 752 | F7: 3.14159, F8: true, |
| 753 | F9: struct { |
| 754 | N1 time.Time `schema:"n1"` |
| 755 | N2 string `schema:"n2"` |
| 756 | }{ |
| 757 | N1: time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC), |
| 758 | N2: "NestedStringValue", |
| 759 | }, |
| 760 | } |
| 761 | enc := NewEncoder() |
| 762 | enc.RegisterEncoder(time.Time{}, func(v reflect.Value) string { |
| 763 | tVal, _ := reflect.TypeAssert[time.Time](v) |
| 764 | return tVal.Format(time.RFC3339) |
| 765 | }) |
| 766 | |
| 767 | b.ResetTimer() |
| 768 | b.RunParallel(func(pb *testing.PB) { |
| 769 | vals := map[string][]string{} |
| 770 | for pb.Next() { |
| 771 | _ = enc.Encode(&s, vals) |
| 772 | } |
| 773 | }) |
| 774 | } |
| 775 | |
| 776 | func BenchmarkTimeDurationEncoding(b *testing.B) { |
| 777 | type DurationStruct struct { |
| 778 | Timeout time.Duration `schema:"timeout"` |
| 779 | } |
| 780 | |
| 781 | testData := DurationStruct{ |
| 782 | Timeout: 5 * time.Second, |
| 783 | } |
| 784 | |
| 785 | enc := NewEncoder() |
| 786 | enc.RegisterEncoder(time.Duration(0), func(v reflect.Value) string { |
| 787 | d, _ := reflect.TypeAssert[time.Duration](v) |
| 788 | return d.String() |
| 789 | }) |
| 790 | |
| 791 | vals := map[string][]string{} |
| 792 | for b.Loop() { |
| 793 | _ = enc.Encode(&testData, vals) |
| 794 | } |
| 795 | } |
| 796 | |
| 797 | // A plan build racing SetAliasTag/RegisterEncoder must not re-insert a |
| 798 | // stale plan after the invalidation; once the reconfiguration call returns, |
| 799 | // every subsequent Encode must observe it. |
| 800 | func TestEncoderReconfigureDuringEncode(t *testing.T) { |
| 801 | type T1 struct { |
| 802 | A string `schema:"schemaname" url:"urlname"` |
| 803 | } |
| 804 | for i := 0; i < 300; i++ { |
| 805 | e := NewEncoder() |
| 806 | done := make(chan struct{}) |
| 807 | go func() { |
| 808 | defer close(done) |
| 809 | dst := map[string][]string{} |
| 810 | _ = e.Encode(T1{A: "x"}, dst) |
| 811 | }() |
| 812 | e.SetAliasTag("url") |
| 813 | <-done |
| 814 | |
| 815 | dst := map[string][]string{} |
| 816 | if err := e.Encode(T1{A: "x"}, dst); err != nil { |
| 817 | t.Fatal(err) |
| 818 | } |
| 819 | if _, ok := dst["urlname"]; !ok { |
| 820 | t.Fatalf("iteration %d: encode after SetAliasTag returned stale plan: %v", i, dst) |
| 821 | } |
| 822 | } |
| 823 | } |
| 824 | |
| 825 | // Errors inside recursed structs (value and pointer) must be collected under |
| 826 | // the nested type's name. |
| 827 | func TestEncoderNestedErrors(t *testing.T) { |
| 828 | type Bad struct { |
| 829 | M map[string]string `schema:"m"` |
| 830 | } |
| 831 | type S struct { |
| 832 | V Bad `schema:"v"` |
| 833 | P *Bad `schema:"p"` |
| 834 | } |
| 835 | enc := NewEncoder() |
| 836 | dst := map[string][]string{} |
| 837 | err := enc.Encode(S{V: Bad{M: map[string]string{"a": "b"}}, P: &Bad{}}, dst) |
| 838 | if err == nil { |
| 839 | t.Fatal("expected error for unsupported nested field") |
| 840 | } |
| 841 | if !strings.Contains(err.Error(), "encoder not found") { |
| 842 | t.Errorf("unexpected error: %v", err) |
| 843 | } |
| 844 | } |
| 845 | |
| 846 | // An encoding plan stored by a build that raced a reconfiguration carries |
| 847 | // the old generation and must never be served after the reconfiguration |
| 848 | // returned, even if it lands in the cache. |
| 849 | func TestEncoderStaleCacheEntryIgnored(t *testing.T) { |
| 850 | type T1 struct { |
| 851 | A string `schema:"schemaname" url:"urlname"` |
| 852 | } |
| 853 | e := NewEncoder() |
| 854 | typ := reflect.TypeOf(T1{}) |
| 855 | |
| 856 | dst := map[string][]string{} |
| 857 | if err := e.Encode(T1{A: "x"}, dst); err != nil { |
| 858 | t.Fatal(err) |
| 859 | } |
| 860 | stalePlan, ok := e.encCache.Load(typ) |
| 861 | if !ok { |
| 862 | t.Fatal("expected cached plan") |
| 863 | } |
| 864 | |
| 865 | e.SetAliasTag("url") |
| 866 | // Simulate a delayed store from a build that raced the reconfiguration. |
| 867 | e.encCache.Store(typ, stalePlan) |
| 868 | |
| 869 | dst = map[string][]string{} |
| 870 | if err := e.Encode(T1{A: "y"}, dst); err != nil { |
| 871 | t.Fatal(err) |
| 872 | } |
| 873 | if _, ok := dst["urlname"]; !ok { |
| 874 | t.Fatalf("stale plan served: %v", dst) |
| 875 | } |
| 876 | } |
| 877 | |
| 878 | // Pins the four cases the removed isValidStructPointer helper used to |
| 879 | // classify, now decided by the cached plan's recurseStructPtr flag plus a |
| 880 | // runtime nil check: valid struct pointers recurse, nil struct pointers |
| 881 | // encode as "null", struct values recurse, and pointers to non-structs |
| 882 | // encode their element (or "null" when nil). |
| 883 | func TestEncodeStructPointerClassification(t *testing.T) { |
| 884 | type Inner struct { |
| 885 | X string `schema:"x"` |
| 886 | } |
| 887 | type S struct { |
| 888 | SP *Inner `schema:"sp"` // valid struct pointer -> recursed |
| 889 | NP *Inner `schema:"np"` // nil struct pointer -> "null" |
| 890 | SV Inner `schema:"sv"` // struct value -> recursed |
| 891 | IP *int `schema:"ip"` // pointer to non-struct -> element |
| 892 | NIP *int `schema:"nip"` // nil pointer to non-struct -> "null" |
| 893 | } |
| 894 | |
| 895 | seven := 7 |
| 896 | src := S{ |
| 897 | SP: &Inner{X: "from-ptr"}, |
| 898 | SV: Inner{X: "from-val"}, |
| 899 | IP: &seven, |
| 900 | } |
| 901 | // SP and SV both recurse and write under the inner field's alias; SV is |
| 902 | // encoded after SP overwrote nothing (values append under "x"). |
| 903 | dst := map[string][]string{} |
| 904 | if err := NewEncoder().Encode(src, dst); err != nil { |
| 905 | t.Fatal(err) |
| 906 | } |
| 907 | |
| 908 | if got := dst["x"]; len(got) != 2 || got[0] != "from-ptr" || got[1] != "from-val" { |
| 909 | t.Errorf("struct pointer/value recursion: expected [from-ptr from-val] under \"x\", got %v", got) |
| 910 | } |
| 911 | if _, ok := dst["sp"]; ok { |
| 912 | t.Error("valid struct pointer must recurse, not encode under its own alias") |
| 913 | } |
| 914 | if got := dst["np"]; len(got) != 1 || got[0] != "null" { |
| 915 | t.Errorf("nil struct pointer: expected [null], got %v", got) |
| 916 | } |
| 917 | if got := dst["ip"]; len(got) != 1 || got[0] != "7" { |
| 918 | t.Errorf("pointer to non-struct: expected [7], got %v", got) |
| 919 | } |
| 920 | if got := dst["nip"]; len(got) != 1 || got[0] != "null" { |
| 921 | t.Errorf("nil pointer to non-struct: expected [null], got %v", got) |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | // Encoding into a nil destination map used to panic and crash the caller. |
| 926 | func TestEncodeNilDstReturnsError(t *testing.T) { |
| 927 | type S struct { |
| 928 | A string `schema:"a"` |
| 929 | } |
| 930 | err := NewEncoder().Encode(S{A: "x"}, nil) |
| 931 | if err == nil || !strings.Contains(err.Error(), "dst map must not be nil") { |
| 932 | t.Fatalf("expected nil-dst error, got %v", err) |
| 933 | } |
| 934 | } |
| 935 | |
| 936 | // Non-nil pointers to unsupported element types used to invoke a nil inner |
| 937 | // encoder and panic, crashing the caller; they must error instead, while |
| 938 | // nil pointers keep encoding as "null". |
| 939 | func TestEncodePointerToUnsupported(t *testing.T) { |
| 940 | type S struct { |
| 941 | M *map[string]string `schema:"m"` |
| 942 | L *[]int `schema:"l"` |
| 943 | A string `schema:"a"` |
| 944 | } |
| 945 | |
| 946 | m := map[string]string{"k": "v"} |
| 947 | l := []int{1} |
| 948 | dst := map[string][]string{} |
| 949 | err := NewEncoder().Encode(S{M: &m, L: &l, A: "x"}, dst) |
| 950 | if err == nil || !strings.Contains(err.Error(), "encoder not found") { |
| 951 | t.Fatalf("expected encoder-not-found error, got %v", err) |
| 952 | } |
| 953 | if got := dst["a"]; len(got) != 1 || got[0] != "x" { |
| 954 | t.Errorf("supported sibling must still encode: %v", dst) |
| 955 | } |
| 956 | |
| 957 | // Nil pointers to unsupported types keep the historical "null" output. |
| 958 | dst = map[string][]string{} |
| 959 | if err := NewEncoder().Encode(S{A: "x"}, dst); err != nil { |
| 960 | t.Fatal(err) |
| 961 | } |
| 962 | if got := dst["m"]; len(got) != 1 || got[0] != "null" { |
| 963 | t.Errorf("nil *map: expected [null], got %v", dst["m"]) |
| 964 | } |
| 965 | if got := dst["l"]; len(got) != 1 || got[0] != "null" { |
| 966 | t.Errorf("nil *slice: expected [null], got %v", dst["l"]) |
| 967 | } |
| 968 | |
| 969 | // omitempty suppresses the null. |
| 970 | type SO struct { |
| 971 | M *map[string]string `schema:"m,omitempty"` |
| 972 | } |
| 973 | dst = map[string][]string{} |
| 974 | if err := NewEncoder().Encode(SO{}, dst); err != nil { |
| 975 | t.Fatal(err) |
| 976 | } |
| 977 | if _, ok := dst["m"]; ok { |
| 978 | t.Errorf("omitempty nil pointer must be skipped: %v", dst) |
| 979 | } |
| 980 | } |
| 981 | |
| 982 | // Panics from user-registered encoders (or reflection) must surface as |
| 983 | // errors, mirroring Decode's recovery, instead of crashing the caller. |
| 984 | func TestEncodeRecoversEncoderPanic(t *testing.T) { |
| 985 | type PT struct{ V int } |
| 986 | type S struct { |
| 987 | P PT `schema:"p"` |
| 988 | } |
| 989 | enc := NewEncoder() |
| 990 | enc.RegisterEncoder(PT{}, func(reflect.Value) string { panic("boom") }) |
| 991 | err := enc.Encode(S{P: PT{V: 1}}, map[string][]string{}) |
| 992 | if err == nil || !strings.Contains(err.Error(), "panic while encoding: boom") { |
| 993 | t.Fatalf("expected recovered panic error, got %v", err) |
| 994 | } |
| 995 | } |
| 996 | |
| 997 | // An empty slice whose element type has no encoder (e.g. []*Struct) must be |
| 998 | // skipped under omitempty and emitted empty otherwise, not spuriously error; |
| 999 | // only a non-empty such slice errors. Non-slice unencodable fields still error. |
| 1000 | func TestEncodeEmptySliceUnencodableElem(t *testing.T) { |
| 1001 | type Inner struct { |
| 1002 | A string `schema:"a"` |
| 1003 | } |
| 1004 | |
| 1005 | // omitempty + nil slice -> skipped, no error. |
| 1006 | type SOmit struct { |
| 1007 | Children []*Inner `schema:"children,omitempty"` |
| 1008 | Name string `schema:"name"` |
| 1009 | } |
| 1010 | dst := map[string][]string{} |
| 1011 | if err := NewEncoder().Encode(SOmit{Name: "bob"}, dst); err != nil { |
| 1012 | t.Fatalf("omitempty empty slice should not error: %v", err) |
| 1013 | } |
| 1014 | if _, ok := dst["children"]; ok { |
| 1015 | t.Errorf("omitempty empty slice should be skipped, got %v", dst["children"]) |
| 1016 | } |
| 1017 | if got := dst["name"]; len(got) != 1 || got[0] != "bob" { |
| 1018 | t.Errorf("sibling not encoded: %v", dst) |
| 1019 | } |
| 1020 | |
| 1021 | // omitempty + non-nil empty slice -> also skipped (the check is Len-based, |
| 1022 | // not a nil check). |
| 1023 | dst = map[string][]string{} |
| 1024 | if err := NewEncoder().Encode(SOmit{Children: make([]*Inner, 0), Name: "bob"}, dst); err != nil { |
| 1025 | t.Fatalf("omitempty non-nil empty slice should not error: %v", err) |
| 1026 | } |
| 1027 | if _, ok := dst["children"]; ok { |
| 1028 | t.Errorf("omitempty non-nil empty slice should be skipped, got %v", dst["children"]) |
| 1029 | } |
| 1030 | |
| 1031 | // no omitempty + nil slice -> emitted empty, no error. |
| 1032 | type SPlain struct { |
| 1033 | Children []*Inner `schema:"children"` |
| 1034 | Name string `schema:"name"` |
| 1035 | } |
| 1036 | dst = map[string][]string{} |
| 1037 | if err := NewEncoder().Encode(SPlain{Name: "bob"}, dst); err != nil { |
| 1038 | t.Fatalf("empty slice should not error: %v", err) |
| 1039 | } |
| 1040 | if got, ok := dst["children"]; !ok || len(got) != 0 { |
| 1041 | t.Errorf("empty slice should emit empty, got %v (present=%v)", got, ok) |
| 1042 | } |
| 1043 | |
| 1044 | // no omitempty + non-nil empty slice -> also emitted empty, no error. |
| 1045 | dst = map[string][]string{} |
| 1046 | if err := NewEncoder().Encode(SPlain{Children: make([]*Inner, 0), Name: "bob"}, dst); err != nil { |
| 1047 | t.Fatalf("non-nil empty slice should not error: %v", err) |
| 1048 | } |
| 1049 | if got, ok := dst["children"]; !ok || len(got) != 0 { |
| 1050 | t.Errorf("non-nil empty slice should emit empty, got %v (present=%v)", got, ok) |
| 1051 | } |
| 1052 | |
| 1053 | // non-empty slice of unencodable element -> error. |
| 1054 | dst = map[string][]string{} |
| 1055 | err := NewEncoder().Encode(SPlain{Children: []*Inner{{A: "x"}}, Name: "bob"}, dst) |
| 1056 | if err == nil || !strings.Contains(err.Error(), "encoder not found") { |
| 1057 | t.Errorf("non-empty unencodable-elem slice should error, got %v", err) |
| 1058 | } |
| 1059 | |
| 1060 | // []*Struct with nil elements encodes each nil as "null" (as historically), |
| 1061 | // matching a scalar nil *Struct; a non-nil element is an error. |
| 1062 | dst = map[string][]string{} |
| 1063 | if err := NewEncoder().Encode(SPlain{Children: []*Inner{nil, nil}, Name: "bob"}, dst); err != nil { |
| 1064 | t.Fatalf("[]*Struct nil elements should encode as null, got %v", err) |
| 1065 | } |
| 1066 | if got := dst["children"]; len(got) != 2 || got[0] != "null" || got[1] != "null" { |
| 1067 | t.Errorf("nil elements: expected [null null], got %v", got) |
| 1068 | } |
| 1069 | |
| 1070 | // A value-struct slice ([]Struct) is unencodable and errors even when empty. |
| 1071 | type SVal struct { |
| 1072 | Items []Inner `schema:"items"` |
| 1073 | } |
| 1074 | if err := NewEncoder().Encode(SVal{}, map[string][]string{}); err == nil { |
| 1075 | t.Errorf("empty []Struct (value) should error, matching historical behavior") |
| 1076 | } |
| 1077 | |
| 1078 | // non-slice unencodable field (map) still errors regardless of emptiness. |
| 1079 | type SMap struct { |
| 1080 | M map[string]string `schema:"m"` |
| 1081 | } |
| 1082 | if err := NewEncoder().Encode(SMap{}, map[string][]string{}); err == nil { |
| 1083 | t.Errorf("empty map field should still error 'encoder not found'") |
| 1084 | } |
| 1085 | if err := NewEncoder().Encode(SMap{M: map[string]string{"k": "v"}}, map[string][]string{}); err == nil { |
| 1086 | t.Errorf("non-empty map field should error 'encoder not found'") |
| 1087 | } |
| 1088 | } |