github.com/rakyll/go@v0.0.0-20170216000551-64c02460d703/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  type IntType int
   257  
   258  type MyStruct struct {
   259  	IntType
   260  }
   261  
   262  func TestAnonymousNonstruct(t *testing.T) {
   263  	var i IntType = 11
   264  	a := MyStruct{i}
   265  	const want = `{"IntType":11}`
   266  
   267  	b, err := Marshal(a)
   268  	if err != nil {
   269  		t.Fatalf("Marshal: %v", err)
   270  	}
   271  	if got := string(b); got != want {
   272  		t.Errorf("got %q, want %q", got, want)
   273  	}
   274  }
   275  
   276  type BugA struct {
   277  	S string
   278  }
   279  
   280  type BugB struct {
   281  	BugA
   282  	S string
   283  }
   284  
   285  type BugC struct {
   286  	S string
   287  }
   288  
   289  // Legal Go: We never use the repeated embedded field (S).
   290  type BugX struct {
   291  	A int
   292  	BugA
   293  	BugB
   294  }
   295  
   296  // Issue 16042. Even if a nil interface value is passed in
   297  // as long as it implements MarshalJSON, it should be marshaled.
   298  type nilMarshaler string
   299  
   300  func (nm *nilMarshaler) MarshalJSON() ([]byte, error) {
   301  	if nm == nil {
   302  		return Marshal("0zenil0")
   303  	}
   304  	return Marshal("zenil:" + string(*nm))
   305  }
   306  
   307  // Issue 16042.
   308  func TestNilMarshal(t *testing.T) {
   309  	testCases := []struct {
   310  		v    interface{}
   311  		want string
   312  	}{
   313  		{v: nil, want: `null`},
   314  		{v: new(float64), want: `0`},
   315  		{v: []interface{}(nil), want: `null`},
   316  		{v: []string(nil), want: `null`},
   317  		{v: map[string]string(nil), want: `null`},
   318  		{v: []byte(nil), want: `null`},
   319  		{v: struct{ M string }{"gopher"}, want: `{"M":"gopher"}`},
   320  		{v: struct{ M Marshaler }{}, want: `{"M":null}`},
   321  		{v: struct{ M Marshaler }{(*nilMarshaler)(nil)}, want: `{"M":"0zenil0"}`},
   322  		{v: struct{ M interface{} }{(*nilMarshaler)(nil)}, want: `{"M":null}`},
   323  	}
   324  
   325  	for _, tt := range testCases {
   326  		out, err := Marshal(tt.v)
   327  		if err != nil || string(out) != tt.want {
   328  			t.Errorf("Marshal(%#v) = %#q, %#v, want %#q, nil", tt.v, out, err, tt.want)
   329  			continue
   330  		}
   331  	}
   332  }
   333  
   334  // Issue 5245.
   335  func TestEmbeddedBug(t *testing.T) {
   336  	v := BugB{
   337  		BugA{"A"},
   338  		"B",
   339  	}
   340  	b, err := Marshal(v)
   341  	if err != nil {
   342  		t.Fatal("Marshal:", err)
   343  	}
   344  	want := `{"S":"B"}`
   345  	got := string(b)
   346  	if got != want {
   347  		t.Fatalf("Marshal: got %s want %s", got, want)
   348  	}
   349  	// Now check that the duplicate field, S, does not appear.
   350  	x := BugX{
   351  		A: 23,
   352  	}
   353  	b, err = Marshal(x)
   354  	if err != nil {
   355  		t.Fatal("Marshal:", err)
   356  	}
   357  	want = `{"A":23}`
   358  	got = string(b)
   359  	if got != want {
   360  		t.Fatalf("Marshal: got %s want %s", got, want)
   361  	}
   362  }
   363  
   364  type BugD struct { // Same as BugA after tagging.
   365  	XXX string `json:"S"`
   366  }
   367  
   368  // BugD's tagged S field should dominate BugA's.
   369  type BugY struct {
   370  	BugA
   371  	BugD
   372  }
   373  
   374  // Test that a field with a tag dominates untagged fields.
   375  func TestTaggedFieldDominates(t *testing.T) {
   376  	v := BugY{
   377  		BugA{"BugA"},
   378  		BugD{"BugD"},
   379  	}
   380  	b, err := Marshal(v)
   381  	if err != nil {
   382  		t.Fatal("Marshal:", err)
   383  	}
   384  	want := `{"S":"BugD"}`
   385  	got := string(b)
   386  	if got != want {
   387  		t.Fatalf("Marshal: got %s want %s", got, want)
   388  	}
   389  }
   390  
   391  // There are no tags here, so S should not appear.
   392  type BugZ struct {
   393  	BugA
   394  	BugC
   395  	BugY // Contains a tagged S field through BugD; should not dominate.
   396  }
   397  
   398  func TestDuplicatedFieldDisappears(t *testing.T) {
   399  	v := BugZ{
   400  		BugA{"BugA"},
   401  		BugC{"BugC"},
   402  		BugY{
   403  			BugA{"nested BugA"},
   404  			BugD{"nested BugD"},
   405  		},
   406  	}
   407  	b, err := Marshal(v)
   408  	if err != nil {
   409  		t.Fatal("Marshal:", err)
   410  	}
   411  	want := `{}`
   412  	got := string(b)
   413  	if got != want {
   414  		t.Fatalf("Marshal: got %s want %s", got, want)
   415  	}
   416  }
   417  
   418  func TestStringBytes(t *testing.T) {
   419  	t.Parallel()
   420  	// Test that encodeState.stringBytes and encodeState.string use the same encoding.
   421  	var r []rune
   422  	for i := '\u0000'; i <= unicode.MaxRune; i++ {
   423  		r = append(r, i)
   424  	}
   425  	s := string(r) + "\xff\xff\xffhello" // some invalid UTF-8 too
   426  
   427  	for _, escapeHTML := range []bool{true, false} {
   428  		es := &encodeState{}
   429  		es.string(s, escapeHTML)
   430  
   431  		esBytes := &encodeState{}
   432  		esBytes.stringBytes([]byte(s), escapeHTML)
   433  
   434  		enc := es.Buffer.String()
   435  		encBytes := esBytes.Buffer.String()
   436  		if enc != encBytes {
   437  			i := 0
   438  			for i < len(enc) && i < len(encBytes) && enc[i] == encBytes[i] {
   439  				i++
   440  			}
   441  			enc = enc[i:]
   442  			encBytes = encBytes[i:]
   443  			i = 0
   444  			for i < len(enc) && i < len(encBytes) && enc[len(enc)-i-1] == encBytes[len(encBytes)-i-1] {
   445  				i++
   446  			}
   447  			enc = enc[:len(enc)-i]
   448  			encBytes = encBytes[:len(encBytes)-i]
   449  
   450  			if len(enc) > 20 {
   451  				enc = enc[:20] + "..."
   452  			}
   453  			if len(encBytes) > 20 {
   454  				encBytes = encBytes[:20] + "..."
   455  			}
   456  
   457  			t.Errorf("with escapeHTML=%t, encodings differ at %#q vs %#q",
   458  				escapeHTML, enc, encBytes)
   459  		}
   460  	}
   461  }
   462  
   463  func TestIssue10281(t *testing.T) {
   464  	type Foo struct {
   465  		N Number
   466  	}
   467  	x := Foo{Number(`invalid`)}
   468  
   469  	b, err := Marshal(&x)
   470  	if err == nil {
   471  		t.Errorf("Marshal(&x) = %#q; want error", b)
   472  	}
   473  }
   474  
   475  func TestHTMLEscape(t *testing.T) {
   476  	var b, want bytes.Buffer
   477  	m := `{"M":"<html>foo &` + "\xe2\x80\xa8 \xe2\x80\xa9" + `</html>"}`
   478  	want.Write([]byte(`{"M":"\u003chtml\u003efoo \u0026\u2028 \u2029\u003c/html\u003e"}`))
   479  	HTMLEscape(&b, []byte(m))
   480  	if !bytes.Equal(b.Bytes(), want.Bytes()) {
   481  		t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes())
   482  	}
   483  }
   484  
   485  // golang.org/issue/8582
   486  func TestEncodePointerString(t *testing.T) {
   487  	type stringPointer struct {
   488  		N *int64 `json:"n,string"`
   489  	}
   490  	var n int64 = 42
   491  	b, err := Marshal(stringPointer{N: &n})
   492  	if err != nil {
   493  		t.Fatalf("Marshal: %v", err)
   494  	}
   495  	if got, want := string(b), `{"n":"42"}`; got != want {
   496  		t.Errorf("Marshal = %s, want %s", got, want)
   497  	}
   498  	var back stringPointer
   499  	err = Unmarshal(b, &back)
   500  	if err != nil {
   501  		t.Fatalf("Unmarshal: %v", err)
   502  	}
   503  	if back.N == nil {
   504  		t.Fatalf("Unmarshaled nil N field")
   505  	}
   506  	if *back.N != 42 {
   507  		t.Fatalf("*N = %d; want 42", *back.N)
   508  	}
   509  }
   510  
   511  var encodeStringTests = []struct {
   512  	in  string
   513  	out string
   514  }{
   515  	{"\x00", `"\u0000"`},
   516  	{"\x01", `"\u0001"`},
   517  	{"\x02", `"\u0002"`},
   518  	{"\x03", `"\u0003"`},
   519  	{"\x04", `"\u0004"`},
   520  	{"\x05", `"\u0005"`},
   521  	{"\x06", `"\u0006"`},
   522  	{"\x07", `"\u0007"`},
   523  	{"\x08", `"\u0008"`},
   524  	{"\x09", `"\t"`},
   525  	{"\x0a", `"\n"`},
   526  	{"\x0b", `"\u000b"`},
   527  	{"\x0c", `"\u000c"`},
   528  	{"\x0d", `"\r"`},
   529  	{"\x0e", `"\u000e"`},
   530  	{"\x0f", `"\u000f"`},
   531  	{"\x10", `"\u0010"`},
   532  	{"\x11", `"\u0011"`},
   533  	{"\x12", `"\u0012"`},
   534  	{"\x13", `"\u0013"`},
   535  	{"\x14", `"\u0014"`},
   536  	{"\x15", `"\u0015"`},
   537  	{"\x16", `"\u0016"`},
   538  	{"\x17", `"\u0017"`},
   539  	{"\x18", `"\u0018"`},
   540  	{"\x19", `"\u0019"`},
   541  	{"\x1a", `"\u001a"`},
   542  	{"\x1b", `"\u001b"`},
   543  	{"\x1c", `"\u001c"`},
   544  	{"\x1d", `"\u001d"`},
   545  	{"\x1e", `"\u001e"`},
   546  	{"\x1f", `"\u001f"`},
   547  }
   548  
   549  func TestEncodeString(t *testing.T) {
   550  	for _, tt := range encodeStringTests {
   551  		b, err := Marshal(tt.in)
   552  		if err != nil {
   553  			t.Errorf("Marshal(%q): %v", tt.in, err)
   554  			continue
   555  		}
   556  		out := string(b)
   557  		if out != tt.out {
   558  			t.Errorf("Marshal(%q) = %#q, want %#q", tt.in, out, tt.out)
   559  		}
   560  	}
   561  }
   562  
   563  type jsonbyte byte
   564  
   565  func (b jsonbyte) MarshalJSON() ([]byte, error) { return tenc(`{"JB":%d}`, b) }
   566  
   567  type textbyte byte
   568  
   569  func (b textbyte) MarshalText() ([]byte, error) { return tenc(`TB:%d`, b) }
   570  
   571  type jsonint int
   572  
   573  func (i jsonint) MarshalJSON() ([]byte, error) { return tenc(`{"JI":%d}`, i) }
   574  
   575  type textint int
   576  
   577  func (i textint) MarshalText() ([]byte, error) { return tenc(`TI:%d`, i) }
   578  
   579  func tenc(format string, a ...interface{}) ([]byte, error) {
   580  	var buf bytes.Buffer
   581  	fmt.Fprintf(&buf, format, a...)
   582  	return buf.Bytes(), nil
   583  }
   584  
   585  // Issue 13783
   586  func TestEncodeBytekind(t *testing.T) {
   587  	testdata := []struct {
   588  		data interface{}
   589  		want string
   590  	}{
   591  		{byte(7), "7"},
   592  		{jsonbyte(7), `{"JB":7}`},
   593  		{textbyte(4), `"TB:4"`},
   594  		{jsonint(5), `{"JI":5}`},
   595  		{textint(1), `"TI:1"`},
   596  		{[]byte{0, 1}, `"AAE="`},
   597  		{[]jsonbyte{0, 1}, `[{"JB":0},{"JB":1}]`},
   598  		{[][]jsonbyte{{0, 1}, {3}}, `[[{"JB":0},{"JB":1}],[{"JB":3}]]`},
   599  		{[]textbyte{2, 3}, `["TB:2","TB:3"]`},
   600  		{[]jsonint{5, 4}, `[{"JI":5},{"JI":4}]`},
   601  		{[]textint{9, 3}, `["TI:9","TI:3"]`},
   602  		{[]int{9, 3}, `[9,3]`},
   603  	}
   604  	for _, d := range testdata {
   605  		js, err := Marshal(d.data)
   606  		if err != nil {
   607  			t.Error(err)
   608  			continue
   609  		}
   610  		got, want := string(js), d.want
   611  		if got != want {
   612  			t.Errorf("got %s, want %s", got, want)
   613  		}
   614  	}
   615  }
   616  
   617  func TestTextMarshalerMapKeysAreSorted(t *testing.T) {
   618  	b, err := Marshal(map[unmarshalerText]int{
   619  		{"x", "y"}: 1,
   620  		{"y", "x"}: 2,
   621  		{"a", "z"}: 3,
   622  		{"z", "a"}: 4,
   623  	})
   624  	if err != nil {
   625  		t.Fatalf("Failed to Marshal text.Marshaler: %v", err)
   626  	}
   627  	const want = `{"a:z":3,"x:y":1,"y:x":2,"z:a":4}`
   628  	if string(b) != want {
   629  		t.Errorf("Marshal map with text.Marshaler keys: got %#q, want %#q", b, want)
   630  	}
   631  }
   632  
   633  var re = regexp.MustCompile
   634  
   635  // syntactic checks on form of marshaled floating point numbers.
   636  var badFloatREs = []*regexp.Regexp{
   637  	re(`p`),                     // no binary exponential notation
   638  	re(`^\+`),                   // no leading + sign
   639  	re(`^-?0[^.]`),              // no unnecessary leading zeros
   640  	re(`^-?\.`),                 // leading zero required before decimal point
   641  	re(`\.(e|$)`),               // no trailing decimal
   642  	re(`\.[0-9]+0(e|$)`),        // no trailing zero in fraction
   643  	re(`^-?(0|[0-9]{2,})\..*e`), // exponential notation must have normalized mantissa
   644  	re(`e[0-9]`),                // positive exponent must be signed
   645  	re(`e[+-]0`),                // exponent must not have leading zeros
   646  	re(`e-[1-6]$`),              // not tiny enough for exponential notation
   647  	re(`e+(.|1.|20)$`),          // not big enough for exponential notation
   648  	re(`^-?0\.0000000`),         // too tiny, should use exponential notation
   649  	re(`^-?[0-9]{22}`),          // too big, should use exponential notation
   650  	re(`[1-9][0-9]{16}[1-9]`),   // too many significant digits in integer
   651  	re(`[1-9][0-9.]{17}[1-9]`),  // too many significant digits in decimal
   652  	// below here for float32 only
   653  	re(`[1-9][0-9]{8}[1-9]`),  // too many significant digits in integer
   654  	re(`[1-9][0-9.]{9}[1-9]`), // too many significant digits in decimal
   655  }
   656  
   657  func TestMarshalFloat(t *testing.T) {
   658  	t.Parallel()
   659  	nfail := 0
   660  	test := func(f float64, bits int) {
   661  		vf := interface{}(f)
   662  		if bits == 32 {
   663  			f = float64(float32(f)) // round
   664  			vf = float32(f)
   665  		}
   666  		bout, err := Marshal(vf)
   667  		if err != nil {
   668  			t.Errorf("Marshal(%T(%g)): %v", vf, vf, err)
   669  			nfail++
   670  			return
   671  		}
   672  		out := string(bout)
   673  
   674  		// result must convert back to the same float
   675  		g, err := strconv.ParseFloat(out, bits)
   676  		if err != nil {
   677  			t.Errorf("Marshal(%T(%g)) = %q, cannot parse back: %v", vf, vf, out, err)
   678  			nfail++
   679  			return
   680  		}
   681  		if f != g || fmt.Sprint(f) != fmt.Sprint(g) { // fmt.Sprint handles ±0
   682  			t.Errorf("Marshal(%T(%g)) = %q (is %g, not %g)", vf, vf, out, float32(g), vf)
   683  			nfail++
   684  			return
   685  		}
   686  
   687  		bad := badFloatREs
   688  		if bits == 64 {
   689  			bad = bad[:len(bad)-2]
   690  		}
   691  		for _, re := range bad {
   692  			if re.MatchString(out) {
   693  				t.Errorf("Marshal(%T(%g)) = %q, must not match /%s/", vf, vf, out, re)
   694  				nfail++
   695  				return
   696  			}
   697  		}
   698  	}
   699  
   700  	var (
   701  		bigger  = math.Inf(+1)
   702  		smaller = math.Inf(-1)
   703  	)
   704  
   705  	var digits = "1.2345678901234567890123"
   706  	for i := len(digits); i >= 2; i-- {
   707  		for exp := -30; exp <= 30; exp++ {
   708  			for _, sign := range "+-" {
   709  				for bits := 32; bits <= 64; bits += 32 {
   710  					s := fmt.Sprintf("%c%se%d", sign, digits[:i], exp)
   711  					f, err := strconv.ParseFloat(s, bits)
   712  					if err != nil {
   713  						log.Fatal(err)
   714  					}
   715  					next := math.Nextafter
   716  					if bits == 32 {
   717  						next = func(g, h float64) float64 {
   718  							return float64(math.Nextafter32(float32(g), float32(h)))
   719  						}
   720  					}
   721  					test(f, bits)
   722  					test(next(f, bigger), bits)
   723  					test(next(f, smaller), bits)
   724  					if nfail > 50 {
   725  						t.Fatalf("stopping test early")
   726  					}
   727  				}
   728  			}
   729  		}
   730  	}
   731  	test(0, 64)
   732  	test(math.Copysign(0, -1), 64)
   733  	test(0, 32)
   734  	test(math.Copysign(0, -1), 32)
   735  }
   736  
   737  func TestMarshalRawMessageValue(t *testing.T) {
   738  	type (
   739  		T1 struct {
   740  			M RawMessage `json:",omitempty"`
   741  		}
   742  		T2 struct {
   743  			M *RawMessage `json:",omitempty"`
   744  		}
   745  	)
   746  
   747  	var (
   748  		rawNil   = RawMessage(nil)
   749  		rawEmpty = RawMessage([]byte{})
   750  		rawText  = RawMessage([]byte(`"foo"`))
   751  	)
   752  
   753  	tests := []struct {
   754  		in   interface{}
   755  		want string
   756  		ok   bool
   757  	}{
   758  		// Test with nil RawMessage.
   759  		{rawNil, "null", true},
   760  		{&rawNil, "null", true},
   761  		{[]interface{}{rawNil}, "[null]", true},
   762  		{&[]interface{}{rawNil}, "[null]", true},
   763  		{[]interface{}{&rawNil}, "[null]", true},
   764  		{&[]interface{}{&rawNil}, "[null]", true},
   765  		{struct{ M RawMessage }{rawNil}, `{"M":null}`, true},
   766  		{&struct{ M RawMessage }{rawNil}, `{"M":null}`, true},
   767  		{struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true},
   768  		{&struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true},
   769  		{map[string]interface{}{"M": rawNil}, `{"M":null}`, true},
   770  		{&map[string]interface{}{"M": rawNil}, `{"M":null}`, true},
   771  		{map[string]interface{}{"M": &rawNil}, `{"M":null}`, true},
   772  		{&map[string]interface{}{"M": &rawNil}, `{"M":null}`, true},
   773  		{T1{rawNil}, "{}", true},
   774  		{T2{&rawNil}, `{"M":null}`, true},
   775  		{&T1{rawNil}, "{}", true},
   776  		{&T2{&rawNil}, `{"M":null}`, true},
   777  
   778  		// Test with empty, but non-nil, RawMessage.
   779  		{rawEmpty, "", false},
   780  		{&rawEmpty, "", false},
   781  		{[]interface{}{rawEmpty}, "", false},
   782  		{&[]interface{}{rawEmpty}, "", false},
   783  		{[]interface{}{&rawEmpty}, "", false},
   784  		{&[]interface{}{&rawEmpty}, "", false},
   785  		{struct{ X RawMessage }{rawEmpty}, "", false},
   786  		{&struct{ X RawMessage }{rawEmpty}, "", false},
   787  		{struct{ X *RawMessage }{&rawEmpty}, "", false},
   788  		{&struct{ X *RawMessage }{&rawEmpty}, "", false},
   789  		{map[string]interface{}{"nil": rawEmpty}, "", false},
   790  		{&map[string]interface{}{"nil": rawEmpty}, "", false},
   791  		{map[string]interface{}{"nil": &rawEmpty}, "", false},
   792  		{&map[string]interface{}{"nil": &rawEmpty}, "", false},
   793  		{T1{rawEmpty}, "{}", true},
   794  		{T2{&rawEmpty}, "", false},
   795  		{&T1{rawEmpty}, "{}", true},
   796  		{&T2{&rawEmpty}, "", false},
   797  
   798  		// Test with RawMessage with some text.
   799  		//
   800  		// The tests below marked with Issue6458 used to generate "ImZvbyI=" instead "foo".
   801  		// This behavior was intentionally changed in Go 1.8.
   802  		// See https://github.com/golang/go/issues/14493#issuecomment-255857318
   803  		{rawText, `"foo"`, true}, // Issue6458
   804  		{&rawText, `"foo"`, true},
   805  		{[]interface{}{rawText}, `["foo"]`, true},  // Issue6458
   806  		{&[]interface{}{rawText}, `["foo"]`, true}, // Issue6458
   807  		{[]interface{}{&rawText}, `["foo"]`, true},
   808  		{&[]interface{}{&rawText}, `["foo"]`, true},
   809  		{struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true}, // Issue6458
   810  		{&struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true},
   811  		{struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true},
   812  		{&struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true},
   813  		{map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true},  // Issue6458
   814  		{&map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458
   815  		{map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true},
   816  		{&map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true},
   817  		{T1{rawText}, `{"M":"foo"}`, true}, // Issue6458
   818  		{T2{&rawText}, `{"M":"foo"}`, true},
   819  		{&T1{rawText}, `{"M":"foo"}`, true},
   820  		{&T2{&rawText}, `{"M":"foo"}`, true},
   821  	}
   822  
   823  	for i, tt := range tests {
   824  		b, err := Marshal(tt.in)
   825  		if ok := (err == nil); ok != tt.ok {
   826  			if err != nil {
   827  				t.Errorf("test %d, unexpected failure: %v", i, err)
   828  			} else {
   829  				t.Errorf("test %d, unexpected success", i)
   830  			}
   831  		}
   832  		if got := string(b); got != tt.want {
   833  			t.Errorf("test %d, Marshal(%#v) = %q, want %q", i, tt.in, got, tt.want)
   834  		}
   835  	}
   836  }