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