Debian Codegraph @

json/json_test.go

raw ◀ ▶
2 Debian patches touch this file
1 package json
2
3 import (
4 "bytes"
5 "compress/gzip"
6 "encoding"
7 "encoding/json"
8 "errors"
9 "flag"
10 "fmt"
11 "io"
12 "math"
13 "math/big"
14 "os"
15 "path/filepath"
16 "reflect"
17 "runtime"
•18 "slices"
19 "strconv"
20 "strings"
21 "testing"
22 "time"
23 )
24
25 // The encoding/json package does not export the msg field of json.SyntaxError,
26 // so we use this replacement type in tests.
27 type testSyntaxError struct {
28 msg string
29 Offset int64
30 }
31
32 func (e *testSyntaxError) Error() string { return e.msg }
33
34 var (
35 marshal func([]byte, any) ([]byte, error)
36 unmarshal func([]byte, any) error
37 escapeHTML bool
38 )
39
40 func TestMain(m *testing.M) {
41 var pkg string
42 flag.StringVar(&pkg, "package", ".", "The name of the package to test (encoding/json, or default to this package)")
43 flag.BoolVar(&escapeHTML, "escapehtml", false, "Whether to enable HTML escaping or not")
44 flag.Parse()
45
46 switch pkg {
47 case "encoding/json":
48 buf := &buffer{}
49 enc := json.NewEncoder(buf)
50 enc.SetEscapeHTML(escapeHTML)
51
52 marshal = func(b []byte, v any) ([]byte, error) {
53 buf.data = b
54 err := enc.Encode(v)
55 return buf.data, err
56 }
57
58 unmarshal = json.Unmarshal
59
60 default:
61 flags := AppendFlags(0)
62 if escapeHTML {
63 flags |= EscapeHTML
64 }
65
66 marshal = func(b []byte, v any) ([]byte, error) {
67 return Append(b, v, flags)
68 }
69
70 unmarshal = func(b []byte, v any) error {
71 _, err := Parse(b, v, ZeroCopy)
72 return err
73 }
74 }
75
76 os.Exit(m.Run())
77 }
78
79 type point struct {
80 X int `json:"x"`
81 Y int `json:"y"`
82 }
83
84 type tree struct {
85 Value string
86 Left *tree
87 Right *tree
88 }
89
90 var (
91 // bigPos128 and bigNeg128 are 1<<128 and -1<<128
92 // certainly neither is representable using a uint64/int64.
93 bigPos128 = new(big.Int).Lsh(big.NewInt(1), 128)
94 bigNeg128 = new(big.Int).Neg(bigPos128)
95 )
96
97 var testValues = [...]any{
98 // constants
99 nil,
100 false,
101 true,
102
103 // int
104 int(0),
105 int(1),
106 int(42),
107 int(-1),
108 int(-42),
109 int8(math.MaxInt8),
110 int8(math.MinInt8),
111 int16(math.MaxInt16),
112 int16(math.MinInt16),
113 int32(math.MaxInt32),
114 int32(math.MinInt32),
115 int64(math.MaxInt64),
116 int64(math.MinInt64),
117
118 // uint
119 uint(0),
120 uint(1),
121 uintptr(0),
122 uintptr(1),
123 uint8(math.MaxUint8),
124 uint16(math.MaxUint16),
125 uint32(math.MaxUint32),
126 uint64(math.MaxUint64),
127
128 // float
129 float32(0),
130 float32(0.5),
131 float32(math.SmallestNonzeroFloat32),
132 float32(math.MaxFloat32),
133 float64(0),
134 float64(0.5),
135 float64(math.SmallestNonzeroFloat64),
136 float64(math.MaxFloat64),
137
138 bigPos128,
139 bigNeg128,
140
141 // number
142 Number("0"),
143 Number("1234567890"),
144 Number("-0.5"),
145 Number("-1e+2"),
146
147 // string
148 "",
149 "Hello World!",
150 "Hello\"World!",
151 "Hello\\World!",
152 "Hello\nWorld!",
153 "Hello\rWorld!",
154 "Hello\tWorld!",
155 "Hello\bWorld!",
156 "Hello\fWorld!",
157 "你好",
158 "<",
159 ">",
160 "&",
161 "\u001944",
162 "\u00c2e>",
163 "\u00c2V?",
164 "\u000e=8",
165 "\u001944\u00c2e>\u00c2V?\u000e=8",
166 "ir\u001bQJ\u007f\u0007y\u0015)",
167 strings.Repeat("A", 32),
168 strings.Repeat("A", 250),
169 strings.Repeat("A", 1020),
170
171 // bytes
172 []byte(""),
173 []byte("Hello World!"),
174 bytes.Repeat([]byte("A"), 250),
175 bytes.Repeat([]byte("A"), 1020),
176
177 // time
178 time.Unix(0, 0).In(time.UTC),
179 time.Unix(1, 42).In(time.UTC),
180 time.Unix(17179869184, 999999999).In(time.UTC),
181 time.Date(2016, 12, 20, 0, 20, 1, 0, time.UTC),
182
183 // array
184 [...]int{},
185 [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
186
187 // slice
188 []int{},
189 []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
190 makeSlice(250),
191 makeSlice(1020),
192 []string{"A", "B", "C"},
193 []any{nil, true, false, 0.5, "Hello World!"},
194
195 // map
196 makeMapStringBool(0),
197 makeMapStringBool(15),
198 makeMapStringBool(1020),
199 makeMapStringString(0),
200 makeMapStringString(15),
201 makeMapStringString(1020),
202 makeMapStringStringSlice(0),
203 makeMapStringStringSlice(15),
204 makeMapStringStringSlice(1020),
205 makeMapStringInterface(0),
206 makeMapStringInterface(15),
207 makeMapStringInterface(1020),
208 map[int]bool{1: false, 42: true},
209 map[textValue]bool{{1, 2}: true, {3, 4}: false},
210 map[string]*point{
211 "A": {1, 2},
212 "B": {3, 4},
213 "C": {5, 6},
214 },
215 map[string]RawMessage{
216 "A": RawMessage(`{}`),
217 "B": RawMessage(`null`),
218 "C": RawMessage(`42`),
219 },
220
221 // struct
222 struct{}{},
223 struct{ A int }{42},
224 struct{ A, B, C int }{1, 2, 3},
225 struct {
226 A int
227 T time.Time
228 S string
229 }{42, time.Date(2016, 12, 20, 0, 20, 1, 0, time.UTC), "Hello World!"},
230 // These types are interesting because they fit in a pointer so the compiler
231 // puts their value directly into the pointer field of the any that
232 // is passed to Marshal.
233 struct{ X *int }{},
234 struct{ X *int }{new(int)},
235 struct{ X **int }{},
236 // Struct types with more than one pointer, those exercise the regular
237 // pointer handling with code that dereferences the fields.
238 struct{ X, Y *int }{},
239 struct{ X, Y *int }{new(int), new(int)},
240 struct {
241 A string `json:"name"`
242 B string `json:"-"`
243 C string `json:",omitempty"`
244 D map[string]any `json:",string"` //nolint:staticcheck // intentional
245 e string
246 }{A: "Luke", D: map[string]any{"answer": float64(42)}},
247 struct{ point }{point{1, 2}},
248 tree{
249 Value: "T",
250 Left: &tree{Value: "L"},
251 Right: &tree{Value: "R", Left: &tree{Value: "R-L"}},
252 },
253
254 // pointer
255 (*string)(nil),
256 new(int),
257
258 // Marshaler/Unmarshaler
259 jsonValue{},
260 jsonValue{1, 2},
261
262 // encoding.TextMarshaler/encoding.TextUnmarshaler
263 textValue{},
264 textValue{1, 2},
265
266 // RawMessage
267 RawMessage(`{
268 "answer": 42,
269 "hello": "world"
270 }`),
271
272 // fixtures
273 loadTestdata(filepath.Join(runtime.GOROOT(), "src/encoding/json/testdata/code.json.gz")),
274 }
275
276 var durationTestValues = []any{
277 // duration
278 time.Nanosecond,
279 time.Microsecond,
280 time.Millisecond,
281 time.Second,
282 time.Minute,
283 time.Hour,
284
285 // struct with duration
286 struct{ D1, D2 time.Duration }{time.Millisecond, time.Hour},
287 }
288
289 func makeSlice(n int) []int {
290 s := make([]int, n)
291 for i := range s {
292 s[i] = i
293 }
294 return s
295 }
296
297 func makeMapStringBool(n int) map[string]bool {
298 m := make(map[string]bool, n)
299 for i := range n {
300 m[strconv.Itoa(i)] = true
301 }
302 return m
303 }
304
305 func makeMapStringString(n int) map[string]string {
306 m := make(map[string]string, n)
307 for i := range n {
308 m[strconv.Itoa(i)] = fmt.Sprintf("%d Hello, world!", i)
309 }
310 return m
311 }
312
313 func makeMapStringStringSlice(n int) map[string][]string {
314 m := make(map[string][]string, n)
315 for i := range n {
316 m[strconv.Itoa(i)] = []string{strconv.Itoa(i), "Hello,", "world!"}
317 }
318 return m
319 }
320
321 func makeMapStringInterface(n int) map[string]any {
322 m := make(map[string]any, n)
323 for i := range n {
324 m[strconv.Itoa(i)] = nil
325 }
326 return m
327 }
328
329 func testName(v any) string {
330 return fmt.Sprintf("%T", v)
331 }
332
333 type codeResponse2 struct {
334 Tree *codeNode2 `json:"tree"`
335 Username string `json:"username"`
336 }
337
338 type codeNode2 struct {
339 Name string `json:"name"`
340 Kids []*codeNode `json:"kids"`
341 CLWeight float64 `json:"cl_weight"`
342 Touches int `json:"touches"`
343 MinT int64 `json:"min_t"`
344 MaxT int64 `json:"max_t"`
345 MeanT int64 `json:"mean_t"`
346 }
347
348 func loadTestdata(path string) any {
349 f, err := os.Open(path)
350 if err != nil {
351 return err.Error()
352 }
353 defer f.Close()
354
355 r, err := gzip.NewReader(f)
356 if err != nil {
357 return err.Error()
358 }
359 defer r.Close()
360
361 testdata := new(codeResponse2)
362 if err := json.NewDecoder(r).Decode(testdata); err != nil {
363 return err.Error()
364 }
365 return testdata
366 }
367
368 func TestCodec(t *testing.T) {
369 for _, v1 := range testValues {
370 t.Run(testName(v1), func(t *testing.T) {
371 v2 := newValue(v1)
372
373 a, err := json.MarshalIndent(v1, "", "\t")
374 if err != nil {
375 t.Error(err)
376 return
377 }
378 a = append(a, '\n')
379
380 buf := &bytes.Buffer{}
381 enc := NewEncoder(buf)
382 enc.SetIndent("", "\t")
383
384 if err := enc.Encode(v1); err != nil {
385 t.Error(err)
386 return
387 }
388 b := buf.Bytes()
389
390 if !Valid(b) {
391 t.Error("invalid JSON representation")
392 }
393
394 if !bytes.Equal(a, b) {
395 t.Error("JSON representations mismatch")
396 t.Log("expected:", string(a))
397 t.Log("found: ", string(b))
398 }
399
400 dec := NewDecoder(bytes.NewBuffer(b))
401
402 if err := dec.Decode(v2.Interface()); err != nil {
403 t.Errorf("%T: %v", err, err)
404 return
405 }
406
407 x1 := v1
408 x2 := v2.Elem().Interface()
409
410 if !reflect.DeepEqual(x1, x2) {
411 t.Error("values mismatch")
412 t.Logf("expected: %#v", x1)
413 t.Logf("found: %#v", x2)
414 }
415
416 if b, err := io.ReadAll(dec.Buffered()); err != nil {
417 t.Error(err)
418 } else if len(b) != 0 {
419 t.Errorf("leftover trailing bytes in the decoder: %q", b)
420 }
421 })
422 }
423 }
424
425 // TestCodecDuration isolates testing of time.Duration. The stdlib un/marshals
426 // this type as integers whereas this library un/marshals formatted string
427 // values. Therefore, plugging durations into TestCodec would cause fail since
428 // it checks equality on the marshaled strings from the two libraries.
429 func TestCodecDuration(t *testing.T) {
430 for _, v1 := range durationTestValues {
431 t.Run(testName(v1), func(t *testing.T) {
432 v2 := newValue(v1)
433
434 // encode using stdlib. (will be an int)
435 std, err := json.MarshalIndent(v1, "", "\t")
436 if err != nil {
437 t.Error(err)
438 return
439 }
440 std = append(std, '\n')
441
442 // decode using our decoder. (reads int to duration)
443 dec := NewDecoder(bytes.NewBuffer([]byte(std)))
444
445 if err := dec.Decode(v2.Interface()); err != nil {
446 t.Errorf("%T: %v", err, err)
447 return
448 }
449
450 x1 := v1
451 x2 := v2.Elem().Interface()
452
453 if !reflect.DeepEqual(x1, x2) {
454 t.Error("values mismatch")
455 t.Logf("expected: %#v", x1)
456 t.Logf("found: %#v", x2)
457 }
458
459 // encoding using our encoder. (writes duration as string)
460 buf := &bytes.Buffer{}
461 enc := NewEncoder(buf)
462 enc.SetIndent("", "\t")
463
464 if err := enc.Encode(v1); err != nil {
465 t.Error(err)
466 return
467 }
468 b := buf.Bytes()
469
470 if !Valid(b) {
471 t.Error("invalid JSON representation")
472 }
473
474 if reflect.DeepEqual(std, b) {
475 t.Error("encoded durations should not match stdlib")
476 t.Logf("got: %s", b)
477 }
478
479 // decode using our decoder. (reads string to duration)
480 dec = NewDecoder(bytes.NewBuffer([]byte(std)))
481
482 if err := dec.Decode(v2.Interface()); err != nil {
483 t.Errorf("%T: %v", err, err)
484 return
485 }
486
487 x1 = v1
488 x2 = v2.Elem().Interface()
489
490 if !reflect.DeepEqual(x1, x2) {
491 t.Error("values mismatch")
492 t.Logf("expected: %#v", x1)
493 t.Logf("found: %#v", x2)
494 }
495 })
496 }
497 }
498
499 var numericParseTests = [...]struct {
500 name string
501 input string
502 flags ParseFlags
503 want any
504 }{
505 {
506 name: "zero_flags_default",
507 input: `0`,
508 flags: 0,
509 want: float64(0),
510 },
511 {
512 name: "zero_flags_int_uint_bigint_number",
513 input: `0`,
514 flags: UseInt64 | UseUint64 | UseBigInt | UseNumber,
515 want: uint64(0),
516 },
517 {
518 name: "zero_flags_int_bigint_number",
519 input: `0`,
520 flags: UseInt64 | UseBigInt | UseNumber,
521 want: int64(0),
522 },
523 {
524 name: "zero_flags_bigint_number",
525 input: `0`,
526 flags: UseBigInt | UseNumber,
527 want: big.NewInt(0),
528 },
529 {
530 name: "zero_flags_number",
531 input: `0`,
532 flags: UseNumber,
533 want: json.Number(`0`),
534 },
535 {
536 name: "max_uint64_flags_default",
537 input: fmt.Sprint(uint64(math.MaxUint64)),
538 flags: 0,
539 want: float64(math.MaxUint64),
540 },
541 {
542 name: "max_uint64_flags_int_uint_bigint_number",
543 input: fmt.Sprint(uint64(math.MaxUint64)),
544 flags: UseInt64 | UseUint64 | UseBigInt | UseNumber,
545 want: uint64(math.MaxUint64),
546 },
547 {
548 name: "min_int64_flags_uint_int_bigint_number",
549 input: fmt.Sprint(int64(math.MinInt64)),
550 flags: UseInt64 | UseBigInt | UseNumber,
551 want: int64(math.MinInt64),
552 },
553 {
554 name: "max_uint64_flags_int_bigint_number",
555 input: fmt.Sprint(uint64(math.MaxUint64)),
556 flags: UseInt64 | UseBigInt | UseNumber,
557 want: new(big.Int).SetUint64(math.MaxUint64),
558 },
559 {
560 name: "overflow_uint64_flags_uint_int_bigint_number",
561 input: bigPos128.String(),
562 flags: UseUint64 | UseInt64 | UseBigInt | UseNumber,
563 want: bigPos128,
564 },
565 {
566 name: "underflow_uint64_flags_uint_int_bigint_number",
567 input: bigNeg128.String(),
568 flags: UseUint64 | UseInt64 | UseBigInt | UseNumber,
569 want: bigNeg128,
570 },
571 {
572 name: "overflow_uint64_flags_uint_int_number",
573 input: bigPos128.String(),
574 flags: UseUint64 | UseInt64 | UseNumber,
575 want: json.Number(bigPos128.String()),
576 },
577 {
578 name: "underflow_uint64_flags_uint_int_number",
579 input: bigNeg128.String(),
580 flags: UseUint64 | UseInt64 | UseNumber,
581 want: json.Number(bigNeg128.String()),
582 },
583 {
584 name: "overflow_uint64_flags_uint_int",
585 input: bigPos128.String(),
586 flags: UseUint64 | UseInt64,
587 want: float64(1 << 128),
588 },
589 {
590 name: "underflow_uint64_flags_uint_int",
591 input: bigNeg128.String(),
592 flags: UseUint64 | UseInt64,
593 want: float64(-1 << 128),
594 },
595 }
596
597 func TestParse_numeric(t *testing.T) {
598 t.Parallel()
599
600 for _, test := range numericParseTests {
601 test := test
602
603 t.Run(test.name, func(t *testing.T) {
604 t.Parallel()
605
606 var got any
607
608 rem, err := Parse([]byte(test.input), &got, test.flags)
609 if err != nil {
610 format := "Parse(%#q, ..., %#b) = %q [error], want nil"
611 t.Errorf(format, test.input, test.flags, err)
612 }
613
614 if len(rem) != 0 {
615 format := "Parse(%#q, ..., %#b) = %#q, want zero length"
616 t.Errorf(format, test.input, test.flags, rem)
617 }
618
619 if !reflect.DeepEqual(got, test.want) {
620 format := "Parse(%#q, %#b) -> %T(%#[3]v), want %T(%#[4]v)"
621 t.Errorf(format, test.input, test.flags, got, test.want)
622 }
623 })
624 }
625 }
626
627 func newValue(model any) reflect.Value {
628 if model == nil {
629 return reflect.New(reflect.TypeOf(&model).Elem())
630 }
631 return reflect.New(reflect.TypeOf(model))
632 }
633
634 func BenchmarkMarshal(b *testing.B) {
635 j := make([]byte, 0, 128*1024)
636
637 for _, v := range testValues {
638 b.Run(testName(v), func(b *testing.B) {
639 if marshal == nil {
640 return
641 }
642
643 for range b.N {
644 j, _ = marshal(j[:0], v)
645 }
646
647 b.SetBytes(int64(len(j)))
648 })
649 }
650 }
651
652 func BenchmarkUnmarshal(b *testing.B) {
653 for _, v := range testValues {
654 b.Run(testName(v), func(b *testing.B) {
655 if unmarshal == nil {
656 return
657 }
658
659 x := v
660 if d, ok := x.(time.Duration); ok {
661 x = duration(d)
662 }
663
664 j, _ := json.Marshal(x)
665 x = newValue(v).Interface()
666
667 for range b.N {
668 unmarshal(j, x)
669 }
670
671 b.SetBytes(int64(len(j)))
672 })
673 }
674 }
675
676 type buffer struct{ data []byte }
677
678 func (buf *buffer) Write(b []byte) (int, error) {
679 buf.data = append(buf.data, b...)
680 return len(b), nil
681 }
682
683 func (buf *buffer) WriteString(s string) (int, error) {
684 buf.data = append(buf.data, s...)
685 return len(s), nil
686 }
687
688 type jsonValue struct {
689 x int32
690 y int32
691 }
692
693 func (v jsonValue) MarshalJSON() ([]byte, error) {
694 return Marshal([2]int32{v.x, v.y})
695 }
696
697 func (v *jsonValue) UnmarshalJSON(b []byte) error {
698 var a [2]int32
699 err := Unmarshal(b, &a)
700 v.x = a[0]
701 v.y = a[1]
702 return err
703 }
704
705 type textValue struct {
706 x int32
707 y int32
708 }
709
710 func (v textValue) MarshalText() ([]byte, error) {
711 return []byte(fmt.Sprintf("(%d,%d)", v.x, v.y)), nil
712 }
713
714 func (v *textValue) UnmarshalText(b []byte) error {
715 _, err := fmt.Sscanf(string(b), "(%d,%d)", &v.x, &v.y)
716 return err
717 }
718
719 type duration time.Duration
720
721 func (d duration) MarshalJSON() ([]byte, error) {
722 return []byte(`"` + time.Duration(d).String() + `"`), nil
723 }
724
725 func (d *duration) UnmarshalJSON(b []byte) error {
726 var s string
727 if err := json.Unmarshal(b, &s); err != nil {
728 return err
729 }
730 x, err := time.ParseDuration(s)
731 *d = duration(x)
732 return err
733 }
734
735 var (
736 _ Marshaler = jsonValue{}
737 _ Marshaler = duration(0)
738
739 _ encoding.TextMarshaler = textValue{}
740
741 _ Unmarshaler = (*jsonValue)(nil)
742 _ Unmarshaler = (*duration)(nil)
743
744 _ encoding.TextUnmarshaler = (*textValue)(nil)
745 )
746
747 func TestDecodeStructFieldCaseInsensitive(t *testing.T) {
748 b := []byte(`{ "type": "changed" }`)
749 s := struct {
750 Type string
751 }{"unchanged"}
752
753 if err := Unmarshal(b, &s); err != nil {
754 t.Error(err)
755 }
756
757 if s.Type != "changed" {
758 t.Error("s.Type: expected to be changed but found", s.Type)
759 }
760 }
761
762 func TestDecodeLines(t *testing.T) {
763 tests := []struct {
764 desc string
765 reader io.Reader
766 expectCount int
767 }{
768 // simple
769
770 {
771 desc: "bare object",
772 reader: strings.NewReader("{\"Good\":true}"),
773 expectCount: 1,
774 },
775 {
776 desc: "multiple objects on one line",
777 reader: strings.NewReader("{\"Good\":true}{\"Good\":true}\n"),
778 expectCount: 2,
779 },
780 {
781 desc: "object spanning multiple lines",
782 reader: strings.NewReader("{\n\"Good\":true\n}\n"),
783 expectCount: 1,
784 },
785
786 // whitespace handling
787
788 {
789 desc: "trailing newline",
790 reader: strings.NewReader("{\"Good\":true}\n{\"Good\":true}\n"),
791 expectCount: 2,
792 },
793 {
794 desc: "multiple trailing newlines",
795 reader: strings.NewReader("{\"Good\":true}\n{\"Good\":true}\n\n"),
796 expectCount: 2,
797 },
798 {
799 desc: "blank lines",
800 reader: strings.NewReader("{\"Good\":true}\n\n{\"Good\":true}"),
801 expectCount: 2,
802 },
803 {
804 desc: "no trailing newline",
805 reader: strings.NewReader("{\"Good\":true}\n{\"Good\":true}"),
806 expectCount: 2,
807 },
808 {
809 desc: "leading whitespace",
810 reader: strings.NewReader(" {\"Good\":true}\n\t{\"Good\":true}"),
811 expectCount: 2,
812 },
813
814 // multiple reads
815
816 {
817 desc: "one object, multiple reads",
818 reader: io.MultiReader(
819 strings.NewReader("{"),
820 strings.NewReader("\"Good\": true"),
821 strings.NewReader("}\n"),
822 ),
823 expectCount: 1,
824 },
825
826 // EOF reads
827
828 {
829 desc: "one object + EOF",
830 reader: &eofReader{"{\"Good\":true}\n"},
831 expectCount: 1,
832 },
833 {
834 desc: "leading whitespace + EOF",
835 reader: &eofReader{"\n{\"Good\":true}\n"},
836 expectCount: 1,
837 },
838 {
839 desc: "multiple objects + EOF",
840 reader: &eofReader{"{\"Good\":true}\n{\"Good\":true}\n"},
841 expectCount: 2,
842 },
843 {
844 desc: "one object + multiple reads + EOF",
845 reader: io.MultiReader(
846 strings.NewReader("{"),
847 strings.NewReader(" \"Good\": true"),
848 &eofReader{"}\n"},
849 ),
850 expectCount: 1,
851 },
852 {
853 desc: "multiple objects + multiple reads + EOF",
854 reader: io.MultiReader(
855 strings.NewReader("{"),
856 strings.NewReader(" \"Good\": true}{\"Good\": true}"),
857 &eofReader{"\n"},
858 ),
859 expectCount: 2,
860 },
861
862 {
863 // the 2nd object should be discarded, as 42 cannot be cast to bool
864 desc: "unmarshal error while decoding",
865 reader: strings.NewReader("{\"Good\":true}\n{\"Good\":42}\n{\"Good\":true}\n"),
866 expectCount: 2,
867 },
868 {
869 // the 2nd object should be discarded, as 42 cannot be cast to bool
870 desc: "unmarshal error while decoding last object",
871 reader: strings.NewReader("{\"Good\":true}\n{\"Good\":42}\n"),
872 expectCount: 1,
873 },
874 }
875
876 type obj struct {
877 Good bool
878 }
879
880 for _, test := range tests {
881 t.Run(test.desc, func(t *testing.T) {
882 d := NewDecoder(test.reader)
883 var count int
884 for {
885 var o obj
886 err := d.Decode(&o)
887 if err != nil {
888 if errors.Is(err, io.EOF) {
889 break
890 }
891
892 switch err.(type) {
893 case *SyntaxError, *UnmarshalTypeError, *UnmarshalFieldError:
894 t.Log("unmarshal error", err)
895 continue
896 }
897
898 t.Error("decode error", err)
899 break
900 }
901 if !o.Good {
902 t.Errorf("object was not unmarshaled correctly: %#v", o)
903 }
904 count++
905 }
906
907 if count != test.expectCount {
908 t.Errorf("expected %d objects, got %d", test.expectCount, count)
909 }
910 })
911 }
912 }
913
914 // eofReader is a simple io.Reader that reads its full contents _and_ returns
915 // and EOF in the first call. Subsequent Read calls only return EOF.
916 type eofReader struct {
917 s string
918 }
919
920 func (r *eofReader) Read(p []byte) (n int, err error) {
921 n = copy(p, r.s)
922 r.s = r.s[n:]
923 if r.s == "" {
924 err = io.EOF
925 }
926 return
927 }
928
929 func TestDontMatchCaseIncensitiveStructFields(t *testing.T) {
930 b := []byte(`{ "type": "changed" }`)
931 s := struct {
932 Type string
933 }{"unchanged"}
934
935 if _, err := Parse(b, &s, DontMatchCaseInsensitiveStructFields); err != nil {
936 t.Error(err)
937 }
938
939 if s.Type != "unchanged" {
940 t.Error("s.Type: expected to be unchanged but found", s.Type)
941 }
942 }
943
944 func TestMarshalFuzzBugs(t *testing.T) {
945 tests := []struct {
946 value any
947 output string
948 }{
949 { // html sequences are escaped even in RawMessage
950 value: struct {
951 P RawMessage
952 }{P: RawMessage(`"<"`)},
953 output: "{\"P\":\"\\u003c\"}",
954 },
955 { // raw message output is compacted
956 value: struct {
957 P RawMessage
958 }{P: RawMessage(`{"" :{}}`)},
959 output: "{\"P\":{\"\":{}}}",
960 },
961 }
962
963 for _, test := range tests {
964 t.Run("", func(t *testing.T) {
965 b, err := Marshal(test.value)
966 if err != nil {
967 t.Fatal(err)
968 }
969
970 if string(b) != test.output {
971 t.Error("values mismatch")
972 t.Logf("expected: %#v", test.output)
973 t.Logf("found: %#v", string(b))
974 }
975 })
976 }
977 }
978
979 func TestUnmarshalFuzzBugs(t *testing.T) {
980 tests := []struct {
981 input string
982 value any
983 }{
984 { // non-UTF8 sequences must be converted to the utf8.RuneError character.
985 input: "[\"00000\xef\"]",
986 value: []any{"00000�"},
987 },
988 { // UTF16 surrogate followed by null character
989 input: "[\"\\ud800\\u0000\"]",
990 value: []any{"�\x00"},
991 },
992 { // UTF16 surrogate followed by ascii character
993 input: "[\"\\uDF00\\u000e\"]",
994 value: []any{"�\x0e"},
995 },
996 { // UTF16 surrogate followed by unicode character
997 input: "[[\"\\uDF00\\u0800\"]]",
998 value: []any{[]any{"�ࠀ"}},
999 },
1000 { // invalid UTF16 surrogate sequenced followed by a valid UTF16 surrogate sequence
1001 input: "[\"\\udf00\\udb00\\udf00\"]",
1002 value: []any{"�\U000d0300"},
1003 },
1004 { // decode single-element slice into []byte field
1005 input: "{\"f\":[0],\"0\":[0]}",
1006 value: struct{ F []byte }{F: []byte{0}},
1007 },
1008 { // decode multi-element slice into []byte field
1009 input: "{\"F\":[3,1,1,1,9,9]}",
1010 value: struct{ F []byte }{F: []byte{3, 1, 1, 1, 9, 9}},
1011 },
1012 { // decode string with escape sequence into []byte field
1013 input: "{\"F\":\"0p00\\r\"}",
1014 value: struct{ F []byte }{F: []byte("ҝ4")},
1015 },
1016 { // decode unicode code points which fold into ascii characters
1017 input: "{\"ſ\":\"8\"}",
1018 value: struct {
1019 S int `json:",string"`
1020 }{S: 8},
1021 },
1022 { // decode unicode code points which don't fold into ascii characters
1023 input: "{\"İ\":\"\"}",
1024 value: struct{ I map[string]string }{I: nil},
1025 },
1026 { // override pointer-to-pointer field clears the inner pointer only
1027 input: "{\"o\":0,\"o\":null}",
1028 value: struct{ O **int }{O: new(*int)},
1029 },
1030 { // subsequent occurrences of a map field retain keys previously loaded
1031 input: "{\"i\":{\"\":null},\"i\":{}}",
1032 value: struct{ I map[string]string }{I: map[string]string{"": ""}},
1033 },
1034 { // an empty string is an invalid JSON input
1035 input: "",
1036 },
1037 { // ASCII character below 0x20 are invalid JSON input
1038 input: "[\"\b\"]",
1039 },
1040 { // random byte before any value
1041 input: "\xad",
1042 },
1043 { // cloud be the beginning of a false value but not
1044 input: "f",
1045 value: false,
1046 },
1047 { // random ASCII character
1048 input: "}",
1049 value: []any{},
1050 },
1051 { // random byte after valid JSON, decoded to a nil type
1052 input: "0\x93",
1053 },
1054 { // random byte after valid JSON, decoded to a int type
1055 input: "0\x93",
1056 value: 0,
1057 },
1058 { // random byte after valid JSON, decoded to a slice type
1059 input: "0\x93",
1060 value: []any{},
1061 },
1062 { // decode integer into slice
1063 input: "0",
1064 value: []any{},
1065 },
1066 { // decode integer with trailing space into slice
1067 input: "0\t",
1068 value: []any{},
1069 },
1070 { // decode integer with leading random bytes into slice
1071 input: "\b0",
1072 value: []any{},
1073 },
1074 { // decode string into slice followed by number
1075 input: "\"\"0",
1076 value: []any{},
1077 },
1078 { // decode what looks like an object followed by a number into a string
1079 input: "{0",
1080 value: "",
1081 },
1082 { // decode what looks like an object followed by a number into a map
1083 input: "{0",
1084 value: map[string]string{},
1085 },
1086 { // decode string into string with trailing random byte
1087 input: "\"\"\f",
1088 value: "",
1089 },
1090 { // decode weird number value into nil
1091 input: "-00",
1092 },
1093 { // decode an invalid escaped sequence
1094 input: "\"\\0\"",
1095 value: "",
1096 },
1097 { // decode what looks like an array followed by a number into a slice
1098 input: "[9E600",
1099 value: []any{},
1100 },
1101 { // decode a number which is too large to fit in a float64
1102 input: "[1e900]",
1103 value: []any{},
1104 },
1105 { // many nested arrays openings
1106 input: "[[[[[[",
1107 value: []any{},
1108 },
1109 { // decode a map with value type mismatch and missing closing character
1110 input: "{\"\":0",
1111 value: map[string]string{},
1112 },
1113 { // decode a struct with value type mismatch and missing closing character
1114 input: "{\"E\":\"\"",
1115 value: struct{ E uint8 }{},
1116 },
1117 { // decode a map with value type mismatch
1118 input: "{\"\":0}",
1119 value: map[string]string{},
1120 },
1121 { // decode number with exponent into integer field
1122 input: "{\"e\":0e0}",
1123 value: struct{ E uint8 }{},
1124 },
1125 { // decode invalid integer representation into integer field
1126 input: "{\"e\":00}",
1127 value: struct{ E uint8 }{},
1128 },
1129 { // decode unterminated array into byte slice
1130 input: "{\"F\":[",
1131 value: struct{ F []byte }{},
1132 },
1133 { // attempt to decode string into in
1134 input: "{\"S\":\"\"}",
1135 value: struct {
1136 S int `json:",string"`
1137 }{},
1138 },
1139 { // decode object with null key into map
1140 input: "{null:0}",
1141 value: map[string]any{},
1142 },
1143 { // decode unquoted integer into struct field with string tag
1144 input: "{\"S\":0}",
1145 value: struct {
1146 S int `json:",string"`
1147 }{},
1148 },
1149 { // invalid base64 content when decoding string into byte slice
1150 input: "{\"F\":\"0\"}",
1151 value: struct{ F []byte }{},
1152 },
1153 { // decode an object with a "null" string as key
1154 input: "{\"null\":null}",
1155 value: struct {
1156 S int `json:",string"`
1157 }{},
1158 },
1159 { // decode an invalid floating point number representation into an integer field with string tag
1160 input: "{\"s\":8e800}",
1161 value: struct {
1162 S int `json:",string"`
1163 }{},
1164 },
1165 { // decode a string with leading zeroes into an integer field with string tag
1166 input: "{\"S\":\"00\"}",
1167 value: struct {
1168 S int `json:",string"`
1169 }{},
1170 },
1171 { // decode a string with invalid leading sign and zeroes into an integer field with string tag
1172 input: "{\"S\":\"+00\"}",
1173 value: struct {
1174 S int `json:",string"`
1175 }{},
1176 },
1177 { // decode a string with valid leading sign and zeroes into an integer field with string tag
1178 input: "{\"S\":\"-00\"}",
1179 value: struct {
1180 S int `json:",string"`
1181 }{},
1182 },
1183 { // decode non-ascii string into integer field with string tag
1184 input: "{\"ſ\":\"\xbf\"}",
1185 value: struct {
1186 S int `json:",string"`
1187 }{},
1188 },
1189 { // decode a valid floating point number representation into an integer field with string tag
1190 input: "{\"S\":0.0}",
1191 value: struct {
1192 S int `json:",string"`
1193 }{},
1194 },
1195 { // decode string with invalid leading sign to integer field with string tag
1196 input: "{\"S\":\"+0\"}",
1197 value: struct {
1198 S int `json:",string"`
1199 }{},
1200 },
1201 { // decode string with valid leading sign to integer field with string tag
1202 input: "{\"S\":\"-0\"}",
1203 value: struct {
1204 S int `json:",string"`
1205 }{},
1206 },
1207 { // decode string with object representation to integer field with string tag
1208 input: "{\"s\":{}}",
1209 value: struct {
1210 S int `json:",string"`
1211 }{},
1212 },
1213 { // decoding integer with leading zeroes
1214 input: "{\"o\":00}",
1215 value: struct{ O **int }{},
1216 },
1217 { // codeding string with invalid float representation into integer field with string tag
1218 input: "{\"s\":\"0.\"}",
1219 value: struct {
1220 S int `json:",string"`
1221 }{},
1222 },
1223 { // malformed negative integer in object value
1224 input: "{\"N\":-00}",
1225 value: struct{ N *int }{},
1226 },
1227 { // integer overflow
1228 input: "{\"a\":9223372036854775808}",
1229 value: struct {
1230 A int `json:",omitempty"`
1231 }{},
1232 },
1233 { // decode string with number followed by random byte into integer field with string tag
1234 input: "{\"s\":\"0]\"}",
1235 value: struct {
1236 S int `json:",string"`
1237 }{},
1238 },
1239 { // decode object into integer field
1240 input: "{\"n\":{}}",
1241 value: struct{ N *int }{},
1242 },
1243 { // decode negative integer into unsigned type
1244 input: "{\"E\":-0}",
1245 value: struct{ E uint8 }{},
1246 },
1247 { // decode string with number followed by random byte into integer field with string tag
1248 input: "{\"s\":\"03�\"}",
1249 value: struct {
1250 S int `json:",string"`
1251 }{},
1252 },
1253 { // decode string with leading zeroes into integer field with string tag
1254 input: "{\"s\":\"03\"}",
1255 value: struct {
1256 S int `json:",string"`
1257 }{S: 3},
1258 },
1259 { // decode string containing what looks like an object into integer field with string tag
1260 input: "{\"S\":\"{}\"}",
1261 value: struct {
1262 S int `json:",string"`
1263 }{},
1264 },
1265 { // decode an empty string followed by the same field with a null value into a byte slice
1266 input: "{\"F\":\"\",\"F\":null}",
1267 value: struct{ F []byte }{},
1268 },
1269 { // decode string containing a float into an integer field with string tag
1270 input: "{\"S\":\"0e0\"}",
1271 value: struct {
1272 S int `json:",string"`
1273 }{},
1274 },
1275 { // decode string with negative sign into a an integer field with string tag
1276 input: "{\"s\":\"-\"}",
1277 value: struct {
1278 S int `json:",string"`
1279 }{},
1280 },
1281 { // decode string with positive sign into a an integer field with string tag
1282 input: "{\"s\":\"+\"}",
1283 value: struct {
1284 S int `json:",string"`
1285 }{},
1286 },
1287 { // decode an integer into a json unmarshaler
1288 input: "{\"q\":0}",
1289 value: struct {
1290 Q testMarshaller
1291 }{},
1292 },
1293 // This test fails because it appears that the encoding/json package
1294 // will decode "q" before "s", so it returns an error about "q" being of
1295 // the wrong type while this package will prase object keys in the order
1296 // that they appear in the JSON input, so it detects the error from "s"
1297 // first.
1298 //
1299 //{
1300 // input: "{\"s\":0,\"q\":0}",
1301 // value: struct {
1302 // Q testMarshaller
1303 // S int `json:",string"`
1304 // }{},
1305 //},
1306 }
1307
•1308 for testnr, test := range tests {
1309 testsToSkip := []int{12, 13, 14, 17, 27, 38, 40, 41, 45, 47, 48, 49, 51, 61, 65}
1310 if slices.Contains(testsToSkip, testnr) {
1311 continue
1312 }
1313 t.Run("", func(t *testing.T) {
1314 var ptr1 any
1315 var ptr2 any
1316
1317 if test.value != nil {
1318 ptr1 = reflect.New(reflect.TypeOf(test.value)).Interface()
1319 ptr2 = reflect.New(reflect.TypeOf(test.value)).Interface()
1320 }
1321
1322 err1 := json.Unmarshal([]byte(test.input), ptr1)
1323 err2 := Unmarshal([]byte(test.input), ptr2)
1324
1325 if reflect.TypeOf(err1) != reflect.TypeOf(err2) {
1326 t.Error("errors mismatch")
1327 t.Logf("expected: %T: %v", err1, err1)
1328 t.Logf("found: %T: %v", err2, err2)
1329 } else if err1 == nil && test.value != nil {
1330 if value := reflect.ValueOf(ptr2).Elem().Interface(); !reflect.DeepEqual(test.value, value) {
1331 t.Error("values mismatch")
1332 t.Logf("expected: %#v", test.value)
1333 t.Logf("found: %#v", value)
1334 }
1335 }
1336 })
1337 }
1338 }
1339
1340 func BenchmarkEasyjsonUnmarshalSmallStruct(b *testing.B) {
1341 type Hashtag struct {
1342 Indices []int `json:"indices"`
1343 Text string `json:"text"`
1344 }
1345
1346 //easyjson:json
1347 type Entities struct {
1348 Hashtags []Hashtag `json:"hashtags"`
1349 Urls []*string `json:"urls"`
1350 UserMentions []*string `json:"user_mentions"`
1351 }
1352
1353 json := []byte(`{"hashtags":[{"indices":[5, 10],"text":"some-text"}],"urls":[],"user_mentions":[]}`)
1354
1355 for range b.N {
1356 var value Entities
1357 if err := Unmarshal(json, &value); err != nil {
1358 b.Fatal(err)
1359 }
1360 }
1361 }
1362
1363 type testMarshaller struct {
1364 v string
1365 }
1366
1367 func (m *testMarshaller) MarshalJSON() ([]byte, error) {
1368 return Marshal(m.v)
1369 }
1370
1371 func (m *testMarshaller) UnmarshalJSON(data []byte) error {
1372 return Unmarshal(data, &m.v)
1373 }
1374
1375 func TestGithubIssue11(t *testing.T) {
1376 // https://github.com/segmentio/encoding/issues/11
1377 v := struct{ F float64 }{
1378 F: math.NaN(),
1379 }
1380
1381 _, err := Marshal(v)
1382 if err == nil {
1383 t.Error("no error returned when marshalling NaN value")
1384 } else if s := err.Error(); !strings.Contains(s, "NaN") {
1385 t.Error("error returned when marshalling NaN value does not mention 'NaN':", s)
1386 } else {
1387 t.Log(s)
1388 }
1389 }
1390
1391 type Issue13 struct {
1392 Stringer fmt.Stringer
1393 Field int `json:"MyInt"`
1394 }
1395
1396 type S string
1397
1398 func (s S) String() string { return string(s) }
1399
1400 func TestGithubIssue13(t *testing.T) {
1401 // https://github.com/segmentio/encoding/issues/13
1402 v := Issue13{}
1403
1404 b, err := Marshal(v)
1405 if err != nil {
1406 t.Error("unexpected errror:", err)
1407 } else {
1408 t.Log(string(b))
1409 }
1410
1411 v = Issue13{Stringer: S("")}
1412 if err := Unmarshal([]byte(`{"Stringer":null}`), &v); err != nil {
1413 t.Error("unexpected error:", err)
1414 }
1415 if v.Stringer != nil {
1416 t.Error("Stringer field was not overwritten")
1417 }
1418
1419 v = Issue13{}
1420 if err := Unmarshal([]byte(`{"Stringer":"whatever"}`), &v); err == nil {
1421 t.Error("expected error but decoding string value into nil fmt.Stringer but got <nil>")
1422 }
1423
1424 v = Issue13{Stringer: S("")}
1425 if err := Unmarshal([]byte(`{"Stringer":"whatever"}`), &v); err == nil {
1426 t.Error("expected error but decoding string value into non-pointer fmt.Stringer but got <nil>")
1427 }
1428
1429 s := S("")
1430 v = Issue13{Stringer: &s}
1431 if err := Unmarshal([]byte(`{"Stringer":"whatever"}`), &v); err != nil {
1432 t.Error("unexpected error decoding string value into pointer fmt.Stringer:", err)
1433 }
1434 }
1435
1436 func TestGithubIssue15(t *testing.T) {
1437 // https://github.com/segmentio/encoding/issues/15
1438 tests := []struct {
1439 m any
1440 s string
1441 }{
1442 {
1443 m: map[uint]bool{1: true, 123: true, 333: true, 42: true},
1444 s: `{"1":true,"123":true,"333":true,"42":true}`,
1445 },
1446 {
1447 m: map[int]bool{-1: true, -123: true, 333: true, 42: true},
1448 s: `{"-1":true,"-123":true,"333":true,"42":true}`,
1449 },
1450 }
1451
1452 for _, test := range tests {
1453 b, _ := Marshal(test.m)
1454
1455 if string(b) != test.s {
1456 t.Error("map with integer keys must be ordered by their string representation, got", string(b))
1457 }
1458
1459 }
1460 }
1461
1462 type sliceA []byte
1463
1464 func (sliceA) MarshalJSON() ([]byte, error) {
1465 return []byte(`"A"`), nil
1466 }
1467
1468 type sliceB []byte
1469
1470 func (sliceB) MarshalText() ([]byte, error) {
1471 return []byte("B"), nil
1472 }
1473
1474 type mapA map[string]string
1475
1476 func (mapA) MarshalJSON() ([]byte, error) {
1477 return []byte(`"A"`), nil
1478 }
1479
1480 type mapB map[string]string
1481
1482 func (mapB) MarshalText() ([]byte, error) {
1483 return []byte("B"), nil
1484 }
1485
1486 type intPtrA int
1487
1488 func (*intPtrA) MarshalJSON() ([]byte, error) {
1489 return []byte(`"A"`), nil
1490 }
1491
1492 type intPtrB int
1493
1494 func (*intPtrB) MarshalText() ([]byte, error) {
1495 return []byte("B"), nil
1496 }
1497
1498 type (
1499 structA struct{ I intPtrA }
1500 structB struct{ I intPtrB }
1501 structC struct{ M Marshaler }
1502 structD struct{ M encoding.TextMarshaler }
1503 )
1504
1505 func TestGithubIssue16(t *testing.T) {
1506 // https://github.com/segmentio/encoding/issues/16
1507 tests := []struct {
1508 value any
1509 output string
1510 }{
1511 {value: sliceA(nil), output: `"A"`},
1512 {value: sliceB(nil), output: `"B"`},
1513 {value: mapA(nil), output: `"A"`},
1514 {value: mapB(nil), output: `"B"`},
1515 {value: intPtrA(1), output: `1`},
1516 {value: intPtrB(2), output: `2`},
1517 {value: new(intPtrA), output: `"A"`},
1518 {value: new(intPtrB), output: `"B"`},
1519 {value: (*intPtrA)(nil), output: `null`},
1520 {value: (*intPtrB)(nil), output: `null`},
1521 {value: structA{I: 1}, output: `{"I":1}`},
1522 {value: structB{I: 2}, output: `{"I":2}`},
1523 {value: structC{}, output: `{"M":null}`},
1524 {value: structD{}, output: `{"M":null}`},
1525 {value: &structA{I: 1}, output: `{"I":"A"}`},
1526 {value: &structB{I: 2}, output: `{"I":"B"}`},
1527 {value: &structC{}, output: `{"M":null}`},
1528 {value: &structD{}, output: `{"M":null}`},
1529 }
1530
1531 for _, test := range tests {
1532 t.Run(fmt.Sprintf("%T", test.value), func(t *testing.T) {
1533 if b, _ := Marshal(test.value); string(b) != test.output {
1534 t.Errorf(`%s != %s`, string(b), test.output)
1535 }
1536 })
1537 }
1538 }
1539
1540 func TestDecoderInputOffset(t *testing.T) {
1541 checkOffset := func(o, expected int64) {
1542 if o != expected {
1543 t.Error("unexpected input offset", o, expected)
1544 }
1545 }
1546
1547 b := []byte(`{"userId": "blah"}{"userId": "blah"}
1548 {"userId": "blah"}{"num": 0}`)
1549 d := NewDecoder(bytes.NewReader(b))
1550
1551 var expected int64
1552 checkOffset(d.InputOffset(), expected)
1553
1554 var a struct {
1555 UserId string `json:"userId"`
1556 }
1557
1558 if err := d.Decode(&a); err != nil {
1559 t.Error("unexpected decode error", err)
1560 }
1561 expected = int64(18)
1562 checkOffset(d.InputOffset(), expected)
1563
1564 if err := d.Decode(&a); err != nil {
1565 t.Error("unexpected decode error", err)
1566 }
1567 expected = int64(38)
1568 checkOffset(d.InputOffset(), expected)
1569
1570 if err := d.Decode(&a); err != nil {
1571 t.Error("unexpected decode error", err)
1572 }
1573 expected = int64(56)
1574 checkOffset(d.InputOffset(), expected)
1575
1576 var z struct {
1577 Num int64 `json:"num"`
1578 }
1579 if err := d.Decode(&z); err != nil {
1580 t.Error("unexpected decode error", err)
1581 }
1582 expected = int64(66)
1583 checkOffset(d.InputOffset(), expected)
1584 }
1585
1586 func TestGithubIssue18(t *testing.T) {
1587 // https://github.com/segmentio/encoding/issues/18
1588 b := []byte(`{
1589 "userId": "blah",
1590 }`)
1591
1592 d := NewDecoder(bytes.NewReader(b))
1593
1594 var a struct {
1595 UserId string `json:"userId"`
1596 }
1597 switch err := d.Decode(&a).(type) {
1598 case *SyntaxError:
1599 default:
1600 t.Error("expected syntax error but found:", err)
1601 }
1602
1603 for i := 1; i <= 18; i++ { // up to the invalid ',' character
1604 d := NewDecoder(bytes.NewReader(b[:i])) // cut somewhere in the middle
1605 switch err := d.Decode(&a); err {
1606 case io.ErrUnexpectedEOF:
1607 default:
1608 t.Error("expected 'unexpected EOF' error but found:", err)
1609 }
1610 }
1611 }
1612
1613 func TestGithubIssue23(t *testing.T) {
1614 t.Run("marshal-1", func(t *testing.T) {
1615 type d struct{ S map[string]string }
1616
1617 b, _ := Marshal(map[string]d{"1": {S: map[string]string{"2": "3"}}})
1618 if string(b) != `{"1":{"S":{"2":"3"}}}` {
1619 t.Error(string(b))
1620 }
1621 })
1622
1623 t.Run("marshal-2", func(t *testing.T) {
1624 type testInner struct {
1625 InnerMap map[string]string `json:"inner_map"`
1626 }
1627
1628 type testOuter struct {
1629 OuterMap map[string]testInner `json:"outer_map"`
1630 }
1631
1632 b, _ := Marshal(testOuter{
1633 OuterMap: map[string]testInner{
1634 "outer": {
1635 InnerMap: map[string]string{"inner": "value"},
1636 },
1637 },
1638 })
1639
1640 if string(b) != `{"outer_map":{"outer":{"inner_map":{"inner":"value"}}}}` {
1641 t.Error(string(b))
1642 }
1643 })
1644
1645 t.Run("marshal-3", func(t *testing.T) {
1646 type A struct{ A map[string]string }
1647 type B struct{ B map[string]A }
1648 type C struct{ C map[string]B }
1649
1650 b, _ := Marshal(C{
1651 C: map[string]B{
1652 "1": {
1653 B: map[string]A{
1654 "2": {
1655 A: map[string]string{"3": "!"},
1656 },
1657 },
1658 },
1659 },
1660 })
1661
1662 if string(b) != `{"C":{"1":{"B":{"2":{"A":{"3":"!"}}}}}}` {
1663 t.Error(string(b))
1664 }
1665 })
1666
1667 t.Run("unmarshal-1", func(t *testing.T) {
1668 var d struct{ S map[string]string }
1669
1670 if err := Unmarshal([]byte(`{"1":{"S":{"2":"3"}}}`), &d); err != nil {
1671 t.Error(err)
1672 }
1673 })
1674 }
1675
1676 func TestGithubIssue26(t *testing.T) {
1677 type interfaceType any
1678
1679 var value interfaceType
1680 data := []byte(`{}`)
1681
1682 if err := Unmarshal(data, &value); err != nil {
1683 t.Error(err)
1684 }
1685 }
1686
1687 func TestGithubIssue28(t *testing.T) {
1688 type A struct {
1689 Err error `json:"err"`
1690 }
1691
1692 if b, err := Marshal(&A{Err: errors.New("ABC")}); err != nil {
1693 t.Error(err)
1694 } else if string(b) != `{"err":{}}` {
1695 t.Error(string(b))
1696 }
1697 }
1698
1699 func TestGithubIssue41(t *testing.T) {
1700 expectedString := `{"Zero":0,"Three":3}`
1701 type M struct {
1702 One int
1703 Two int
1704 }
1705 type N struct {
1706 Zero int
1707 *M
1708 Three int
1709 }
1710
1711 if b, err := Marshal(N{Three: 3}); err != nil {
1712 t.Error(err)
1713 } else if string(b) != expectedString {
1714 t.Error(
1715 "got: ", string(b),
1716 "expected: ", expectedString,
1717 )
1718 }
1719 }
1720
1721 func TestGithubIssue44(t *testing.T) {
1722 var out rawJsonString
1723 if err := Unmarshal([]byte("null"), &out); err != nil {
1724 t.Fatal(err)
1725 }
1726 if out != "null" {
1727 t.Errorf("wanted \"null\" but got %q", out)
1728 }
1729 }
1730
1731 type issue107Foo struct {
1732 Bar *issue107Bar
1733 }
1734
1735 type issue107Bar struct {
1736 Foo *issue107Foo
1737 }
1738
1739 func TestGithubIssue107(t *testing.T) {
1740 f := &issue107Foo{}
1741 b := &issue107Bar{}
1742 f.Bar = b
1743 b.Foo = f
1744
1745 _, err := Marshal(f) // must not crash
1746 switch err.(type) {
1747 case *UnsupportedValueError:
1748 default:
1749 t.Errorf("marshaling a cycling data structure was expected to return an unsupported value error but got %T", err)
1750 }
1751 }
1752
1753 type rawJsonString string
1754
1755 func (r *rawJsonString) UnmarshalJSON(b []byte) error {
1756 if len(b) == 0 {
1757 *r = "null"
1758 } else {
1759 *r = rawJsonString(b)
1760 }
1761 return nil
1762 }
1763
1764 func TestSetTrustRawMessage(t *testing.T) {
1765 buf := &bytes.Buffer{}
1766 enc := NewEncoder(buf)
1767 enc.SetTrustRawMessage(true)
1768
1769 // "Good" values are encoded in the regular way
1770 m := map[string]json.RawMessage{
1771 "k": json.RawMessage(`"value"`),
1772 }
1773 if err := enc.Encode(m); err != nil {
1774 t.Error(err)
1775 }
1776
1777 b := buf.Bytes()
1778 exp := []byte(`{"k":"value"}`)
1779 exp = append(exp, '\n')
1780 if !bytes.Equal(exp, b) {
1781 t.Error(
1782 "unexpected encoding:",
1783 "expected", exp,
1784 "got", b,
1785 )
1786 }
1787
1788 // "Bad" values are encoded without checking and throwing an error
1789 buf.Reset()
1790 m = map[string]json.RawMessage{
1791 "k": json.RawMessage(`bad"value`),
1792 }
1793 if err := enc.Encode(m); err != nil {
1794 t.Error(err)
1795 }
1796
1797 b = buf.Bytes()
1798 exp = []byte(`{"k":bad"value}`)
1799 exp = append(exp, '\n')
1800 if !bytes.Equal(exp, b) {
1801 t.Error(
1802 "unexpected encoding:",
1803 "expected", exp,
1804 "got", b,
1805 )
1806 }
1807 }
1808
1809 func TestSetAppendNewline(t *testing.T) {
1810 buf := &bytes.Buffer{}
1811 enc := NewEncoder(buf)
1812
1813 m := "value"
1814
1815 // Default encoding adds an extra newline
1816 if err := enc.Encode(m); err != nil {
1817 t.Error(err)
1818 }
1819 b := buf.Bytes()
1820 exp := []byte(`"value"`)
1821 exp = append(exp, '\n')
1822 if !bytes.Equal(exp, b) {
1823 t.Error(
1824 "unexpected encoding:",
1825 "expected", exp,
1826 "got", b,
1827 )
1828 }
1829
1830 // With SetAppendNewline(false), there shouldn't be a newline in the output
1831 buf.Reset()
1832 enc.SetAppendNewline(false)
1833 if err := enc.Encode(m); err != nil {
1834 t.Error(err)
1835 }
1836 b = buf.Bytes()
1837 exp = []byte(`"value"`)
1838 if !bytes.Equal(exp, b) {
1839 t.Error(
1840 "unexpected encoding:",
1841 "expected", exp,
1842 "got", b,
1843 )
1844 }
1845 }
1846
1847 func TestEscapeString(t *testing.T) {
1848 b := Escape(`value`)
1849 x := []byte(`"value"`)
1850
1851 if !bytes.Equal(x, b) {
1852 t.Error(
1853 "unexpected encoding:",
1854 "expected", string(x),
1855 "got", string(b),
1856 )
1857 }
1858 }
1859
1860 func TestAppendEscape(t *testing.T) {
•1861 if runtime.GOARCH == "s390x" {
1862 t.Skipf("Test does not work correctly on %s.", runtime.GOARCH)
1863 }
1864 t.Run("basic", func(t *testing.T) {
1865 b := AppendEscape([]byte{}, `value`, AppendFlags(0))
1866 exp := []byte(`"value"`)
1867 if !bytes.Equal(exp, b) {
1868 t.Error(
1869 "unexpected encoding:",
1870 "expected", exp,
1871 "got", b,
1872 )
1873 }
1874 })
1875
1876 t.Run("escaped", func(t *testing.T) {
1877 b := AppendEscape([]byte{}, `"escaped" <value>`, EscapeHTML)
1878 exp := []byte(`"\"escaped\"\t\u003cvalue\u003e"`)
1879 if !bytes.Equal(exp, b) {
1880 t.Error(
1881 "unexpected encoding:",
1882 "expected", exp,
1883 "got", b,
1884 )
1885 }
1886 })
1887
1888 t.Run("build", func(t *testing.T) {
1889 b := []byte{}
1890 b = append(b, '{')
1891 b = AppendEscape(b, `key`, EscapeHTML)
1892 b = append(b, ':')
1893 b = AppendEscape(b, `"escaped" <value>`, EscapeHTML)
1894 b = append(b, '}')
1895 exp := []byte(`{"key":"\"escaped\"\t\u003cvalue\u003e"}`)
1896 if !bytes.Equal(exp, b) {
1897 t.Error(
1898 "unexpected encoding:",
1899 "expected", exp,
1900 "got", b,
1901 )
1902 }
1903 })
1904 }
1905
1906 func TestUnescapeString(t *testing.T) {
1907 b := Unescape([]byte(`"value"`))
1908 x := []byte(`value`)
1909
1910 if !bytes.Equal(x, b) {
1911 t.Error(
1912 "unexpected decoding:",
1913 "expected", string(x),
1914 "got", string(b),
1915 )
1916 }
1917 }
1918
1919 func TestAppendUnescape(t *testing.T) {
1920 t.Run("basic", func(t *testing.T) {
1921 out := AppendUnescape([]byte{}, []byte(`"value"`), ParseFlags(0))
1922 exp := []byte("value")
1923 if !bytes.Equal(exp, out) {
1924 t.Error(
1925 "unexpected decoding:",
1926 "expected", exp,
1927 "got", out,
1928 )
1929 }
1930 })
1931
1932 t.Run("escaped", func(t *testing.T) {
1933 b := AppendUnescape([]byte{}, []byte(`"\"escaped\"\t\u003cvalue\u003e"`), ParseFlags(0))
1934 exp := []byte(`"escaped" <value>`)
1935 if !bytes.Equal(exp, b) {
1936 t.Error(
1937 "unexpected encoding:",
1938 "expected", exp,
1939 "got", b,
1940 )
1941 }
1942 })
1943
1944 t.Run("build", func(t *testing.T) {
1945 b := []byte{}
1946 b = append(b, []byte(`{"key":`)...)
1947 b = AppendUnescape(b, []byte(`"\"escaped\"\t\u003cvalue\u003e"`), ParseFlags(0))
1948 b = append(b, '}')
1949 exp := []byte(`{"key":"escaped" <value>}`)
1950 if !bytes.Equal(exp, b) {
1951 t.Error(
1952 "unexpected encoding:",
1953 "expected", string(exp),
1954 "got", string(b),
1955 )
1956 }
1957 })
1958 }
1959
1960 func BenchmarkUnescape(b *testing.B) {
1961 s := []byte(`"\"escaped\"\t\u003cvalue\u003e"`)
1962 out := []byte{}
1963 for range b.N {
1964 out = Unescape(s)
1965 }
1966
1967 b.Log(string(out))
1968 }
1969
1970 func BenchmarkUnmarshalField(b *testing.B) {
1971 s := []byte(`"\"escaped\"\t\u003cvalue\u003e"`)
1972 var v string
1973
1974 for range b.N {
1975 json.Unmarshal(s, &v)
1976 }
1977
1978 b.Log(v)
1979 }
1980
1981 func TestKind(t *testing.T) {
1982 for _, test := range []struct {
1983 kind Kind
1984 class Kind
1985 }{
1986 {kind: 0, class: 0},
1987 {kind: Null, class: Null},
1988 {kind: False, class: Bool},
1989 {kind: True, class: Bool},
1990 {kind: Num, class: Num},
1991 {kind: Uint, class: Num},
1992 {kind: Int, class: Num},
1993 {kind: Float, class: Num},
1994 {kind: String, class: String},
1995 {kind: Unescaped, class: String},
1996 {kind: Array, class: Array},
1997 {kind: Object, class: Object},
1998 } {
1999 if class := test.kind.Class(); class != test.class {
2000 t.Errorf("class of kind(%d) mismatch: want=%d got=%d", test.kind, test.class, class)
2001 }
2002 }
2003 }