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