github.com/kdevb0x/go@v0.0.0-20180115030120-39687051e9e7/src/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 "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 410 for _, tt := range tests { 411 t.Run(tt.label, func(t *testing.T) { 412 b, err := Marshal(tt.makeInput()) 413 if err != nil { 414 t.Fatalf("Marshal() = %v, want nil error", err) 415 } 416 if string(b) != tt.want { 417 t.Fatalf("Marshal() = %q, want %q", b, tt.want) 418 } 419 }) 420 } 421 } 422 423 type BugA struct { 424 S string 425 } 426 427 type BugB struct { 428 BugA 429 S string 430 } 431 432 type BugC struct { 433 S string 434 } 435 436 // Legal Go: We never use the repeated embedded field (S). 437 type BugX struct { 438 A int 439 BugA 440 BugB 441 } 442 443 // Issue 16042. Even if a nil interface value is passed in 444 // as long as it implements MarshalJSON, it should be marshaled. 445 type nilMarshaler string 446 447 func (nm *nilMarshaler) MarshalJSON() ([]byte, error) { 448 if nm == nil { 449 return Marshal("0zenil0") 450 } 451 return Marshal("zenil:" + string(*nm)) 452 } 453 454 // Issue 16042. 455 func TestNilMarshal(t *testing.T) { 456 testCases := []struct { 457 v interface{} 458 want string 459 }{ 460 {v: nil, want: `null`}, 461 {v: new(float64), want: `0`}, 462 {v: []interface{}(nil), want: `null`}, 463 {v: []string(nil), want: `null`}, 464 {v: map[string]string(nil), want: `null`}, 465 {v: []byte(nil), want: `null`}, 466 {v: struct{ M string }{"gopher"}, want: `{"M":"gopher"}`}, 467 {v: struct{ M Marshaler }{}, want: `{"M":null}`}, 468 {v: struct{ M Marshaler }{(*nilMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, 469 {v: struct{ M interface{} }{(*nilMarshaler)(nil)}, want: `{"M":null}`}, 470 } 471 472 for _, tt := range testCases { 473 out, err := Marshal(tt.v) 474 if err != nil || string(out) != tt.want { 475 t.Errorf("Marshal(%#v) = %#q, %#v, want %#q, nil", tt.v, out, err, tt.want) 476 continue 477 } 478 } 479 } 480 481 // Issue 5245. 482 func TestEmbeddedBug(t *testing.T) { 483 v := BugB{ 484 BugA{"A"}, 485 "B", 486 } 487 b, err := Marshal(v) 488 if err != nil { 489 t.Fatal("Marshal:", err) 490 } 491 want := `{"S":"B"}` 492 got := string(b) 493 if got != want { 494 t.Fatalf("Marshal: got %s want %s", got, want) 495 } 496 // Now check that the duplicate field, S, does not appear. 497 x := BugX{ 498 A: 23, 499 } 500 b, err = Marshal(x) 501 if err != nil { 502 t.Fatal("Marshal:", err) 503 } 504 want = `{"A":23}` 505 got = string(b) 506 if got != want { 507 t.Fatalf("Marshal: got %s want %s", got, want) 508 } 509 } 510 511 type BugD struct { // Same as BugA after tagging. 512 XXX string `json:"S"` 513 } 514 515 // BugD's tagged S field should dominate BugA's. 516 type BugY struct { 517 BugA 518 BugD 519 } 520 521 // Test that a field with a tag dominates untagged fields. 522 func TestTaggedFieldDominates(t *testing.T) { 523 v := BugY{ 524 BugA{"BugA"}, 525 BugD{"BugD"}, 526 } 527 b, err := Marshal(v) 528 if err != nil { 529 t.Fatal("Marshal:", err) 530 } 531 want := `{"S":"BugD"}` 532 got := string(b) 533 if got != want { 534 t.Fatalf("Marshal: got %s want %s", got, want) 535 } 536 } 537 538 // There are no tags here, so S should not appear. 539 type BugZ struct { 540 BugA 541 BugC 542 BugY // Contains a tagged S field through BugD; should not dominate. 543 } 544 545 func TestDuplicatedFieldDisappears(t *testing.T) { 546 v := BugZ{ 547 BugA{"BugA"}, 548 BugC{"BugC"}, 549 BugY{ 550 BugA{"nested BugA"}, 551 BugD{"nested BugD"}, 552 }, 553 } 554 b, err := Marshal(v) 555 if err != nil { 556 t.Fatal("Marshal:", err) 557 } 558 want := `{}` 559 got := string(b) 560 if got != want { 561 t.Fatalf("Marshal: got %s want %s", got, want) 562 } 563 } 564 565 func TestStringBytes(t *testing.T) { 566 t.Parallel() 567 // Test that encodeState.stringBytes and encodeState.string use the same encoding. 568 var r []rune 569 for i := '\u0000'; i <= unicode.MaxRune; i++ { 570 r = append(r, i) 571 } 572 s := string(r) + "\xff\xff\xffhello" // some invalid UTF-8 too 573 574 for _, escapeHTML := range []bool{true, false} { 575 es := &encodeState{} 576 es.string(s, escapeHTML) 577 578 esBytes := &encodeState{} 579 esBytes.stringBytes([]byte(s), escapeHTML) 580 581 enc := es.Buffer.String() 582 encBytes := esBytes.Buffer.String() 583 if enc != encBytes { 584 i := 0 585 for i < len(enc) && i < len(encBytes) && enc[i] == encBytes[i] { 586 i++ 587 } 588 enc = enc[i:] 589 encBytes = encBytes[i:] 590 i = 0 591 for i < len(enc) && i < len(encBytes) && enc[len(enc)-i-1] == encBytes[len(encBytes)-i-1] { 592 i++ 593 } 594 enc = enc[:len(enc)-i] 595 encBytes = encBytes[:len(encBytes)-i] 596 597 if len(enc) > 20 { 598 enc = enc[:20] + "..." 599 } 600 if len(encBytes) > 20 { 601 encBytes = encBytes[:20] + "..." 602 } 603 604 t.Errorf("with escapeHTML=%t, encodings differ at %#q vs %#q", 605 escapeHTML, enc, encBytes) 606 } 607 } 608 } 609 610 func TestIssue10281(t *testing.T) { 611 type Foo struct { 612 N Number 613 } 614 x := Foo{Number(`invalid`)} 615 616 b, err := Marshal(&x) 617 if err == nil { 618 t.Errorf("Marshal(&x) = %#q; want error", b) 619 } 620 } 621 622 func TestHTMLEscape(t *testing.T) { 623 var b, want bytes.Buffer 624 m := `{"M":"<html>foo &` + "\xe2\x80\xa8 \xe2\x80\xa9" + `</html>"}` 625 want.Write([]byte(`{"M":"\u003chtml\u003efoo \u0026\u2028 \u2029\u003c/html\u003e"}`)) 626 HTMLEscape(&b, []byte(m)) 627 if !bytes.Equal(b.Bytes(), want.Bytes()) { 628 t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes()) 629 } 630 } 631 632 // golang.org/issue/8582 633 func TestEncodePointerString(t *testing.T) { 634 type stringPointer struct { 635 N *int64 `json:"n,string"` 636 } 637 var n int64 = 42 638 b, err := Marshal(stringPointer{N: &n}) 639 if err != nil { 640 t.Fatalf("Marshal: %v", err) 641 } 642 if got, want := string(b), `{"n":"42"}`; got != want { 643 t.Errorf("Marshal = %s, want %s", got, want) 644 } 645 var back stringPointer 646 err = Unmarshal(b, &back) 647 if err != nil { 648 t.Fatalf("Unmarshal: %v", err) 649 } 650 if back.N == nil { 651 t.Fatalf("Unmarshaled nil N field") 652 } 653 if *back.N != 42 { 654 t.Fatalf("*N = %d; want 42", *back.N) 655 } 656 } 657 658 var encodeStringTests = []struct { 659 in string 660 out string 661 }{ 662 {"\x00", `"\u0000"`}, 663 {"\x01", `"\u0001"`}, 664 {"\x02", `"\u0002"`}, 665 {"\x03", `"\u0003"`}, 666 {"\x04", `"\u0004"`}, 667 {"\x05", `"\u0005"`}, 668 {"\x06", `"\u0006"`}, 669 {"\x07", `"\u0007"`}, 670 {"\x08", `"\u0008"`}, 671 {"\x09", `"\t"`}, 672 {"\x0a", `"\n"`}, 673 {"\x0b", `"\u000b"`}, 674 {"\x0c", `"\u000c"`}, 675 {"\x0d", `"\r"`}, 676 {"\x0e", `"\u000e"`}, 677 {"\x0f", `"\u000f"`}, 678 {"\x10", `"\u0010"`}, 679 {"\x11", `"\u0011"`}, 680 {"\x12", `"\u0012"`}, 681 {"\x13", `"\u0013"`}, 682 {"\x14", `"\u0014"`}, 683 {"\x15", `"\u0015"`}, 684 {"\x16", `"\u0016"`}, 685 {"\x17", `"\u0017"`}, 686 {"\x18", `"\u0018"`}, 687 {"\x19", `"\u0019"`}, 688 {"\x1a", `"\u001a"`}, 689 {"\x1b", `"\u001b"`}, 690 {"\x1c", `"\u001c"`}, 691 {"\x1d", `"\u001d"`}, 692 {"\x1e", `"\u001e"`}, 693 {"\x1f", `"\u001f"`}, 694 } 695 696 func TestEncodeString(t *testing.T) { 697 for _, tt := range encodeStringTests { 698 b, err := Marshal(tt.in) 699 if err != nil { 700 t.Errorf("Marshal(%q): %v", tt.in, err) 701 continue 702 } 703 out := string(b) 704 if out != tt.out { 705 t.Errorf("Marshal(%q) = %#q, want %#q", tt.in, out, tt.out) 706 } 707 } 708 } 709 710 type jsonbyte byte 711 712 func (b jsonbyte) MarshalJSON() ([]byte, error) { return tenc(`{"JB":%d}`, b) } 713 714 type textbyte byte 715 716 func (b textbyte) MarshalText() ([]byte, error) { return tenc(`TB:%d`, b) } 717 718 type jsonint int 719 720 func (i jsonint) MarshalJSON() ([]byte, error) { return tenc(`{"JI":%d}`, i) } 721 722 type textint int 723 724 func (i textint) MarshalText() ([]byte, error) { return tenc(`TI:%d`, i) } 725 726 func tenc(format string, a ...interface{}) ([]byte, error) { 727 var buf bytes.Buffer 728 fmt.Fprintf(&buf, format, a...) 729 return buf.Bytes(), nil 730 } 731 732 // Issue 13783 733 func TestEncodeBytekind(t *testing.T) { 734 testdata := []struct { 735 data interface{} 736 want string 737 }{ 738 {byte(7), "7"}, 739 {jsonbyte(7), `{"JB":7}`}, 740 {textbyte(4), `"TB:4"`}, 741 {jsonint(5), `{"JI":5}`}, 742 {textint(1), `"TI:1"`}, 743 {[]byte{0, 1}, `"AAE="`}, 744 {[]jsonbyte{0, 1}, `[{"JB":0},{"JB":1}]`}, 745 {[][]jsonbyte{{0, 1}, {3}}, `[[{"JB":0},{"JB":1}],[{"JB":3}]]`}, 746 {[]textbyte{2, 3}, `["TB:2","TB:3"]`}, 747 {[]jsonint{5, 4}, `[{"JI":5},{"JI":4}]`}, 748 {[]textint{9, 3}, `["TI:9","TI:3"]`}, 749 {[]int{9, 3}, `[9,3]`}, 750 } 751 for _, d := range testdata { 752 js, err := Marshal(d.data) 753 if err != nil { 754 t.Error(err) 755 continue 756 } 757 got, want := string(js), d.want 758 if got != want { 759 t.Errorf("got %s, want %s", got, want) 760 } 761 } 762 } 763 764 func TestTextMarshalerMapKeysAreSorted(t *testing.T) { 765 b, err := Marshal(map[unmarshalerText]int{ 766 {"x", "y"}: 1, 767 {"y", "x"}: 2, 768 {"a", "z"}: 3, 769 {"z", "a"}: 4, 770 }) 771 if err != nil { 772 t.Fatalf("Failed to Marshal text.Marshaler: %v", err) 773 } 774 const want = `{"a:z":3,"x:y":1,"y:x":2,"z:a":4}` 775 if string(b) != want { 776 t.Errorf("Marshal map with text.Marshaler keys: got %#q, want %#q", b, want) 777 } 778 } 779 780 var re = regexp.MustCompile 781 782 // syntactic checks on form of marshaled floating point numbers. 783 var badFloatREs = []*regexp.Regexp{ 784 re(`p`), // no binary exponential notation 785 re(`^\+`), // no leading + sign 786 re(`^-?0[^.]`), // no unnecessary leading zeros 787 re(`^-?\.`), // leading zero required before decimal point 788 re(`\.(e|$)`), // no trailing decimal 789 re(`\.[0-9]+0(e|$)`), // no trailing zero in fraction 790 re(`^-?(0|[0-9]{2,})\..*e`), // exponential notation must have normalized mantissa 791 re(`e[0-9]`), // positive exponent must be signed 792 re(`e[+-]0`), // exponent must not have leading zeros 793 re(`e-[1-6]$`), // not tiny enough for exponential notation 794 re(`e+(.|1.|20)$`), // not big enough for exponential notation 795 re(`^-?0\.0000000`), // too tiny, should use exponential notation 796 re(`^-?[0-9]{22}`), // too big, should use exponential notation 797 re(`[1-9][0-9]{16}[1-9]`), // too many significant digits in integer 798 re(`[1-9][0-9.]{17}[1-9]`), // too many significant digits in decimal 799 // below here for float32 only 800 re(`[1-9][0-9]{8}[1-9]`), // too many significant digits in integer 801 re(`[1-9][0-9.]{9}[1-9]`), // too many significant digits in decimal 802 } 803 804 func TestMarshalFloat(t *testing.T) { 805 t.Parallel() 806 nfail := 0 807 test := func(f float64, bits int) { 808 vf := interface{}(f) 809 if bits == 32 { 810 f = float64(float32(f)) // round 811 vf = float32(f) 812 } 813 bout, err := Marshal(vf) 814 if err != nil { 815 t.Errorf("Marshal(%T(%g)): %v", vf, vf, err) 816 nfail++ 817 return 818 } 819 out := string(bout) 820 821 // result must convert back to the same float 822 g, err := strconv.ParseFloat(out, bits) 823 if err != nil { 824 t.Errorf("Marshal(%T(%g)) = %q, cannot parse back: %v", vf, vf, out, err) 825 nfail++ 826 return 827 } 828 if f != g || fmt.Sprint(f) != fmt.Sprint(g) { // fmt.Sprint handles ±0 829 t.Errorf("Marshal(%T(%g)) = %q (is %g, not %g)", vf, vf, out, float32(g), vf) 830 nfail++ 831 return 832 } 833 834 bad := badFloatREs 835 if bits == 64 { 836 bad = bad[:len(bad)-2] 837 } 838 for _, re := range bad { 839 if re.MatchString(out) { 840 t.Errorf("Marshal(%T(%g)) = %q, must not match /%s/", vf, vf, out, re) 841 nfail++ 842 return 843 } 844 } 845 } 846 847 var ( 848 bigger = math.Inf(+1) 849 smaller = math.Inf(-1) 850 ) 851 852 var digits = "1.2345678901234567890123" 853 for i := len(digits); i >= 2; i-- { 854 for exp := -30; exp <= 30; exp++ { 855 for _, sign := range "+-" { 856 for bits := 32; bits <= 64; bits += 32 { 857 s := fmt.Sprintf("%c%se%d", sign, digits[:i], exp) 858 f, err := strconv.ParseFloat(s, bits) 859 if err != nil { 860 log.Fatal(err) 861 } 862 next := math.Nextafter 863 if bits == 32 { 864 next = func(g, h float64) float64 { 865 return float64(math.Nextafter32(float32(g), float32(h))) 866 } 867 } 868 test(f, bits) 869 test(next(f, bigger), bits) 870 test(next(f, smaller), bits) 871 if nfail > 50 { 872 t.Fatalf("stopping test early") 873 } 874 } 875 } 876 } 877 } 878 test(0, 64) 879 test(math.Copysign(0, -1), 64) 880 test(0, 32) 881 test(math.Copysign(0, -1), 32) 882 } 883 884 func TestMarshalRawMessageValue(t *testing.T) { 885 type ( 886 T1 struct { 887 M RawMessage `json:",omitempty"` 888 } 889 T2 struct { 890 M *RawMessage `json:",omitempty"` 891 } 892 ) 893 894 var ( 895 rawNil = RawMessage(nil) 896 rawEmpty = RawMessage([]byte{}) 897 rawText = RawMessage([]byte(`"foo"`)) 898 ) 899 900 tests := []struct { 901 in interface{} 902 want string 903 ok bool 904 }{ 905 // Test with nil RawMessage. 906 {rawNil, "null", true}, 907 {&rawNil, "null", true}, 908 {[]interface{}{rawNil}, "[null]", true}, 909 {&[]interface{}{rawNil}, "[null]", true}, 910 {[]interface{}{&rawNil}, "[null]", true}, 911 {&[]interface{}{&rawNil}, "[null]", true}, 912 {struct{ M RawMessage }{rawNil}, `{"M":null}`, true}, 913 {&struct{ M RawMessage }{rawNil}, `{"M":null}`, true}, 914 {struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true}, 915 {&struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true}, 916 {map[string]interface{}{"M": rawNil}, `{"M":null}`, true}, 917 {&map[string]interface{}{"M": rawNil}, `{"M":null}`, true}, 918 {map[string]interface{}{"M": &rawNil}, `{"M":null}`, true}, 919 {&map[string]interface{}{"M": &rawNil}, `{"M":null}`, true}, 920 {T1{rawNil}, "{}", true}, 921 {T2{&rawNil}, `{"M":null}`, true}, 922 {&T1{rawNil}, "{}", true}, 923 {&T2{&rawNil}, `{"M":null}`, true}, 924 925 // Test with empty, but non-nil, RawMessage. 926 {rawEmpty, "", false}, 927 {&rawEmpty, "", false}, 928 {[]interface{}{rawEmpty}, "", false}, 929 {&[]interface{}{rawEmpty}, "", false}, 930 {[]interface{}{&rawEmpty}, "", false}, 931 {&[]interface{}{&rawEmpty}, "", false}, 932 {struct{ X RawMessage }{rawEmpty}, "", false}, 933 {&struct{ X RawMessage }{rawEmpty}, "", false}, 934 {struct{ X *RawMessage }{&rawEmpty}, "", false}, 935 {&struct{ X *RawMessage }{&rawEmpty}, "", false}, 936 {map[string]interface{}{"nil": rawEmpty}, "", false}, 937 {&map[string]interface{}{"nil": rawEmpty}, "", false}, 938 {map[string]interface{}{"nil": &rawEmpty}, "", false}, 939 {&map[string]interface{}{"nil": &rawEmpty}, "", false}, 940 {T1{rawEmpty}, "{}", true}, 941 {T2{&rawEmpty}, "", false}, 942 {&T1{rawEmpty}, "{}", true}, 943 {&T2{&rawEmpty}, "", false}, 944 945 // Test with RawMessage with some text. 946 // 947 // The tests below marked with Issue6458 used to generate "ImZvbyI=" instead "foo". 948 // This behavior was intentionally changed in Go 1.8. 949 // See https://golang.org/issues/14493#issuecomment-255857318 950 {rawText, `"foo"`, true}, // Issue6458 951 {&rawText, `"foo"`, true}, 952 {[]interface{}{rawText}, `["foo"]`, true}, // Issue6458 953 {&[]interface{}{rawText}, `["foo"]`, true}, // Issue6458 954 {[]interface{}{&rawText}, `["foo"]`, true}, 955 {&[]interface{}{&rawText}, `["foo"]`, true}, 956 {struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true}, // Issue6458 957 {&struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true}, 958 {struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true}, 959 {&struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true}, 960 {map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 961 {&map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 962 {map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true}, 963 {&map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true}, 964 {T1{rawText}, `{"M":"foo"}`, true}, // Issue6458 965 {T2{&rawText}, `{"M":"foo"}`, true}, 966 {&T1{rawText}, `{"M":"foo"}`, true}, 967 {&T2{&rawText}, `{"M":"foo"}`, true}, 968 } 969 970 for i, tt := range tests { 971 b, err := Marshal(tt.in) 972 if ok := (err == nil); ok != tt.ok { 973 if err != nil { 974 t.Errorf("test %d, unexpected failure: %v", i, err) 975 } else { 976 t.Errorf("test %d, unexpected success", i) 977 } 978 } 979 if got := string(b); got != tt.want { 980 t.Errorf("test %d, Marshal(%#v) = %q, want %q", i, tt.in, got, tt.want) 981 } 982 } 983 }