1// Copyright 2011 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5package json 6 7import ( 8 "bytes" 9 "encoding" 10 "fmt" 11 "log" 12 "math" 13 "reflect" 14 "regexp" 15 "strconv" 16 "testing" 17 "unicode" 18) 19 20type Optionals struct { 21 Sr string `json:"sr"` 22 So string `json:"so,omitempty"` 23 Sw string `json:"-"` 24 25 Ir int `json:"omitempty"` // actually named omitempty, not an option 26 Io int `json:"io,omitempty"` 27 28 Slr []string `json:"slr,random"` 29 Slo []string `json:"slo,omitempty"` 30 31 Mr map[string]interface{} `json:"mr"` 32 Mo map[string]interface{} `json:",omitempty"` 33 34 Fr float64 `json:"fr"` 35 Fo float64 `json:"fo,omitempty"` 36 37 Br bool `json:"br"` 38 Bo bool `json:"bo,omitempty"` 39 40 Ur uint `json:"ur"` 41 Uo uint `json:"uo,omitempty"` 42 43 Str struct{} `json:"str"` 44 Sto struct{} `json:"sto,omitempty"` 45} 46 47var optionalsExpected = `{ 48 "sr": "", 49 "omitempty": 0, 50 "slr": null, 51 "mr": {}, 52 "fr": 0, 53 "br": false, 54 "ur": 0, 55 "str": {}, 56 "sto": {} 57}` 58 59func TestOmitEmpty(t *testing.T) { 60 var o Optionals 61 o.Sw = "something" 62 o.Mr = map[string]interface{}{} 63 o.Mo = map[string]interface{}{} 64 65 got, err := MarshalIndent(&o, "", " ") 66 if err != nil { 67 t.Fatal(err) 68 } 69 if got := string(got); got != optionalsExpected { 70 t.Errorf(" got: %s\nwant: %s\n", got, optionalsExpected) 71 } 72} 73 74type StringTag struct { 75 BoolStr bool `json:",string"` 76 IntStr int64 `json:",string"` 77 UintptrStr uintptr `json:",string"` 78 StrStr string `json:",string"` 79 NumberStr Number `json:",string"` 80} 81 82func TestRoundtripStringTag(t *testing.T) { 83 tests := []struct { 84 name string 85 in StringTag 86 want string // empty to just test that we roundtrip 87 }{ 88 { 89 name: "AllTypes", 90 in: StringTag{ 91 BoolStr: true, 92 IntStr: 42, 93 UintptrStr: 44, 94 StrStr: "xzbit", 95 NumberStr: "46", 96 }, 97 want: `{ 98 "BoolStr": "true", 99 "IntStr": "42", 100 "UintptrStr": "44", 101 "StrStr": "\"xzbit\"", 102 "NumberStr": "46" 103 }`, 104 }, 105 { 106 // See golang.org/issues/38173. 107 name: "StringDoubleEscapes", 108 in: StringTag{ 109 StrStr: "\b\f\n\r\t\"\\", 110 NumberStr: "0", // just to satisfy the roundtrip 111 }, 112 want: `{ 113 "BoolStr": "false", 114 "IntStr": "0", 115 "UintptrStr": "0", 116 "StrStr": "\"\\u0008\\u000c\\n\\r\\t\\\"\\\\\"", 117 "NumberStr": "0" 118 }`, 119 }, 120 } 121 for _, test := range tests { 122 t.Run(test.name, func(t *testing.T) { 123 // Indent with a tab prefix to make the multi-line string 124 // literals in the table nicer to read. 125 got, err := MarshalIndent(&test.in, "\t\t\t", "\t") 126 if err != nil { 127 t.Fatal(err) 128 } 129 if got := string(got); got != test.want { 130 t.Fatalf(" got: %s\nwant: %s\n", got, test.want) 131 } 132 133 // Verify that it round-trips. 134 var s2 StringTag 135 if err := Unmarshal(got, &s2); err != nil { 136 t.Fatalf("Decode: %v", err) 137 } 138 if !reflect.DeepEqual(test.in, s2) { 139 t.Fatalf("decode didn't match.\nsource: %#v\nEncoded as:\n%s\ndecode: %#v", test.in, string(got), s2) 140 } 141 }) 142 } 143} 144 145// byte slices are special even if they're renamed types. 146type renamedByte byte 147type renamedByteSlice []byte 148type renamedRenamedByteSlice []renamedByte 149 150func TestEncodeRenamedByteSlice(t *testing.T) { 151 s := renamedByteSlice("abc") 152 result, err := Marshal(s) 153 if err != nil { 154 t.Fatal(err) 155 } 156 expect := `"YWJj"` 157 if string(result) != expect { 158 t.Errorf(" got %s want %s", result, expect) 159 } 160 r := renamedRenamedByteSlice("abc") 161 result, err = Marshal(r) 162 if err != nil { 163 t.Fatal(err) 164 } 165 if string(result) != expect { 166 t.Errorf(" got %s want %s", result, expect) 167 } 168} 169 170type SamePointerNoCycle struct { 171 Ptr1, Ptr2 *SamePointerNoCycle 172} 173 174var samePointerNoCycle = &SamePointerNoCycle{} 175 176type PointerCycle struct { 177 Ptr *PointerCycle 178} 179 180var pointerCycle = &PointerCycle{} 181 182type PointerCycleIndirect struct { 183 Ptrs []interface{} 184} 185 186var pointerCycleIndirect = &PointerCycleIndirect{} 187 188func init() { 189 ptr := &SamePointerNoCycle{} 190 samePointerNoCycle.Ptr1 = ptr 191 samePointerNoCycle.Ptr2 = ptr 192 193 pointerCycle.Ptr = pointerCycle 194 pointerCycleIndirect.Ptrs = []interface{}{pointerCycleIndirect} 195} 196 197func TestSamePointerNoCycle(t *testing.T) { 198 if _, err := Marshal(samePointerNoCycle); err != nil { 199 t.Fatalf("unexpected error: %v", err) 200 } 201} 202 203var unsupportedValues = []interface{}{ 204 math.NaN(), 205 math.Inf(-1), 206 math.Inf(1), 207 pointerCycle, 208 pointerCycleIndirect, 209} 210 211func TestUnsupportedValues(t *testing.T) { 212 for _, v := range unsupportedValues { 213 if _, err := Marshal(v); err != nil { 214 if _, ok := err.(*UnsupportedValueError); !ok { 215 t.Errorf("for %v, got %T want UnsupportedValueError", v, err) 216 } 217 } else { 218 t.Errorf("for %v, expected error", v) 219 } 220 } 221} 222 223// Ref has Marshaler and Unmarshaler methods with pointer receiver. 224type Ref int 225 226func (*Ref) MarshalJSON() ([]byte, error) { 227 return []byte(`"ref"`), nil 228} 229 230func (r *Ref) UnmarshalJSON([]byte) error { 231 *r = 12 232 return nil 233} 234 235// Val has Marshaler methods with value receiver. 236type Val int 237 238func (Val) MarshalJSON() ([]byte, error) { 239 return []byte(`"val"`), nil 240} 241 242// RefText has Marshaler and Unmarshaler methods with pointer receiver. 243type RefText int 244 245func (*RefText) MarshalText() ([]byte, error) { 246 return []byte(`"ref"`), nil 247} 248 249func (r *RefText) UnmarshalText([]byte) error { 250 *r = 13 251 return nil 252} 253 254// ValText has Marshaler methods with value receiver. 255type ValText int 256 257func (ValText) MarshalText() ([]byte, error) { 258 return []byte(`"val"`), nil 259} 260 261func TestRefValMarshal(t *testing.T) { 262 var s = struct { 263 R0 Ref 264 R1 *Ref 265 R2 RefText 266 R3 *RefText 267 V0 Val 268 V1 *Val 269 V2 ValText 270 V3 *ValText 271 }{ 272 R0: 12, 273 R1: new(Ref), 274 R2: 14, 275 R3: new(RefText), 276 V0: 13, 277 V1: new(Val), 278 V2: 15, 279 V3: new(ValText), 280 } 281 const want = `{"R0":"ref","R1":"ref","R2":"\"ref\"","R3":"\"ref\"","V0":"val","V1":"val","V2":"\"val\"","V3":"\"val\""}` 282 b, err := Marshal(&s) 283 if err != nil { 284 t.Fatalf("Marshal: %v", err) 285 } 286 if got := string(b); got != want { 287 t.Errorf("got %q, want %q", got, want) 288 } 289} 290 291// C implements Marshaler and returns unescaped JSON. 292type C int 293 294func (C) MarshalJSON() ([]byte, error) { 295 return []byte(`"<&>"`), nil 296} 297 298// CText implements Marshaler and returns unescaped text. 299type CText int 300 301func (CText) MarshalText() ([]byte, error) { 302 return []byte(`"<&>"`), nil 303} 304 305func TestMarshalerEscaping(t *testing.T) { 306 var c C 307 want := `"\u003c\u0026\u003e"` 308 b, err := Marshal(c) 309 if err != nil { 310 t.Fatalf("Marshal(c): %v", err) 311 } 312 if got := string(b); got != want { 313 t.Errorf("Marshal(c) = %#q, want %#q", got, want) 314 } 315 316 var ct CText 317 want = `"\"\u003c\u0026\u003e\""` 318 b, err = Marshal(ct) 319 if err != nil { 320 t.Fatalf("Marshal(ct): %v", err) 321 } 322 if got := string(b); got != want { 323 t.Errorf("Marshal(ct) = %#q, want %#q", got, want) 324 } 325} 326 327func TestAnonymousFields(t *testing.T) { 328 tests := []struct { 329 label string // Test name 330 makeInput func() interface{} // Function to create input value 331 want string // Expected JSON output 332 }{{ 333 // Both S1 and S2 have a field named X. From the perspective of S, 334 // it is ambiguous which one X refers to. 335 // This should not serialize either field. 336 label: "AmbiguousField", 337 makeInput: func() interface{} { 338 type ( 339 S1 struct{ x, X int } 340 S2 struct{ x, X int } 341 S struct { 342 S1 343 S2 344 } 345 ) 346 return S{S1{1, 2}, S2{3, 4}} 347 }, 348 want: `{}`, 349 }, { 350 label: "DominantField", 351 // Both S1 and S2 have a field named X, but since S has an X field as 352 // well, it takes precedence over S1.X and S2.X. 353 makeInput: func() interface{} { 354 type ( 355 S1 struct{ x, X int } 356 S2 struct{ x, X int } 357 S struct { 358 S1 359 S2 360 x, X int 361 } 362 ) 363 return S{S1{1, 2}, S2{3, 4}, 5, 6} 364 }, 365 want: `{"X":6}`, 366 }, { 367 // Unexported embedded field of non-struct type should not be serialized. 368 label: "UnexportedEmbeddedInt", 369 makeInput: func() interface{} { 370 type ( 371 myInt int 372 S struct{ myInt } 373 ) 374 return S{5} 375 }, 376 want: `{}`, 377 }, { 378 // Exported embedded field of non-struct type should be serialized. 379 label: "ExportedEmbeddedInt", 380 makeInput: func() interface{} { 381 type ( 382 MyInt int 383 S struct{ MyInt } 384 ) 385 return S{5} 386 }, 387 want: `{"MyInt":5}`, 388 }, { 389 // Unexported embedded field of pointer to non-struct type 390 // should not be serialized. 391 label: "UnexportedEmbeddedIntPointer", 392 makeInput: func() interface{} { 393 type ( 394 myInt int 395 S struct{ *myInt } 396 ) 397 s := S{new(myInt)} 398 *s.myInt = 5 399 return s 400 }, 401 want: `{}`, 402 }, { 403 // Exported embedded field of pointer to non-struct type 404 // should be serialized. 405 label: "ExportedEmbeddedIntPointer", 406 makeInput: func() interface{} { 407 type ( 408 MyInt int 409 S struct{ *MyInt } 410 ) 411 s := S{new(MyInt)} 412 *s.MyInt = 5 413 return s 414 }, 415 want: `{"MyInt":5}`, 416 }, { 417 // Exported fields of embedded structs should have their 418 // exported fields be serialized regardless of whether the struct types 419 // themselves are exported. 420 label: "EmbeddedStruct", 421 makeInput: func() interface{} { 422 type ( 423 s1 struct{ x, X int } 424 S2 struct{ y, Y int } 425 S struct { 426 s1 427 S2 428 } 429 ) 430 return S{s1{1, 2}, S2{3, 4}} 431 }, 432 want: `{"X":2,"Y":4}`, 433 }, { 434 // Exported fields of pointers to embedded structs should have their 435 // exported fields be serialized regardless of whether the struct types 436 // themselves are exported. 437 label: "EmbeddedStructPointer", 438 makeInput: func() interface{} { 439 type ( 440 s1 struct{ x, X int } 441 S2 struct{ y, Y int } 442 S struct { 443 *s1 444 *S2 445 } 446 ) 447 return S{&s1{1, 2}, &S2{3, 4}} 448 }, 449 want: `{"X":2,"Y":4}`, 450 }, { 451 // Exported fields on embedded unexported structs at multiple levels 452 // of nesting should still be serialized. 453 label: "NestedStructAndInts", 454 makeInput: func() interface{} { 455 type ( 456 MyInt1 int 457 MyInt2 int 458 myInt int 459 s2 struct { 460 MyInt2 461 myInt 462 } 463 s1 struct { 464 MyInt1 465 myInt 466 s2 467 } 468 S struct { 469 s1 470 myInt 471 } 472 ) 473 return S{s1{1, 2, s2{3, 4}}, 6} 474 }, 475 want: `{"MyInt1":1,"MyInt2":3}`, 476 }, { 477 // If an anonymous struct pointer field is nil, we should ignore 478 // the embedded fields behind it. Not properly doing so may 479 // result in the wrong output or reflect panics. 480 label: "EmbeddedFieldBehindNilPointer", 481 makeInput: func() interface{} { 482 type ( 483 S2 struct{ Field string } 484 S struct{ *S2 } 485 ) 486 return S{} 487 }, 488 want: `{}`, 489 }} 490 491 for _, tt := range tests { 492 t.Run(tt.label, func(t *testing.T) { 493 b, err := Marshal(tt.makeInput()) 494 if err != nil { 495 t.Fatalf("Marshal() = %v, want nil error", err) 496 } 497 if string(b) != tt.want { 498 t.Fatalf("Marshal() = %q, want %q", b, tt.want) 499 } 500 }) 501 } 502} 503 504type BugA struct { 505 S string 506} 507 508type BugB struct { 509 BugA 510 S string 511} 512 513type BugC struct { 514 S string 515} 516 517// Legal Go: We never use the repeated embedded field (S). 518type BugX struct { 519 A int 520 BugA 521 BugB 522} 523 524// golang.org/issue/16042. 525// Even if a nil interface value is passed in, as long as 526// it implements Marshaler, it should be marshaled. 527type nilJSONMarshaler string 528 529func (nm *nilJSONMarshaler) MarshalJSON() ([]byte, error) { 530 if nm == nil { 531 return Marshal("0zenil0") 532 } 533 return Marshal("zenil:" + string(*nm)) 534} 535 536// golang.org/issue/34235. 537// Even if a nil interface value is passed in, as long as 538// it implements encoding.TextMarshaler, it should be marshaled. 539type nilTextMarshaler string 540 541func (nm *nilTextMarshaler) MarshalText() ([]byte, error) { 542 if nm == nil { 543 return []byte("0zenil0"), nil 544 } 545 return []byte("zenil:" + string(*nm)), nil 546} 547 548// See golang.org/issue/16042 and golang.org/issue/34235. 549func TestNilMarshal(t *testing.T) { 550 testCases := []struct { 551 v interface{} 552 want string 553 }{ 554 {v: nil, want: `null`}, 555 {v: new(float64), want: `0`}, 556 {v: []interface{}(nil), want: `null`}, 557 {v: []string(nil), want: `null`}, 558 {v: map[string]string(nil), want: `null`}, 559 {v: []byte(nil), want: `null`}, 560 {v: struct{ M string }{"gopher"}, want: `{"M":"gopher"}`}, 561 {v: struct{ M Marshaler }{}, want: `{"M":null}`}, 562 {v: struct{ M Marshaler }{(*nilJSONMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, 563 {v: struct{ M interface{} }{(*nilJSONMarshaler)(nil)}, want: `{"M":null}`}, 564 {v: struct{ M encoding.TextMarshaler }{}, want: `{"M":null}`}, 565 {v: struct{ M encoding.TextMarshaler }{(*nilTextMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, 566 {v: struct{ M interface{} }{(*nilTextMarshaler)(nil)}, want: `{"M":null}`}, 567 } 568 569 for _, tt := range testCases { 570 out, err := Marshal(tt.v) 571 if err != nil || string(out) != tt.want { 572 t.Errorf("Marshal(%#v) = %#q, %#v, want %#q, nil", tt.v, out, err, tt.want) 573 continue 574 } 575 } 576} 577 578// Issue 5245. 579func TestEmbeddedBug(t *testing.T) { 580 v := BugB{ 581 BugA{"A"}, 582 "B", 583 } 584 b, err := Marshal(v) 585 if err != nil { 586 t.Fatal("Marshal:", err) 587 } 588 want := `{"S":"B"}` 589 got := string(b) 590 if got != want { 591 t.Fatalf("Marshal: got %s want %s", got, want) 592 } 593 // Now check that the duplicate field, S, does not appear. 594 x := BugX{ 595 A: 23, 596 } 597 b, err = Marshal(x) 598 if err != nil { 599 t.Fatal("Marshal:", err) 600 } 601 want = `{"A":23}` 602 got = string(b) 603 if got != want { 604 t.Fatalf("Marshal: got %s want %s", got, want) 605 } 606} 607 608type BugD struct { // Same as BugA after tagging. 609 XXX string `json:"S"` 610} 611 612// BugD's tagged S field should dominate BugA's. 613type BugY struct { 614 BugA 615 BugD 616} 617 618// Test that a field with a tag dominates untagged fields. 619func TestTaggedFieldDominates(t *testing.T) { 620 v := BugY{ 621 BugA{"BugA"}, 622 BugD{"BugD"}, 623 } 624 b, err := Marshal(v) 625 if err != nil { 626 t.Fatal("Marshal:", err) 627 } 628 want := `{"S":"BugD"}` 629 got := string(b) 630 if got != want { 631 t.Fatalf("Marshal: got %s want %s", got, want) 632 } 633} 634 635// There are no tags here, so S should not appear. 636type BugZ struct { 637 BugA 638 BugC 639 BugY // Contains a tagged S field through BugD; should not dominate. 640} 641 642func TestDuplicatedFieldDisappears(t *testing.T) { 643 v := BugZ{ 644 BugA{"BugA"}, 645 BugC{"BugC"}, 646 BugY{ 647 BugA{"nested BugA"}, 648 BugD{"nested BugD"}, 649 }, 650 } 651 b, err := Marshal(v) 652 if err != nil { 653 t.Fatal("Marshal:", err) 654 } 655 want := `{}` 656 got := string(b) 657 if got != want { 658 t.Fatalf("Marshal: got %s want %s", got, want) 659 } 660} 661 662func TestStringBytes(t *testing.T) { 663 t.Parallel() 664 // Test that encodeState.stringBytes and encodeState.string use the same encoding. 665 var r []rune 666 for i := '\u0000'; i <= unicode.MaxRune; i++ { 667 if testing.Short() && i > 1000 { 668 i = unicode.MaxRune 669 } 670 r = append(r, i) 671 } 672 s := string(r) + "\xff\xff\xffhello" // some invalid UTF-8 too 673 674 for _, escapeHTML := range []bool{true, false} { 675 es := &encodeState{} 676 es.string(s, escapeHTML) 677 678 esBytes := &encodeState{} 679 esBytes.stringBytes([]byte(s), escapeHTML) 680 681 enc := es.Buffer.String() 682 encBytes := esBytes.Buffer.String() 683 if enc != encBytes { 684 i := 0 685 for i < len(enc) && i < len(encBytes) && enc[i] == encBytes[i] { 686 i++ 687 } 688 enc = enc[i:] 689 encBytes = encBytes[i:] 690 i = 0 691 for i < len(enc) && i < len(encBytes) && enc[len(enc)-i-1] == encBytes[len(encBytes)-i-1] { 692 i++ 693 } 694 enc = enc[:len(enc)-i] 695 encBytes = encBytes[:len(encBytes)-i] 696 697 if len(enc) > 20 { 698 enc = enc[:20] + "..." 699 } 700 if len(encBytes) > 20 { 701 encBytes = encBytes[:20] + "..." 702 } 703 704 t.Errorf("with escapeHTML=%t, encodings differ at %#q vs %#q", 705 escapeHTML, enc, encBytes) 706 } 707 } 708} 709 710func TestIssue10281(t *testing.T) { 711 type Foo struct { 712 N Number 713 } 714 x := Foo{Number(`invalid`)} 715 716 b, err := Marshal(&x) 717 if err == nil { 718 t.Errorf("Marshal(&x) = %#q; want error", b) 719 } 720} 721 722func TestHTMLEscape(t *testing.T) { 723 var b, want bytes.Buffer 724 m := `{"M":"<html>foo &` + "\xe2\x80\xa8 \xe2\x80\xa9" + `</html>"}` 725 want.Write([]byte(`{"M":"\u003chtml\u003efoo \u0026\u2028 \u2029\u003c/html\u003e"}`)) 726 HTMLEscape(&b, []byte(m)) 727 if !bytes.Equal(b.Bytes(), want.Bytes()) { 728 t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes()) 729 } 730} 731 732// golang.org/issue/8582 733func TestEncodePointerString(t *testing.T) { 734 type stringPointer struct { 735 N *int64 `json:"n,string"` 736 } 737 var n int64 = 42 738 b, err := Marshal(stringPointer{N: &n}) 739 if err != nil { 740 t.Fatalf("Marshal: %v", err) 741 } 742 if got, want := string(b), `{"n":"42"}`; got != want { 743 t.Errorf("Marshal = %s, want %s", got, want) 744 } 745 var back stringPointer 746 err = Unmarshal(b, &back) 747 if err != nil { 748 t.Fatalf("Unmarshal: %v", err) 749 } 750 if back.N == nil { 751 t.Fatalf("Unmarshaled nil N field") 752 } 753 if *back.N != 42 { 754 t.Fatalf("*N = %d; want 42", *back.N) 755 } 756} 757 758var encodeStringTests = []struct { 759 in string 760 out string 761}{ 762 {"\x00", `"\u0000"`}, 763 {"\x01", `"\u0001"`}, 764 {"\x02", `"\u0002"`}, 765 {"\x03", `"\u0003"`}, 766 {"\x04", `"\u0004"`}, 767 {"\x05", `"\u0005"`}, 768 {"\x06", `"\u0006"`}, 769 {"\x07", `"\u0007"`}, 770 {"\x08", `"\u0008"`}, 771 {"\x09", `"\t"`}, 772 {"\x0a", `"\n"`}, 773 {"\x0b", `"\u000b"`}, 774 {"\x0c", `"\u000c"`}, 775 {"\x0d", `"\r"`}, 776 {"\x0e", `"\u000e"`}, 777 {"\x0f", `"\u000f"`}, 778 {"\x10", `"\u0010"`}, 779 {"\x11", `"\u0011"`}, 780 {"\x12", `"\u0012"`}, 781 {"\x13", `"\u0013"`}, 782 {"\x14", `"\u0014"`}, 783 {"\x15", `"\u0015"`}, 784 {"\x16", `"\u0016"`}, 785 {"\x17", `"\u0017"`}, 786 {"\x18", `"\u0018"`}, 787 {"\x19", `"\u0019"`}, 788 {"\x1a", `"\u001a"`}, 789 {"\x1b", `"\u001b"`}, 790 {"\x1c", `"\u001c"`}, 791 {"\x1d", `"\u001d"`}, 792 {"\x1e", `"\u001e"`}, 793 {"\x1f", `"\u001f"`}, 794} 795 796func TestEncodeString(t *testing.T) { 797 for _, tt := range encodeStringTests { 798 b, err := Marshal(tt.in) 799 if err != nil { 800 t.Errorf("Marshal(%q): %v", tt.in, err) 801 continue 802 } 803 out := string(b) 804 if out != tt.out { 805 t.Errorf("Marshal(%q) = %#q, want %#q", tt.in, out, tt.out) 806 } 807 } 808} 809 810type jsonbyte byte 811 812func (b jsonbyte) MarshalJSON() ([]byte, error) { return tenc(`{"JB":%d}`, b) } 813 814type textbyte byte 815 816func (b textbyte) MarshalText() ([]byte, error) { return tenc(`TB:%d`, b) } 817 818type jsonint int 819 820func (i jsonint) MarshalJSON() ([]byte, error) { return tenc(`{"JI":%d}`, i) } 821 822type textint int 823 824func (i textint) MarshalText() ([]byte, error) { return tenc(`TI:%d`, i) } 825 826func tenc(format string, a ...interface{}) ([]byte, error) { 827 var buf bytes.Buffer 828 fmt.Fprintf(&buf, format, a...) 829 return buf.Bytes(), nil 830} 831 832// Issue 13783 833func TestEncodeBytekind(t *testing.T) { 834 testdata := []struct { 835 data interface{} 836 want string 837 }{ 838 {byte(7), "7"}, 839 {jsonbyte(7), `{"JB":7}`}, 840 {textbyte(4), `"TB:4"`}, 841 {jsonint(5), `{"JI":5}`}, 842 {textint(1), `"TI:1"`}, 843 {[]byte{0, 1}, `"AAE="`}, 844 {[]jsonbyte{0, 1}, `[{"JB":0},{"JB":1}]`}, 845 {[][]jsonbyte{{0, 1}, {3}}, `[[{"JB":0},{"JB":1}],[{"JB":3}]]`}, 846 {[]textbyte{2, 3}, `["TB:2","TB:3"]`}, 847 {[]jsonint{5, 4}, `[{"JI":5},{"JI":4}]`}, 848 {[]textint{9, 3}, `["TI:9","TI:3"]`}, 849 {[]int{9, 3}, `[9,3]`}, 850 } 851 for _, d := range testdata { 852 js, err := Marshal(d.data) 853 if err != nil { 854 t.Error(err) 855 continue 856 } 857 got, want := string(js), d.want 858 if got != want { 859 t.Errorf("got %s, want %s", got, want) 860 } 861 } 862} 863 864func TestTextMarshalerMapKeysAreSorted(t *testing.T) { 865 b, err := Marshal(map[unmarshalerText]int{ 866 {"x", "y"}: 1, 867 {"y", "x"}: 2, 868 {"a", "z"}: 3, 869 {"z", "a"}: 4, 870 }) 871 if err != nil { 872 t.Fatalf("Failed to Marshal text.Marshaler: %v", err) 873 } 874 const want = `{"a:z":3,"x:y":1,"y:x":2,"z:a":4}` 875 if string(b) != want { 876 t.Errorf("Marshal map with text.Marshaler keys: got %#q, want %#q", b, want) 877 } 878} 879 880// https://golang.org/issue/33675 881func TestNilMarshalerTextMapKey(t *testing.T) { 882 b, err := Marshal(map[*unmarshalerText]int{ 883 (*unmarshalerText)(nil): 1, 884 {"A", "B"}: 2, 885 }) 886 if err != nil { 887 t.Fatalf("Failed to Marshal *text.Marshaler: %v", err) 888 } 889 const want = `{"":1,"A:B":2}` 890 if string(b) != want { 891 t.Errorf("Marshal map with *text.Marshaler keys: got %#q, want %#q", b, want) 892 } 893} 894 895var re = regexp.MustCompile 896 897// syntactic checks on form of marshaled floating point numbers. 898var badFloatREs = []*regexp.Regexp{ 899 re(`p`), // no binary exponential notation 900 re(`^\+`), // no leading + sign 901 re(`^-?0[^.]`), // no unnecessary leading zeros 902 re(`^-?\.`), // leading zero required before decimal point 903 re(`\.(e|$)`), // no trailing decimal 904 re(`\.[0-9]+0(e|$)`), // no trailing zero in fraction 905 re(`^-?(0|[0-9]{2,})\..*e`), // exponential notation must have normalized mantissa 906 re(`e[0-9]`), // positive exponent must be signed 907 re(`e[+-]0`), // exponent must not have leading zeros 908 re(`e-[1-6]$`), // not tiny enough for exponential notation 909 re(`e+(.|1.|20)$`), // not big enough for exponential notation 910 re(`^-?0\.0000000`), // too tiny, should use exponential notation 911 re(`^-?[0-9]{22}`), // too big, should use exponential notation 912 re(`[1-9][0-9]{16}[1-9]`), // too many significant digits in integer 913 re(`[1-9][0-9.]{17}[1-9]`), // too many significant digits in decimal 914 // below here for float32 only 915 re(`[1-9][0-9]{8}[1-9]`), // too many significant digits in integer 916 re(`[1-9][0-9.]{9}[1-9]`), // too many significant digits in decimal 917} 918 919func TestMarshalFloat(t *testing.T) { 920 t.Parallel() 921 nfail := 0 922 test := func(f float64, bits int) { 923 vf := interface{}(f) 924 if bits == 32 { 925 f = float64(float32(f)) // round 926 vf = float32(f) 927 } 928 bout, err := Marshal(vf) 929 if err != nil { 930 t.Errorf("Marshal(%T(%g)): %v", vf, vf, err) 931 nfail++ 932 return 933 } 934 out := string(bout) 935 936 // result must convert back to the same float 937 g, err := strconv.ParseFloat(out, bits) 938 if err != nil { 939 t.Errorf("Marshal(%T(%g)) = %q, cannot parse back: %v", vf, vf, out, err) 940 nfail++ 941 return 942 } 943 if f != g || fmt.Sprint(f) != fmt.Sprint(g) { // fmt.Sprint handles ±0 944 t.Errorf("Marshal(%T(%g)) = %q (is %g, not %g)", vf, vf, out, float32(g), vf) 945 nfail++ 946 return 947 } 948 949 bad := badFloatREs 950 if bits == 64 { 951 bad = bad[:len(bad)-2] 952 } 953 for _, re := range bad { 954 if re.MatchString(out) { 955 t.Errorf("Marshal(%T(%g)) = %q, must not match /%s/", vf, vf, out, re) 956 nfail++ 957 return 958 } 959 } 960 } 961 962 var ( 963 bigger = math.Inf(+1) 964 smaller = math.Inf(-1) 965 ) 966 967 var digits = "1.2345678901234567890123" 968 for i := len(digits); i >= 2; i-- { 969 if testing.Short() && i < len(digits)-4 { 970 break 971 } 972 for exp := -30; exp <= 30; exp++ { 973 for _, sign := range "+-" { 974 for bits := 32; bits <= 64; bits += 32 { 975 s := fmt.Sprintf("%c%se%d", sign, digits[:i], exp) 976 f, err := strconv.ParseFloat(s, bits) 977 if err != nil { 978 log.Fatal(err) 979 } 980 next := math.Nextafter 981 if bits == 32 { 982 next = func(g, h float64) float64 { 983 return float64(math.Nextafter32(float32(g), float32(h))) 984 } 985 } 986 test(f, bits) 987 test(next(f, bigger), bits) 988 test(next(f, smaller), bits) 989 if nfail > 50 { 990 t.Fatalf("stopping test early") 991 } 992 } 993 } 994 } 995 } 996 test(0, 64) 997 test(math.Copysign(0, -1), 64) 998 test(0, 32) 999 test(math.Copysign(0, -1), 32) 1000} 1001 1002func TestMarshalRawMessageValue(t *testing.T) { 1003 type ( 1004 T1 struct { 1005 M RawMessage `json:",omitempty"` 1006 } 1007 T2 struct { 1008 M *RawMessage `json:",omitempty"` 1009 } 1010 ) 1011 1012 var ( 1013 rawNil = RawMessage(nil) 1014 rawEmpty = RawMessage([]byte{}) 1015 rawText = RawMessage([]byte(`"foo"`)) 1016 ) 1017 1018 tests := []struct { 1019 in interface{} 1020 want string 1021 ok bool 1022 }{ 1023 // Test with nil RawMessage. 1024 {rawNil, "null", true}, 1025 {&rawNil, "null", true}, 1026 {[]interface{}{rawNil}, "[null]", true}, 1027 {&[]interface{}{rawNil}, "[null]", true}, 1028 {[]interface{}{&rawNil}, "[null]", true}, 1029 {&[]interface{}{&rawNil}, "[null]", true}, 1030 {struct{ M RawMessage }{rawNil}, `{"M":null}`, true}, 1031 {&struct{ M RawMessage }{rawNil}, `{"M":null}`, true}, 1032 {struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true}, 1033 {&struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true}, 1034 {map[string]interface{}{"M": rawNil}, `{"M":null}`, true}, 1035 {&map[string]interface{}{"M": rawNil}, `{"M":null}`, true}, 1036 {map[string]interface{}{"M": &rawNil}, `{"M":null}`, true}, 1037 {&map[string]interface{}{"M": &rawNil}, `{"M":null}`, true}, 1038 {T1{rawNil}, "{}", true}, 1039 {T2{&rawNil}, `{"M":null}`, true}, 1040 {&T1{rawNil}, "{}", true}, 1041 {&T2{&rawNil}, `{"M":null}`, true}, 1042 1043 // Test with empty, but non-nil, RawMessage. 1044 {rawEmpty, "", false}, 1045 {&rawEmpty, "", false}, 1046 {[]interface{}{rawEmpty}, "", false}, 1047 {&[]interface{}{rawEmpty}, "", false}, 1048 {[]interface{}{&rawEmpty}, "", false}, 1049 {&[]interface{}{&rawEmpty}, "", false}, 1050 {struct{ X RawMessage }{rawEmpty}, "", false}, 1051 {&struct{ X RawMessage }{rawEmpty}, "", false}, 1052 {struct{ X *RawMessage }{&rawEmpty}, "", false}, 1053 {&struct{ X *RawMessage }{&rawEmpty}, "", false}, 1054 {map[string]interface{}{"nil": rawEmpty}, "", false}, 1055 {&map[string]interface{}{"nil": rawEmpty}, "", false}, 1056 {map[string]interface{}{"nil": &rawEmpty}, "", false}, 1057 {&map[string]interface{}{"nil": &rawEmpty}, "", false}, 1058 {T1{rawEmpty}, "{}", true}, 1059 {T2{&rawEmpty}, "", false}, 1060 {&T1{rawEmpty}, "{}", true}, 1061 {&T2{&rawEmpty}, "", false}, 1062 1063 // Test with RawMessage with some text. 1064 // 1065 // The tests below marked with Issue6458 used to generate "ImZvbyI=" instead "foo". 1066 // This behavior was intentionally changed in Go 1.8. 1067 // See https://golang.org/issues/14493#issuecomment-255857318 1068 {rawText, `"foo"`, true}, // Issue6458 1069 {&rawText, `"foo"`, true}, 1070 {[]interface{}{rawText}, `["foo"]`, true}, // Issue6458 1071 {&[]interface{}{rawText}, `["foo"]`, true}, // Issue6458 1072 {[]interface{}{&rawText}, `["foo"]`, true}, 1073 {&[]interface{}{&rawText}, `["foo"]`, true}, 1074 {struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true}, // Issue6458 1075 {&struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true}, 1076 {struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true}, 1077 {&struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true}, 1078 {map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 1079 {&map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 1080 {map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true}, 1081 {&map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true}, 1082 {T1{rawText}, `{"M":"foo"}`, true}, // Issue6458 1083 {T2{&rawText}, `{"M":"foo"}`, true}, 1084 {&T1{rawText}, `{"M":"foo"}`, true}, 1085 {&T2{&rawText}, `{"M":"foo"}`, true}, 1086 } 1087 1088 for i, tt := range tests { 1089 b, err := Marshal(tt.in) 1090 if ok := (err == nil); ok != tt.ok { 1091 if err != nil { 1092 t.Errorf("test %d, unexpected failure: %v", i, err) 1093 } else { 1094 t.Errorf("test %d, unexpected success", i) 1095 } 1096 } 1097 if got := string(b); got != tt.want { 1098 t.Errorf("test %d, Marshal(%#v) = %q, want %q", i, tt.in, got, tt.want) 1099 } 1100 } 1101} 1102 1103type marshalPanic struct{} 1104 1105func (marshalPanic) MarshalJSON() ([]byte, error) { panic(0xdead) } 1106 1107func TestMarshalPanic(t *testing.T) { 1108 defer func() { 1109 if got := recover(); !reflect.DeepEqual(got, 0xdead) { 1110 t.Errorf("panic() = (%T)(%v), want 0xdead", got, got) 1111 } 1112 }() 1113 Marshal(&marshalPanic{}) 1114 t.Error("Marshal should have panicked") 1115} 1116 1117func TestMarshalUncommonFieldNames(t *testing.T) { 1118 v := struct { 1119 A0, À, Aβ int 1120 }{} 1121 b, err := Marshal(v) 1122 if err != nil { 1123 t.Fatal("Marshal:", err) 1124 } 1125 want := `{"A0":0,"À":0,"Aβ":0}` 1126 got := string(b) 1127 if got != want { 1128 t.Fatalf("Marshal: got %s want %s", got, want) 1129 } 1130} 1131 1132func TestMarshalerError(t *testing.T) { 1133 s := "test variable" 1134 st := reflect.TypeOf(s) 1135 errText := "json: test error" 1136 1137 tests := []struct { 1138 err *MarshalerError 1139 want string 1140 }{ 1141 { 1142 &MarshalerError{st, fmt.Errorf(errText), ""}, 1143 "json: error calling MarshalJSON for type " + st.String() + ": " + errText, 1144 }, 1145 { 1146 &MarshalerError{st, fmt.Errorf(errText), "TestMarshalerError"}, 1147 "json: error calling TestMarshalerError for type " + st.String() + ": " + errText, 1148 }, 1149 } 1150 1151 for i, tt := range tests { 1152 got := tt.err.Error() 1153 if got != tt.want { 1154 t.Errorf("MarshalerError test %d, got: %s, want: %s", i, got, tt.want) 1155 } 1156 } 1157} 1158