github.com/aergoio/aergo@v1.3.1/cmd/aergocli/util/encoding/json/encode_test.go (about)

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