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