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