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