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