...
Run Format

Source file src/encoding/json/encode_test.go

Documentation: encoding/json

     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  		// 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  		r = append(r, i)
   584  	}
   585  	s := string(r) + "\xff\xff\xffhello" // some invalid UTF-8 too
   586  
   587  	for _, escapeHTML := range []bool{true, false} {
   588  		es := &encodeState{}
   589  		es.string(s, escapeHTML)
   590  
   591  		esBytes := &encodeState{}
   592  		esBytes.stringBytes([]byte(s), escapeHTML)
   593  
   594  		enc := es.Buffer.String()
   595  		encBytes := esBytes.Buffer.String()
   596  		if enc != encBytes {
   597  			i := 0
   598  			for i < len(enc) && i < len(encBytes) && enc[i] == encBytes[i] {
   599  				i++
   600  			}
   601  			enc = enc[i:]
   602  			encBytes = encBytes[i:]
   603  			i = 0
   604  			for i < len(enc) && i < len(encBytes) && enc[len(enc)-i-1] == encBytes[len(encBytes)-i-1] {
   605  				i++
   606  			}
   607  			enc = enc[:len(enc)-i]
   608  			encBytes = encBytes[:len(encBytes)-i]
   609  
   610  			if len(enc) > 20 {
   611  				enc = enc[:20] + "..."
   612  			}
   613  			if len(encBytes) > 20 {
   614  				encBytes = encBytes[:20] + "..."
   615  			}
   616  
   617  			t.Errorf("with escapeHTML=%t, encodings differ at %#q vs %#q",
   618  				escapeHTML, enc, encBytes)
   619  		}
   620  	}
   621  }
   622  
   623  func TestIssue10281(t *testing.T) {
   624  	type Foo struct {
   625  		N Number
   626  	}
   627  	x := Foo{Number(`invalid`)}
   628  
   629  	b, err := Marshal(&x)
   630  	if err == nil {
   631  		t.Errorf("Marshal(&x) = %#q; want error", b)
   632  	}
   633  }
   634  
   635  func TestHTMLEscape(t *testing.T) {
   636  	var b, want bytes.Buffer
   637  	m := `{"M":"<html>foo &` + "\xe2\x80\xa8 \xe2\x80\xa9" + `</html>"}`
   638  	want.Write([]byte(`{"M":"\u003chtml\u003efoo \u0026\u2028 \u2029\u003c/html\u003e"}`))
   639  	HTMLEscape(&b, []byte(m))
   640  	if !bytes.Equal(b.Bytes(), want.Bytes()) {
   641  		t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes())
   642  	}
   643  }
   644  
   645  // golang.org/issue/8582
   646  func TestEncodePointerString(t *testing.T) {
   647  	type stringPointer struct {
   648  		N *int64 `json:"n,string"`
   649  	}
   650  	var n int64 = 42
   651  	b, err := Marshal(stringPointer{N: &n})
   652  	if err != nil {
   653  		t.Fatalf("Marshal: %v", err)
   654  	}
   655  	if got, want := string(b), `{"n":"42"}`; got != want {
   656  		t.Errorf("Marshal = %s, want %s", got, want)
   657  	}
   658  	var back stringPointer
   659  	err = Unmarshal(b, &back)
   660  	if err != nil {
   661  		t.Fatalf("Unmarshal: %v", err)
   662  	}
   663  	if back.N == nil {
   664  		t.Fatalf("Unmarshaled nil N field")
   665  	}
   666  	if *back.N != 42 {
   667  		t.Fatalf("*N = %d; want 42", *back.N)
   668  	}
   669  }
   670  
   671  var encodeStringTests = []struct {
   672  	in  string
   673  	out string
   674  }{
   675  	{"\x00", `"\u0000"`},
   676  	{"\x01", `"\u0001"`},
   677  	{"\x02", `"\u0002"`},
   678  	{"\x03", `"\u0003"`},
   679  	{"\x04", `"\u0004"`},
   680  	{"\x05", `"\u0005"`},
   681  	{"\x06", `"\u0006"`},
   682  	{"\x07", `"\u0007"`},
   683  	{"\x08", `"\u0008"`},
   684  	{"\x09", `"\t"`},
   685  	{"\x0a", `"\n"`},
   686  	{"\x0b", `"\u000b"`},
   687  	{"\x0c", `"\u000c"`},
   688  	{"\x0d", `"\r"`},
   689  	{"\x0e", `"\u000e"`},
   690  	{"\x0f", `"\u000f"`},
   691  	{"\x10", `"\u0010"`},
   692  	{"\x11", `"\u0011"`},
   693  	{"\x12", `"\u0012"`},
   694  	{"\x13", `"\u0013"`},
   695  	{"\x14", `"\u0014"`},
   696  	{"\x15", `"\u0015"`},
   697  	{"\x16", `"\u0016"`},
   698  	{"\x17", `"\u0017"`},
   699  	{"\x18", `"\u0018"`},
   700  	{"\x19", `"\u0019"`},
   701  	{"\x1a", `"\u001a"`},
   702  	{"\x1b", `"\u001b"`},
   703  	{"\x1c", `"\u001c"`},
   704  	{"\x1d", `"\u001d"`},
   705  	{"\x1e", `"\u001e"`},
   706  	{"\x1f", `"\u001f"`},
   707  }
   708  
   709  func TestEncodeString(t *testing.T) {
   710  	for _, tt := range encodeStringTests {
   711  		b, err := Marshal(tt.in)
   712  		if err != nil {
   713  			t.Errorf("Marshal(%q): %v", tt.in, err)
   714  			continue
   715  		}
   716  		out := string(b)
   717  		if out != tt.out {
   718  			t.Errorf("Marshal(%q) = %#q, want %#q", tt.in, out, tt.out)
   719  		}
   720  	}
   721  }
   722  
   723  type jsonbyte byte
   724  
   725  func (b jsonbyte) MarshalJSON() ([]byte, error) { return tenc(`{"JB":%d}`, b) }
   726  
   727  type textbyte byte
   728  
   729  func (b textbyte) MarshalText() ([]byte, error) { return tenc(`TB:%d`, b) }
   730  
   731  type jsonint int
   732  
   733  func (i jsonint) MarshalJSON() ([]byte, error) { return tenc(`{"JI":%d}`, i) }
   734  
   735  type textint int
   736  
   737  func (i textint) MarshalText() ([]byte, error) { return tenc(`TI:%d`, i) }
   738  
   739  func tenc(format string, a ...interface{}) ([]byte, error) {
   740  	var buf bytes.Buffer
   741  	fmt.Fprintf(&buf, format, a...)
   742  	return buf.Bytes(), nil
   743  }
   744  
   745  // Issue 13783
   746  func TestEncodeBytekind(t *testing.T) {
   747  	testdata := []struct {
   748  		data interface{}
   749  		want string
   750  	}{
   751  		{byte(7), "7"},
   752  		{jsonbyte(7), `{"JB":7}`},
   753  		{textbyte(4), `"TB:4"`},
   754  		{jsonint(5), `{"JI":5}`},
   755  		{textint(1), `"TI:1"`},
   756  		{[]byte{0, 1}, `"AAE="`},
   757  		{[]jsonbyte{0, 1}, `[{"JB":0},{"JB":1}]`},
   758  		{[][]jsonbyte{{0, 1}, {3}}, `[[{"JB":0},{"JB":1}],[{"JB":3}]]`},
   759  		{[]textbyte{2, 3}, `["TB:2","TB:3"]`},
   760  		{[]jsonint{5, 4}, `[{"JI":5},{"JI":4}]`},
   761  		{[]textint{9, 3}, `["TI:9","TI:3"]`},
   762  		{[]int{9, 3}, `[9,3]`},
   763  	}
   764  	for _, d := range testdata {
   765  		js, err := Marshal(d.data)
   766  		if err != nil {
   767  			t.Error(err)
   768  			continue
   769  		}
   770  		got, want := string(js), d.want
   771  		if got != want {
   772  			t.Errorf("got %s, want %s", got, want)
   773  		}
   774  	}
   775  }
   776  
   777  func TestTextMarshalerMapKeysAreSorted(t *testing.T) {
   778  	b, err := Marshal(map[unmarshalerText]int{
   779  		{"x", "y"}: 1,
   780  		{"y", "x"}: 2,
   781  		{"a", "z"}: 3,
   782  		{"z", "a"}: 4,
   783  	})
   784  	if err != nil {
   785  		t.Fatalf("Failed to Marshal text.Marshaler: %v", err)
   786  	}
   787  	const want = `{"a:z":3,"x:y":1,"y:x":2,"z:a":4}`
   788  	if string(b) != want {
   789  		t.Errorf("Marshal map with text.Marshaler keys: got %#q, want %#q", b, want)
   790  	}
   791  }
   792  
   793  var re = regexp.MustCompile
   794  
   795  // syntactic checks on form of marshaled floating point numbers.
   796  var badFloatREs = []*regexp.Regexp{
   797  	re(`p`),                     // no binary exponential notation
   798  	re(`^\+`),                   // no leading + sign
   799  	re(`^-?0[^.]`),              // no unnecessary leading zeros
   800  	re(`^-?\.`),                 // leading zero required before decimal point
   801  	re(`\.(e|$)`),               // no trailing decimal
   802  	re(`\.[0-9]+0(e|$)`),        // no trailing zero in fraction
   803  	re(`^-?(0|[0-9]{2,})\..*e`), // exponential notation must have normalized mantissa
   804  	re(`e[0-9]`),                // positive exponent must be signed
   805  	re(`e[+-]0`),                // exponent must not have leading zeros
   806  	re(`e-[1-6]$`),              // not tiny enough for exponential notation
   807  	re(`e+(.|1.|20)$`),          // not big enough for exponential notation
   808  	re(`^-?0\.0000000`),         // too tiny, should use exponential notation
   809  	re(`^-?[0-9]{22}`),          // too big, should use exponential notation
   810  	re(`[1-9][0-9]{16}[1-9]`),   // too many significant digits in integer
   811  	re(`[1-9][0-9.]{17}[1-9]`),  // too many significant digits in decimal
   812  	// below here for float32 only
   813  	re(`[1-9][0-9]{8}[1-9]`),  // too many significant digits in integer
   814  	re(`[1-9][0-9.]{9}[1-9]`), // too many significant digits in decimal
   815  }
   816  
   817  func TestMarshalFloat(t *testing.T) {
   818  	t.Parallel()
   819  	nfail := 0
   820  	test := func(f float64, bits int) {
   821  		vf := interface{}(f)
   822  		if bits == 32 {
   823  			f = float64(float32(f)) // round
   824  			vf = float32(f)
   825  		}
   826  		bout, err := Marshal(vf)
   827  		if err != nil {
   828  			t.Errorf("Marshal(%T(%g)): %v", vf, vf, err)
   829  			nfail++
   830  			return
   831  		}
   832  		out := string(bout)
   833  
   834  		// result must convert back to the same float
   835  		g, err := strconv.ParseFloat(out, bits)
   836  		if err != nil {
   837  			t.Errorf("Marshal(%T(%g)) = %q, cannot parse back: %v", vf, vf, out, err)
   838  			nfail++
   839  			return
   840  		}
   841  		if f != g || fmt.Sprint(f) != fmt.Sprint(g) { // fmt.Sprint handles ±0
   842  			t.Errorf("Marshal(%T(%g)) = %q (is %g, not %g)", vf, vf, out, float32(g), vf)
   843  			nfail++
   844  			return
   845  		}
   846  
   847  		bad := badFloatREs
   848  		if bits == 64 {
   849  			bad = bad[:len(bad)-2]
   850  		}
   851  		for _, re := range bad {
   852  			if re.MatchString(out) {
   853  				t.Errorf("Marshal(%T(%g)) = %q, must not match /%s/", vf, vf, out, re)
   854  				nfail++
   855  				return
   856  			}
   857  		}
   858  	}
   859  
   860  	var (
   861  		bigger  = math.Inf(+1)
   862  		smaller = math.Inf(-1)
   863  	)
   864  
   865  	var digits = "1.2345678901234567890123"
   866  	for i := len(digits); i >= 2; i-- {
   867  		for exp := -30; exp <= 30; exp++ {
   868  			for _, sign := range "+-" {
   869  				for bits := 32; bits <= 64; bits += 32 {
   870  					s := fmt.Sprintf("%c%se%d", sign, digits[:i], exp)
   871  					f, err := strconv.ParseFloat(s, bits)
   872  					if err != nil {
   873  						log.Fatal(err)
   874  					}
   875  					next := math.Nextafter
   876  					if bits == 32 {
   877  						next = func(g, h float64) float64 {
   878  							return float64(math.Nextafter32(float32(g), float32(h)))
   879  						}
   880  					}
   881  					test(f, bits)
   882  					test(next(f, bigger), bits)
   883  					test(next(f, smaller), bits)
   884  					if nfail > 50 {
   885  						t.Fatalf("stopping test early")
   886  					}
   887  				}
   888  			}
   889  		}
   890  	}
   891  	test(0, 64)
   892  	test(math.Copysign(0, -1), 64)
   893  	test(0, 32)
   894  	test(math.Copysign(0, -1), 32)
   895  }
   896  
   897  func TestMarshalRawMessageValue(t *testing.T) {
   898  	type (
   899  		T1 struct {
   900  			M RawMessage `json:",omitempty"`
   901  		}
   902  		T2 struct {
   903  			M *RawMessage `json:",omitempty"`
   904  		}
   905  	)
   906  
   907  	var (
   908  		rawNil   = RawMessage(nil)
   909  		rawEmpty = RawMessage([]byte{})
   910  		rawText  = RawMessage([]byte(`"foo"`))
   911  	)
   912  
   913  	tests := []struct {
   914  		in   interface{}
   915  		want string
   916  		ok   bool
   917  	}{
   918  		// Test with nil RawMessage.
   919  		{rawNil, "null", true},
   920  		{&rawNil, "null", true},
   921  		{[]interface{}{rawNil}, "[null]", true},
   922  		{&[]interface{}{rawNil}, "[null]", true},
   923  		{[]interface{}{&rawNil}, "[null]", true},
   924  		{&[]interface{}{&rawNil}, "[null]", true},
   925  		{struct{ M RawMessage }{rawNil}, `{"M":null}`, true},
   926  		{&struct{ M RawMessage }{rawNil}, `{"M":null}`, true},
   927  		{struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true},
   928  		{&struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true},
   929  		{map[string]interface{}{"M": rawNil}, `{"M":null}`, true},
   930  		{&map[string]interface{}{"M": rawNil}, `{"M":null}`, true},
   931  		{map[string]interface{}{"M": &rawNil}, `{"M":null}`, true},
   932  		{&map[string]interface{}{"M": &rawNil}, `{"M":null}`, true},
   933  		{T1{rawNil}, "{}", true},
   934  		{T2{&rawNil}, `{"M":null}`, true},
   935  		{&T1{rawNil}, "{}", true},
   936  		{&T2{&rawNil}, `{"M":null}`, true},
   937  
   938  		// Test with empty, but non-nil, RawMessage.
   939  		{rawEmpty, "", false},
   940  		{&rawEmpty, "", false},
   941  		{[]interface{}{rawEmpty}, "", false},
   942  		{&[]interface{}{rawEmpty}, "", false},
   943  		{[]interface{}{&rawEmpty}, "", false},
   944  		{&[]interface{}{&rawEmpty}, "", false},
   945  		{struct{ X RawMessage }{rawEmpty}, "", false},
   946  		{&struct{ X RawMessage }{rawEmpty}, "", false},
   947  		{struct{ X *RawMessage }{&rawEmpty}, "", false},
   948  		{&struct{ X *RawMessage }{&rawEmpty}, "", false},
   949  		{map[string]interface{}{"nil": rawEmpty}, "", false},
   950  		{&map[string]interface{}{"nil": rawEmpty}, "", false},
   951  		{map[string]interface{}{"nil": &rawEmpty}, "", false},
   952  		{&map[string]interface{}{"nil": &rawEmpty}, "", false},
   953  		{T1{rawEmpty}, "{}", true},
   954  		{T2{&rawEmpty}, "", false},
   955  		{&T1{rawEmpty}, "{}", true},
   956  		{&T2{&rawEmpty}, "", false},
   957  
   958  		// Test with RawMessage with some text.
   959  		//
   960  		// The tests below marked with Issue6458 used to generate "ImZvbyI=" instead "foo".
   961  		// This behavior was intentionally changed in Go 1.8.
   962  		// See https://golang.org/issues/14493#issuecomment-255857318
   963  		{rawText, `"foo"`, true}, // Issue6458
   964  		{&rawText, `"foo"`, true},
   965  		{[]interface{}{rawText}, `["foo"]`, true},  // Issue6458
   966  		{&[]interface{}{rawText}, `["foo"]`, true}, // Issue6458
   967  		{[]interface{}{&rawText}, `["foo"]`, true},
   968  		{&[]interface{}{&rawText}, `["foo"]`, true},
   969  		{struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true}, // Issue6458
   970  		{&struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true},
   971  		{struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true},
   972  		{&struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true},
   973  		{map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true},  // Issue6458
   974  		{&map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458
   975  		{map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true},
   976  		{&map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true},
   977  		{T1{rawText}, `{"M":"foo"}`, true}, // Issue6458
   978  		{T2{&rawText}, `{"M":"foo"}`, true},
   979  		{&T1{rawText}, `{"M":"foo"}`, true},
   980  		{&T2{&rawText}, `{"M":"foo"}`, true},
   981  	}
   982  
   983  	for i, tt := range tests {
   984  		b, err := Marshal(tt.in)
   985  		if ok := (err == nil); ok != tt.ok {
   986  			if err != nil {
   987  				t.Errorf("test %d, unexpected failure: %v", i, err)
   988  			} else {
   989  				t.Errorf("test %d, unexpected success", i)
   990  			}
   991  		}
   992  		if got := string(b); got != tt.want {
   993  			t.Errorf("test %d, Marshal(%#v) = %q, want %q", i, tt.in, got, tt.want)
   994  		}
   995  	}
   996  }
   997  
   998  type marshalPanic struct{}
   999  
  1000  func (marshalPanic) MarshalJSON() ([]byte, error) { panic(0xdead) }
  1001  
  1002  func TestMarshalPanic(t *testing.T) {
  1003  	defer func() {
  1004  		if got := recover(); !reflect.DeepEqual(got, 0xdead) {
  1005  			t.Errorf("panic() = (%T)(%v), want 0xdead", got, got)
  1006  		}
  1007  	}()
  1008  	Marshal(&marshalPanic{})
  1009  	t.Error("Marshal should have panicked")
  1010  }
  1011  
  1012  func TestMarshalUncommonFieldNames(t *testing.T) {
  1013  	v := struct {
  1014  		A0, À, Aβ int
  1015  	}{}
  1016  	b, err := Marshal(v)
  1017  	if err != nil {
  1018  		t.Fatal("Marshal:", err)
  1019  	}
  1020  	want := `{"A0":0,"À":0,"Aβ":0}`
  1021  	got := string(b)
  1022  	if got != want {
  1023  		t.Fatalf("Marshal: got %s want %s", got, want)
  1024  	}
  1025  }
  1026  

View as plain text