...
Run Format

Source file src/encoding/gob/encoder_test.go

Documentation: encoding/gob

     1  // Copyright 2009 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 gob
     6  
     7  import (
     8  	"bytes"
     9  	"encoding/hex"
    10  	"fmt"
    11  	"io/ioutil"
    12  	"reflect"
    13  	"runtime"
    14  	"strings"
    15  	"testing"
    16  )
    17  
    18  // Test basic operations in a safe manner.
    19  func TestBasicEncoderDecoder(t *testing.T) {
    20  	var values = []interface{}{
    21  		true,
    22  		int(123),
    23  		int8(123),
    24  		int16(-12345),
    25  		int32(123456),
    26  		int64(-1234567),
    27  		uint(123),
    28  		uint8(123),
    29  		uint16(12345),
    30  		uint32(123456),
    31  		uint64(1234567),
    32  		uintptr(12345678),
    33  		float32(1.2345),
    34  		float64(1.2345678),
    35  		complex64(1.2345 + 2.3456i),
    36  		complex128(1.2345678 + 2.3456789i),
    37  		[]byte("hello"),
    38  		string("hello"),
    39  	}
    40  	for _, value := range values {
    41  		b := new(bytes.Buffer)
    42  		enc := NewEncoder(b)
    43  		err := enc.Encode(value)
    44  		if err != nil {
    45  			t.Error("encoder fail:", err)
    46  		}
    47  		dec := NewDecoder(b)
    48  		result := reflect.New(reflect.TypeOf(value))
    49  		err = dec.Decode(result.Interface())
    50  		if err != nil {
    51  			t.Fatalf("error decoding %T: %v:", reflect.TypeOf(value), err)
    52  		}
    53  		if !reflect.DeepEqual(value, result.Elem().Interface()) {
    54  			t.Fatalf("%T: expected %v got %v", value, value, result.Elem().Interface())
    55  		}
    56  	}
    57  }
    58  
    59  func TestEncodeIntSlice(t *testing.T) {
    60  
    61  	s8 := []int8{1, 5, 12, 22, 35, 51, 70, 92, 117}
    62  	s16 := []int16{145, 176, 210, 247, 287, 330, 376, 425, 477}
    63  	s32 := []int32{532, 590, 651, 715, 782, 852, 925, 1001, 1080}
    64  	s64 := []int64{1162, 1247, 1335, 1426, 1520, 1617, 1717, 1820, 1926}
    65  
    66  	t.Run("int8", func(t *testing.T) {
    67  		var sink bytes.Buffer
    68  		enc := NewEncoder(&sink)
    69  		enc.Encode(s8)
    70  
    71  		dec := NewDecoder(&sink)
    72  		res := make([]int8, 9)
    73  		dec.Decode(&res)
    74  
    75  		if !reflect.DeepEqual(s8, res) {
    76  			t.Fatalf("EncodeIntSlice: expected %v, got %v", s8, res)
    77  		}
    78  	})
    79  
    80  	t.Run("int16", func(t *testing.T) {
    81  		var sink bytes.Buffer
    82  		enc := NewEncoder(&sink)
    83  		enc.Encode(s16)
    84  
    85  		dec := NewDecoder(&sink)
    86  		res := make([]int16, 9)
    87  		dec.Decode(&res)
    88  
    89  		if !reflect.DeepEqual(s16, res) {
    90  			t.Fatalf("EncodeIntSlice: expected %v, got %v", s16, res)
    91  		}
    92  	})
    93  
    94  	t.Run("int32", func(t *testing.T) {
    95  		var sink bytes.Buffer
    96  		enc := NewEncoder(&sink)
    97  		enc.Encode(s32)
    98  
    99  		dec := NewDecoder(&sink)
   100  		res := make([]int32, 9)
   101  		dec.Decode(&res)
   102  
   103  		if !reflect.DeepEqual(s32, res) {
   104  			t.Fatalf("EncodeIntSlice: expected %v, got %v", s32, res)
   105  		}
   106  	})
   107  
   108  	t.Run("int64", func(t *testing.T) {
   109  		var sink bytes.Buffer
   110  		enc := NewEncoder(&sink)
   111  		enc.Encode(s64)
   112  
   113  		dec := NewDecoder(&sink)
   114  		res := make([]int64, 9)
   115  		dec.Decode(&res)
   116  
   117  		if !reflect.DeepEqual(s64, res) {
   118  			t.Fatalf("EncodeIntSlice: expected %v, got %v", s64, res)
   119  		}
   120  	})
   121  
   122  }
   123  
   124  type ET0 struct {
   125  	A int
   126  	B string
   127  }
   128  
   129  type ET2 struct {
   130  	X string
   131  }
   132  
   133  type ET1 struct {
   134  	A    int
   135  	Et2  *ET2
   136  	Next *ET1
   137  }
   138  
   139  // Like ET1 but with a different name for a field
   140  type ET3 struct {
   141  	A             int
   142  	Et2           *ET2
   143  	DifferentNext *ET1
   144  }
   145  
   146  // Like ET1 but with a different type for a field
   147  type ET4 struct {
   148  	A    int
   149  	Et2  float64
   150  	Next int
   151  }
   152  
   153  func TestEncoderDecoder(t *testing.T) {
   154  	b := new(bytes.Buffer)
   155  	enc := NewEncoder(b)
   156  	et0 := new(ET0)
   157  	et0.A = 7
   158  	et0.B = "gobs of fun"
   159  	err := enc.Encode(et0)
   160  	if err != nil {
   161  		t.Error("encoder fail:", err)
   162  	}
   163  	//fmt.Printf("% x %q\n", b, b)
   164  	//Debug(b)
   165  	dec := NewDecoder(b)
   166  	newEt0 := new(ET0)
   167  	err = dec.Decode(newEt0)
   168  	if err != nil {
   169  		t.Fatal("error decoding ET0:", err)
   170  	}
   171  
   172  	if !reflect.DeepEqual(et0, newEt0) {
   173  		t.Fatalf("invalid data for et0: expected %+v; got %+v", *et0, *newEt0)
   174  	}
   175  	if b.Len() != 0 {
   176  		t.Error("not at eof;", b.Len(), "bytes left")
   177  	}
   178  	//	t.FailNow()
   179  
   180  	b = new(bytes.Buffer)
   181  	enc = NewEncoder(b)
   182  	et1 := new(ET1)
   183  	et1.A = 7
   184  	et1.Et2 = new(ET2)
   185  	err = enc.Encode(et1)
   186  	if err != nil {
   187  		t.Error("encoder fail:", err)
   188  	}
   189  	dec = NewDecoder(b)
   190  	newEt1 := new(ET1)
   191  	err = dec.Decode(newEt1)
   192  	if err != nil {
   193  		t.Fatal("error decoding ET1:", err)
   194  	}
   195  
   196  	if !reflect.DeepEqual(et1, newEt1) {
   197  		t.Fatalf("invalid data for et1: expected %+v; got %+v", *et1, *newEt1)
   198  	}
   199  	if b.Len() != 0 {
   200  		t.Error("not at eof;", b.Len(), "bytes left")
   201  	}
   202  
   203  	enc.Encode(et1)
   204  	newEt1 = new(ET1)
   205  	err = dec.Decode(newEt1)
   206  	if err != nil {
   207  		t.Fatal("round 2: error decoding ET1:", err)
   208  	}
   209  	if !reflect.DeepEqual(et1, newEt1) {
   210  		t.Fatalf("round 2: invalid data for et1: expected %+v; got %+v", *et1, *newEt1)
   211  	}
   212  	if b.Len() != 0 {
   213  		t.Error("round 2: not at eof;", b.Len(), "bytes left")
   214  	}
   215  
   216  	// Now test with a running encoder/decoder pair that we recognize a type mismatch.
   217  	err = enc.Encode(et1)
   218  	if err != nil {
   219  		t.Error("round 3: encoder fail:", err)
   220  	}
   221  	newEt2 := new(ET2)
   222  	err = dec.Decode(newEt2)
   223  	if err == nil {
   224  		t.Fatal("round 3: expected `bad type' error decoding ET2")
   225  	}
   226  }
   227  
   228  // Run one value through the encoder/decoder, but use the wrong type.
   229  // Input is always an ET1; we compare it to whatever is under 'e'.
   230  func badTypeCheck(e interface{}, shouldFail bool, msg string, t *testing.T) {
   231  	b := new(bytes.Buffer)
   232  	enc := NewEncoder(b)
   233  	et1 := new(ET1)
   234  	et1.A = 7
   235  	et1.Et2 = new(ET2)
   236  	err := enc.Encode(et1)
   237  	if err != nil {
   238  		t.Error("encoder fail:", err)
   239  	}
   240  	dec := NewDecoder(b)
   241  	err = dec.Decode(e)
   242  	if shouldFail && err == nil {
   243  		t.Error("expected error for", msg)
   244  	}
   245  	if !shouldFail && err != nil {
   246  		t.Error("unexpected error for", msg, err)
   247  	}
   248  }
   249  
   250  // Test that we recognize a bad type the first time.
   251  func TestWrongTypeDecoder(t *testing.T) {
   252  	badTypeCheck(new(ET2), true, "no fields in common", t)
   253  	badTypeCheck(new(ET3), false, "different name of field", t)
   254  	badTypeCheck(new(ET4), true, "different type of field", t)
   255  }
   256  
   257  // Types not supported at top level by the Encoder.
   258  var unsupportedValues = []interface{}{
   259  	make(chan int),
   260  	func(a int) bool { return true },
   261  }
   262  
   263  func TestUnsupported(t *testing.T) {
   264  	var b bytes.Buffer
   265  	enc := NewEncoder(&b)
   266  	for _, v := range unsupportedValues {
   267  		err := enc.Encode(v)
   268  		if err == nil {
   269  			t.Errorf("expected error for %T; got none", v)
   270  		}
   271  	}
   272  }
   273  
   274  func encAndDec(in, out interface{}) error {
   275  	b := new(bytes.Buffer)
   276  	enc := NewEncoder(b)
   277  	err := enc.Encode(in)
   278  	if err != nil {
   279  		return err
   280  	}
   281  	dec := NewDecoder(b)
   282  	err = dec.Decode(out)
   283  	if err != nil {
   284  		return err
   285  	}
   286  	return nil
   287  }
   288  
   289  func TestTypeToPtrType(t *testing.T) {
   290  	// Encode a T, decode a *T
   291  	type Type0 struct {
   292  		A int
   293  	}
   294  	t0 := Type0{7}
   295  	t0p := new(Type0)
   296  	if err := encAndDec(t0, t0p); err != nil {
   297  		t.Error(err)
   298  	}
   299  }
   300  
   301  func TestPtrTypeToType(t *testing.T) {
   302  	// Encode a *T, decode a T
   303  	type Type1 struct {
   304  		A uint
   305  	}
   306  	t1p := &Type1{17}
   307  	var t1 Type1
   308  	if err := encAndDec(t1, t1p); err != nil {
   309  		t.Error(err)
   310  	}
   311  }
   312  
   313  func TestTypeToPtrPtrPtrPtrType(t *testing.T) {
   314  	type Type2 struct {
   315  		A ****float64
   316  	}
   317  	t2 := Type2{}
   318  	t2.A = new(***float64)
   319  	*t2.A = new(**float64)
   320  	**t2.A = new(*float64)
   321  	***t2.A = new(float64)
   322  	****t2.A = 27.4
   323  	t2pppp := new(***Type2)
   324  	if err := encAndDec(t2, t2pppp); err != nil {
   325  		t.Fatal(err)
   326  	}
   327  	if ****(****t2pppp).A != ****t2.A {
   328  		t.Errorf("wrong value after decode: %g not %g", ****(****t2pppp).A, ****t2.A)
   329  	}
   330  }
   331  
   332  func TestSlice(t *testing.T) {
   333  	type Type3 struct {
   334  		A []string
   335  	}
   336  	t3p := &Type3{[]string{"hello", "world"}}
   337  	var t3 Type3
   338  	if err := encAndDec(t3, t3p); err != nil {
   339  		t.Error(err)
   340  	}
   341  }
   342  
   343  func TestValueError(t *testing.T) {
   344  	// Encode a *T, decode a T
   345  	type Type4 struct {
   346  		A int
   347  	}
   348  	t4p := &Type4{3}
   349  	var t4 Type4 // note: not a pointer.
   350  	if err := encAndDec(t4p, t4); err == nil || !strings.Contains(err.Error(), "pointer") {
   351  		t.Error("expected error about pointer; got", err)
   352  	}
   353  }
   354  
   355  func TestArray(t *testing.T) {
   356  	type Type5 struct {
   357  		A [3]string
   358  		B [3]byte
   359  	}
   360  	type Type6 struct {
   361  		A [2]string // can't hold t5.a
   362  	}
   363  	t5 := Type5{[3]string{"hello", ",", "world"}, [3]byte{1, 2, 3}}
   364  	var t5p Type5
   365  	if err := encAndDec(t5, &t5p); err != nil {
   366  		t.Error(err)
   367  	}
   368  	var t6 Type6
   369  	if err := encAndDec(t5, &t6); err == nil {
   370  		t.Error("should fail with mismatched array sizes")
   371  	}
   372  }
   373  
   374  func TestRecursiveMapType(t *testing.T) {
   375  	type recursiveMap map[string]recursiveMap
   376  	r1 := recursiveMap{"A": recursiveMap{"B": nil, "C": nil}, "D": nil}
   377  	r2 := make(recursiveMap)
   378  	if err := encAndDec(r1, &r2); err != nil {
   379  		t.Error(err)
   380  	}
   381  }
   382  
   383  func TestRecursiveSliceType(t *testing.T) {
   384  	type recursiveSlice []recursiveSlice
   385  	r1 := recursiveSlice{0: recursiveSlice{0: nil}, 1: nil}
   386  	r2 := make(recursiveSlice, 0)
   387  	if err := encAndDec(r1, &r2); err != nil {
   388  		t.Error(err)
   389  	}
   390  }
   391  
   392  // Regression test for bug: must send zero values inside arrays
   393  func TestDefaultsInArray(t *testing.T) {
   394  	type Type7 struct {
   395  		B []bool
   396  		I []int
   397  		S []string
   398  		F []float64
   399  	}
   400  	t7 := Type7{
   401  		[]bool{false, false, true},
   402  		[]int{0, 0, 1},
   403  		[]string{"hi", "", "there"},
   404  		[]float64{0, 0, 1},
   405  	}
   406  	var t7p Type7
   407  	if err := encAndDec(t7, &t7p); err != nil {
   408  		t.Error(err)
   409  	}
   410  }
   411  
   412  var testInt int
   413  var testFloat32 float32
   414  var testString string
   415  var testSlice []string
   416  var testMap map[string]int
   417  var testArray [7]int
   418  
   419  type SingleTest struct {
   420  	in  interface{}
   421  	out interface{}
   422  	err string
   423  }
   424  
   425  var singleTests = []SingleTest{
   426  	{17, &testInt, ""},
   427  	{float32(17.5), &testFloat32, ""},
   428  	{"bike shed", &testString, ""},
   429  	{[]string{"bike", "shed", "paint", "color"}, &testSlice, ""},
   430  	{map[string]int{"seven": 7, "twelve": 12}, &testMap, ""},
   431  	{[7]int{4, 55, 0, 0, 0, 0, 0}, &testArray, ""}, // case that once triggered a bug
   432  	{[7]int{4, 55, 1, 44, 22, 66, 1234}, &testArray, ""},
   433  
   434  	// Decode errors
   435  	{172, &testFloat32, "type"},
   436  }
   437  
   438  func TestSingletons(t *testing.T) {
   439  	b := new(bytes.Buffer)
   440  	enc := NewEncoder(b)
   441  	dec := NewDecoder(b)
   442  	for _, test := range singleTests {
   443  		b.Reset()
   444  		err := enc.Encode(test.in)
   445  		if err != nil {
   446  			t.Errorf("error encoding %v: %s", test.in, err)
   447  			continue
   448  		}
   449  		err = dec.Decode(test.out)
   450  		switch {
   451  		case err != nil && test.err == "":
   452  			t.Errorf("error decoding %v: %s", test.in, err)
   453  			continue
   454  		case err == nil && test.err != "":
   455  			t.Errorf("expected error decoding %v: %s", test.in, test.err)
   456  			continue
   457  		case err != nil && test.err != "":
   458  			if !strings.Contains(err.Error(), test.err) {
   459  				t.Errorf("wrong error decoding %v: wanted %s, got %v", test.in, test.err, err)
   460  			}
   461  			continue
   462  		}
   463  		// Get rid of the pointer in the rhs
   464  		val := reflect.ValueOf(test.out).Elem().Interface()
   465  		if !reflect.DeepEqual(test.in, val) {
   466  			t.Errorf("decoding singleton: expected %v got %v", test.in, val)
   467  		}
   468  	}
   469  }
   470  
   471  func TestStructNonStruct(t *testing.T) {
   472  	type Struct struct {
   473  		A string
   474  	}
   475  	type NonStruct string
   476  	s := Struct{"hello"}
   477  	var sp Struct
   478  	if err := encAndDec(s, &sp); err != nil {
   479  		t.Error(err)
   480  	}
   481  	var ns NonStruct
   482  	if err := encAndDec(s, &ns); err == nil {
   483  		t.Error("should get error for struct/non-struct")
   484  	} else if !strings.Contains(err.Error(), "type") {
   485  		t.Error("for struct/non-struct expected type error; got", err)
   486  	}
   487  	// Now try the other way
   488  	var nsp NonStruct
   489  	if err := encAndDec(ns, &nsp); err != nil {
   490  		t.Error(err)
   491  	}
   492  	if err := encAndDec(ns, &s); err == nil {
   493  		t.Error("should get error for non-struct/struct")
   494  	} else if !strings.Contains(err.Error(), "type") {
   495  		t.Error("for non-struct/struct expected type error; got", err)
   496  	}
   497  }
   498  
   499  type interfaceIndirectTestI interface {
   500  	F() bool
   501  }
   502  
   503  type interfaceIndirectTestT struct{}
   504  
   505  func (this *interfaceIndirectTestT) F() bool {
   506  	return true
   507  }
   508  
   509  // A version of a bug reported on golang-nuts. Also tests top-level
   510  // slice of interfaces. The issue was registering *T caused T to be
   511  // stored as the concrete type.
   512  func TestInterfaceIndirect(t *testing.T) {
   513  	Register(&interfaceIndirectTestT{})
   514  	b := new(bytes.Buffer)
   515  	w := []interfaceIndirectTestI{&interfaceIndirectTestT{}}
   516  	err := NewEncoder(b).Encode(w)
   517  	if err != nil {
   518  		t.Fatal("encode error:", err)
   519  	}
   520  
   521  	var r []interfaceIndirectTestI
   522  	err = NewDecoder(b).Decode(&r)
   523  	if err != nil {
   524  		t.Fatal("decode error:", err)
   525  	}
   526  }
   527  
   528  // Now follow various tests that decode into things that can't represent the
   529  // encoded value, all of which should be legal.
   530  
   531  // Also, when the ignored object contains an interface value, it may define
   532  // types. Make sure that skipping the value still defines the types by using
   533  // the encoder/decoder pair to send a value afterwards. If an interface
   534  // is sent, its type in the test is always NewType0, so this checks that the
   535  // encoder and decoder don't skew with respect to type definitions.
   536  
   537  type Struct0 struct {
   538  	I interface{}
   539  }
   540  
   541  type NewType0 struct {
   542  	S string
   543  }
   544  
   545  type ignoreTest struct {
   546  	in, out interface{}
   547  }
   548  
   549  var ignoreTests = []ignoreTest{
   550  	// Decode normal struct into an empty struct
   551  	{&struct{ A int }{23}, &struct{}{}},
   552  	// Decode normal struct into a nil.
   553  	{&struct{ A int }{23}, nil},
   554  	// Decode singleton string into a nil.
   555  	{"hello, world", nil},
   556  	// Decode singleton slice into a nil.
   557  	{[]int{1, 2, 3, 4}, nil},
   558  	// Decode struct containing an interface into a nil.
   559  	{&Struct0{&NewType0{"value0"}}, nil},
   560  	// Decode singleton slice of interfaces into a nil.
   561  	{[]interface{}{"hi", &NewType0{"value1"}, 23}, nil},
   562  }
   563  
   564  func TestDecodeIntoNothing(t *testing.T) {
   565  	Register(new(NewType0))
   566  	for i, test := range ignoreTests {
   567  		b := new(bytes.Buffer)
   568  		enc := NewEncoder(b)
   569  		err := enc.Encode(test.in)
   570  		if err != nil {
   571  			t.Errorf("%d: encode error %s:", i, err)
   572  			continue
   573  		}
   574  		dec := NewDecoder(b)
   575  		err = dec.Decode(test.out)
   576  		if err != nil {
   577  			t.Errorf("%d: decode error: %s", i, err)
   578  			continue
   579  		}
   580  		// Now see if the encoder and decoder are in a consistent state.
   581  		str := fmt.Sprintf("Value %d", i)
   582  		err = enc.Encode(&NewType0{str})
   583  		if err != nil {
   584  			t.Fatalf("%d: NewType0 encode error: %s", i, err)
   585  		}
   586  		ns := new(NewType0)
   587  		err = dec.Decode(ns)
   588  		if err != nil {
   589  			t.Fatalf("%d: NewType0 decode error: %s", i, err)
   590  		}
   591  		if ns.S != str {
   592  			t.Fatalf("%d: expected %q got %q", i, str, ns.S)
   593  		}
   594  	}
   595  }
   596  
   597  func TestIgnoreRecursiveType(t *testing.T) {
   598  	// It's hard to build a self-contained test for this because
   599  	// we can't build compatible types in one package with
   600  	// different items so something is ignored. Here is
   601  	// some data that represents, according to debug.go:
   602  	// type definition {
   603  	//	slice "recursiveSlice" id=106
   604  	//		elem id=106
   605  	// }
   606  	data := []byte{
   607  		0x1d, 0xff, 0xd3, 0x02, 0x01, 0x01, 0x0e, 0x72,
   608  		0x65, 0x63, 0x75, 0x72, 0x73, 0x69, 0x76, 0x65,
   609  		0x53, 0x6c, 0x69, 0x63, 0x65, 0x01, 0xff, 0xd4,
   610  		0x00, 0x01, 0xff, 0xd4, 0x00, 0x00, 0x07, 0xff,
   611  		0xd4, 0x00, 0x02, 0x01, 0x00, 0x00,
   612  	}
   613  	dec := NewDecoder(bytes.NewReader(data))
   614  	// Issue 10415: This caused infinite recursion.
   615  	err := dec.Decode(nil)
   616  	if err != nil {
   617  		t.Fatal(err)
   618  	}
   619  }
   620  
   621  // Another bug from golang-nuts, involving nested interfaces.
   622  type Bug0Outer struct {
   623  	Bug0Field interface{}
   624  }
   625  
   626  type Bug0Inner struct {
   627  	A int
   628  }
   629  
   630  func TestNestedInterfaces(t *testing.T) {
   631  	var buf bytes.Buffer
   632  	e := NewEncoder(&buf)
   633  	d := NewDecoder(&buf)
   634  	Register(new(Bug0Outer))
   635  	Register(new(Bug0Inner))
   636  	f := &Bug0Outer{&Bug0Outer{&Bug0Inner{7}}}
   637  	var v interface{} = f
   638  	err := e.Encode(&v)
   639  	if err != nil {
   640  		t.Fatal("Encode:", err)
   641  	}
   642  	err = d.Decode(&v)
   643  	if err != nil {
   644  		t.Fatal("Decode:", err)
   645  	}
   646  	// Make sure it decoded correctly.
   647  	outer1, ok := v.(*Bug0Outer)
   648  	if !ok {
   649  		t.Fatalf("v not Bug0Outer: %T", v)
   650  	}
   651  	outer2, ok := outer1.Bug0Field.(*Bug0Outer)
   652  	if !ok {
   653  		t.Fatalf("v.Bug0Field not Bug0Outer: %T", outer1.Bug0Field)
   654  	}
   655  	inner, ok := outer2.Bug0Field.(*Bug0Inner)
   656  	if !ok {
   657  		t.Fatalf("v.Bug0Field.Bug0Field not Bug0Inner: %T", outer2.Bug0Field)
   658  	}
   659  	if inner.A != 7 {
   660  		t.Fatalf("final value %d; expected %d", inner.A, 7)
   661  	}
   662  }
   663  
   664  // The bugs keep coming. We forgot to send map subtypes before the map.
   665  
   666  type Bug1Elem struct {
   667  	Name string
   668  	Id   int
   669  }
   670  
   671  type Bug1StructMap map[string]Bug1Elem
   672  
   673  func TestMapBug1(t *testing.T) {
   674  	in := make(Bug1StructMap)
   675  	in["val1"] = Bug1Elem{"elem1", 1}
   676  	in["val2"] = Bug1Elem{"elem2", 2}
   677  
   678  	b := new(bytes.Buffer)
   679  	enc := NewEncoder(b)
   680  	err := enc.Encode(in)
   681  	if err != nil {
   682  		t.Fatal("encode:", err)
   683  	}
   684  	dec := NewDecoder(b)
   685  	out := make(Bug1StructMap)
   686  	err = dec.Decode(&out)
   687  	if err != nil {
   688  		t.Fatal("decode:", err)
   689  	}
   690  	if !reflect.DeepEqual(in, out) {
   691  		t.Errorf("mismatch: %v %v", in, out)
   692  	}
   693  }
   694  
   695  func TestGobMapInterfaceEncode(t *testing.T) {
   696  	m := map[string]interface{}{
   697  		"up": uintptr(0),
   698  		"i0": []int{-1},
   699  		"i1": []int8{-1},
   700  		"i2": []int16{-1},
   701  		"i3": []int32{-1},
   702  		"i4": []int64{-1},
   703  		"u0": []uint{1},
   704  		"u1": []uint8{1},
   705  		"u2": []uint16{1},
   706  		"u3": []uint32{1},
   707  		"u4": []uint64{1},
   708  		"f0": []float32{1},
   709  		"f1": []float64{1},
   710  		"c0": []complex64{complex(2, -2)},
   711  		"c1": []complex128{complex(2, float64(-2))},
   712  		"us": []uintptr{0},
   713  		"bo": []bool{false},
   714  		"st": []string{"s"},
   715  	}
   716  	enc := NewEncoder(new(bytes.Buffer))
   717  	err := enc.Encode(m)
   718  	if err != nil {
   719  		t.Errorf("encode map: %s", err)
   720  	}
   721  }
   722  
   723  func TestSliceReusesMemory(t *testing.T) {
   724  	buf := new(bytes.Buffer)
   725  	// Bytes
   726  	{
   727  		x := []byte("abcd")
   728  		enc := NewEncoder(buf)
   729  		err := enc.Encode(x)
   730  		if err != nil {
   731  			t.Errorf("bytes: encode: %s", err)
   732  		}
   733  		// Decode into y, which is big enough.
   734  		y := []byte("ABCDE")
   735  		addr := &y[0]
   736  		dec := NewDecoder(buf)
   737  		err = dec.Decode(&y)
   738  		if err != nil {
   739  			t.Fatal("bytes: decode:", err)
   740  		}
   741  		if !bytes.Equal(x, y) {
   742  			t.Errorf("bytes: expected %q got %q\n", x, y)
   743  		}
   744  		if addr != &y[0] {
   745  			t.Errorf("bytes: unnecessary reallocation")
   746  		}
   747  	}
   748  	// general slice
   749  	{
   750  		x := []rune("abcd")
   751  		enc := NewEncoder(buf)
   752  		err := enc.Encode(x)
   753  		if err != nil {
   754  			t.Errorf("ints: encode: %s", err)
   755  		}
   756  		// Decode into y, which is big enough.
   757  		y := []rune("ABCDE")
   758  		addr := &y[0]
   759  		dec := NewDecoder(buf)
   760  		err = dec.Decode(&y)
   761  		if err != nil {
   762  			t.Fatal("ints: decode:", err)
   763  		}
   764  		if !reflect.DeepEqual(x, y) {
   765  			t.Errorf("ints: expected %q got %q\n", x, y)
   766  		}
   767  		if addr != &y[0] {
   768  			t.Errorf("ints: unnecessary reallocation")
   769  		}
   770  	}
   771  }
   772  
   773  // Used to crash: negative count in recvMessage.
   774  func TestBadCount(t *testing.T) {
   775  	b := []byte{0xfb, 0xa5, 0x82, 0x2f, 0xca, 0x1}
   776  	if err := NewDecoder(bytes.NewReader(b)).Decode(nil); err == nil {
   777  		t.Error("expected error from bad count")
   778  	} else if err.Error() != errBadCount.Error() {
   779  		t.Error("expected bad count error; got", err)
   780  	}
   781  }
   782  
   783  // Verify that sequential Decoders built on a single input will
   784  // succeed if the input implements ReadByte and there is no
   785  // type information in the stream.
   786  func TestSequentialDecoder(t *testing.T) {
   787  	b := new(bytes.Buffer)
   788  	enc := NewEncoder(b)
   789  	const count = 10
   790  	for i := 0; i < count; i++ {
   791  		s := fmt.Sprintf("%d", i)
   792  		if err := enc.Encode(s); err != nil {
   793  			t.Error("encoder fail:", err)
   794  		}
   795  	}
   796  	for i := 0; i < count; i++ {
   797  		dec := NewDecoder(b)
   798  		var s string
   799  		if err := dec.Decode(&s); err != nil {
   800  			t.Fatal("decoder fail:", err)
   801  		}
   802  		if s != fmt.Sprintf("%d", i) {
   803  			t.Fatalf("decode expected %d got %s", i, s)
   804  		}
   805  	}
   806  }
   807  
   808  // Should be able to have unrepresentable fields (chan, func, *chan etc.); we just ignore them.
   809  type Bug2 struct {
   810  	A   int
   811  	C   chan int
   812  	CP  *chan int
   813  	F   func()
   814  	FPP **func()
   815  }
   816  
   817  func TestChanFuncIgnored(t *testing.T) {
   818  	c := make(chan int)
   819  	f := func() {}
   820  	fp := &f
   821  	b0 := Bug2{23, c, &c, f, &fp}
   822  	var buf bytes.Buffer
   823  	enc := NewEncoder(&buf)
   824  	if err := enc.Encode(b0); err != nil {
   825  		t.Fatal("error encoding:", err)
   826  	}
   827  	var b1 Bug2
   828  	err := NewDecoder(&buf).Decode(&b1)
   829  	if err != nil {
   830  		t.Fatal("decode:", err)
   831  	}
   832  	if b1.A != b0.A {
   833  		t.Fatalf("got %d want %d", b1.A, b0.A)
   834  	}
   835  	if b1.C != nil || b1.CP != nil || b1.F != nil || b1.FPP != nil {
   836  		t.Fatal("unexpected value for chan or func")
   837  	}
   838  }
   839  
   840  func TestSliceIncompatibility(t *testing.T) {
   841  	var in = []byte{1, 2, 3}
   842  	var out []int
   843  	if err := encAndDec(in, &out); err == nil {
   844  		t.Error("expected compatibility error")
   845  	}
   846  }
   847  
   848  // Mutually recursive slices of structs caused problems.
   849  type Bug3 struct {
   850  	Num      int
   851  	Children []*Bug3
   852  }
   853  
   854  func TestGobPtrSlices(t *testing.T) {
   855  	in := []*Bug3{
   856  		{1, nil},
   857  		{2, nil},
   858  	}
   859  	b := new(bytes.Buffer)
   860  	err := NewEncoder(b).Encode(&in)
   861  	if err != nil {
   862  		t.Fatal("encode:", err)
   863  	}
   864  
   865  	var out []*Bug3
   866  	err = NewDecoder(b).Decode(&out)
   867  	if err != nil {
   868  		t.Fatal("decode:", err)
   869  	}
   870  	if !reflect.DeepEqual(in, out) {
   871  		t.Fatalf("got %v; wanted %v", out, in)
   872  	}
   873  }
   874  
   875  // getDecEnginePtr cached engine for ut.base instead of ut.user so we passed
   876  // a *map and then tried to reuse its engine to decode the inner map.
   877  func TestPtrToMapOfMap(t *testing.T) {
   878  	Register(make(map[string]interface{}))
   879  	subdata := make(map[string]interface{})
   880  	subdata["bar"] = "baz"
   881  	data := make(map[string]interface{})
   882  	data["foo"] = subdata
   883  
   884  	b := new(bytes.Buffer)
   885  	err := NewEncoder(b).Encode(data)
   886  	if err != nil {
   887  		t.Fatal("encode:", err)
   888  	}
   889  	var newData map[string]interface{}
   890  	err = NewDecoder(b).Decode(&newData)
   891  	if err != nil {
   892  		t.Fatal("decode:", err)
   893  	}
   894  	if !reflect.DeepEqual(data, newData) {
   895  		t.Fatalf("expected %v got %v", data, newData)
   896  	}
   897  }
   898  
   899  // Test that untyped nils generate an error, not a panic.
   900  // See Issue 16204.
   901  func TestCatchInvalidNilValue(t *testing.T) {
   902  	encodeErr, panicErr := encodeAndRecover(nil)
   903  	if panicErr != nil {
   904  		t.Fatalf("panicErr=%v, should not panic encoding untyped nil", panicErr)
   905  	}
   906  	if encodeErr == nil {
   907  		t.Errorf("got err=nil, want non-nil error when encoding untyped nil value")
   908  	} else if !strings.Contains(encodeErr.Error(), "nil value") {
   909  		t.Errorf("expected 'nil value' error; got err=%v", encodeErr)
   910  	}
   911  }
   912  
   913  // A top-level nil pointer generates a panic with a helpful string-valued message.
   914  func TestTopLevelNilPointer(t *testing.T) {
   915  	var ip *int
   916  	encodeErr, panicErr := encodeAndRecover(ip)
   917  	if encodeErr != nil {
   918  		t.Fatal("error in encode:", encodeErr)
   919  	}
   920  	if panicErr == nil {
   921  		t.Fatal("top-level nil pointer did not panic")
   922  	}
   923  	errMsg := panicErr.Error()
   924  	if !strings.Contains(errMsg, "nil pointer") {
   925  		t.Fatal("expected nil pointer error, got:", errMsg)
   926  	}
   927  }
   928  
   929  func encodeAndRecover(value interface{}) (encodeErr, panicErr error) {
   930  	defer func() {
   931  		e := recover()
   932  		if e != nil {
   933  			switch err := e.(type) {
   934  			case error:
   935  				panicErr = err
   936  			default:
   937  				panicErr = fmt.Errorf("%v", err)
   938  			}
   939  		}
   940  	}()
   941  
   942  	encodeErr = NewEncoder(ioutil.Discard).Encode(value)
   943  	return
   944  }
   945  
   946  func TestNilPointerPanics(t *testing.T) {
   947  	var (
   948  		nilStringPtr      *string
   949  		intMap            = make(map[int]int)
   950  		intMapPtr         = &intMap
   951  		nilIntMapPtr      *map[int]int
   952  		zero              int
   953  		nilBoolChannel    chan bool
   954  		nilBoolChannelPtr *chan bool
   955  		nilStringSlice    []string
   956  		stringSlice       = make([]string, 1)
   957  		nilStringSlicePtr *[]string
   958  	)
   959  
   960  	testCases := []struct {
   961  		value     interface{}
   962  		mustPanic bool
   963  	}{
   964  		{nilStringPtr, true},
   965  		{intMap, false},
   966  		{intMapPtr, false},
   967  		{nilIntMapPtr, true},
   968  		{zero, false},
   969  		{nilStringSlice, false},
   970  		{stringSlice, false},
   971  		{nilStringSlicePtr, true},
   972  		{nilBoolChannel, false},
   973  		{nilBoolChannelPtr, true},
   974  	}
   975  
   976  	for _, tt := range testCases {
   977  		_, panicErr := encodeAndRecover(tt.value)
   978  		if tt.mustPanic {
   979  			if panicErr == nil {
   980  				t.Errorf("expected panic with input %#v, did not panic", tt.value)
   981  			}
   982  			continue
   983  		}
   984  		if panicErr != nil {
   985  			t.Fatalf("expected no panic with input %#v, got panic=%v", tt.value, panicErr)
   986  		}
   987  	}
   988  }
   989  
   990  func TestNilPointerInsideInterface(t *testing.T) {
   991  	var ip *int
   992  	si := struct {
   993  		I interface{}
   994  	}{
   995  		I: ip,
   996  	}
   997  	buf := new(bytes.Buffer)
   998  	err := NewEncoder(buf).Encode(si)
   999  	if err == nil {
  1000  		t.Fatal("expected error, got none")
  1001  	}
  1002  	errMsg := err.Error()
  1003  	if !strings.Contains(errMsg, "nil pointer") || !strings.Contains(errMsg, "interface") {
  1004  		t.Fatal("expected error about nil pointer and interface, got:", errMsg)
  1005  	}
  1006  }
  1007  
  1008  type Bug4Public struct {
  1009  	Name   string
  1010  	Secret Bug4Secret
  1011  }
  1012  
  1013  type Bug4Secret struct {
  1014  	a int // error: no exported fields.
  1015  }
  1016  
  1017  // Test that a failed compilation doesn't leave around an executable encoder.
  1018  // Issue 3723.
  1019  func TestMutipleEncodingsOfBadType(t *testing.T) {
  1020  	x := Bug4Public{
  1021  		Name:   "name",
  1022  		Secret: Bug4Secret{1},
  1023  	}
  1024  	buf := new(bytes.Buffer)
  1025  	enc := NewEncoder(buf)
  1026  	err := enc.Encode(x)
  1027  	if err == nil {
  1028  		t.Fatal("first encoding: expected error")
  1029  	}
  1030  	buf.Reset()
  1031  	enc = NewEncoder(buf)
  1032  	err = enc.Encode(x)
  1033  	if err == nil {
  1034  		t.Fatal("second encoding: expected error")
  1035  	}
  1036  	if !strings.Contains(err.Error(), "no exported fields") {
  1037  		t.Errorf("expected error about no exported fields; got %v", err)
  1038  	}
  1039  }
  1040  
  1041  // There was an error check comparing the length of the input with the
  1042  // length of the slice being decoded. It was wrong because the next
  1043  // thing in the input might be a type definition, which would lead to
  1044  // an incorrect length check. This test reproduces the corner case.
  1045  
  1046  type Z struct {
  1047  }
  1048  
  1049  func Test29ElementSlice(t *testing.T) {
  1050  	Register(Z{})
  1051  	src := make([]interface{}, 100) // Size needs to be bigger than size of type definition.
  1052  	for i := range src {
  1053  		src[i] = Z{}
  1054  	}
  1055  	buf := new(bytes.Buffer)
  1056  	err := NewEncoder(buf).Encode(src)
  1057  	if err != nil {
  1058  		t.Fatalf("encode: %v", err)
  1059  		return
  1060  	}
  1061  
  1062  	var dst []interface{}
  1063  	err = NewDecoder(buf).Decode(&dst)
  1064  	if err != nil {
  1065  		t.Errorf("decode: %v", err)
  1066  		return
  1067  	}
  1068  }
  1069  
  1070  // Don't crash, just give error when allocating a huge slice.
  1071  // Issue 8084.
  1072  func TestErrorForHugeSlice(t *testing.T) {
  1073  	// Encode an int slice.
  1074  	buf := new(bytes.Buffer)
  1075  	slice := []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
  1076  	err := NewEncoder(buf).Encode(slice)
  1077  	if err != nil {
  1078  		t.Fatal("encode:", err)
  1079  	}
  1080  	// Reach into the buffer and smash the count to make the encoded slice very long.
  1081  	buf.Bytes()[buf.Len()-len(slice)-1] = 0xfa
  1082  	// Decode and see error.
  1083  	err = NewDecoder(buf).Decode(&slice)
  1084  	if err == nil {
  1085  		t.Fatal("decode: no error")
  1086  	}
  1087  	if !strings.Contains(err.Error(), "slice too big") {
  1088  		t.Fatalf("decode: expected slice too big error, got %s", err.Error())
  1089  	}
  1090  }
  1091  
  1092  type badDataTest struct {
  1093  	input string      // The input encoded as a hex string.
  1094  	error string      // A substring of the error that should result.
  1095  	data  interface{} // What to decode into.
  1096  }
  1097  
  1098  var badDataTests = []badDataTest{
  1099  	{"", "EOF", nil},
  1100  	{"7F6869", "unexpected EOF", nil},
  1101  	{"036e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e", "unknown type id", new(ET2)},
  1102  	{"0424666f6f", "field numbers out of bounds", new(ET2)}, // Issue 6323.
  1103  	{"05100028557b02027f8302", "interface encoding", nil},   // Issue 10270.
  1104  	// Issue 10273.
  1105  	{"130a00fb5dad0bf8ff020263e70002fa28020202a89859", "slice length too large", nil},
  1106  	{"0f1000fb285d003316020735ff023a65c5", "interface encoding", nil},
  1107  	{"03fffb0616fffc00f902ff02ff03bf005d02885802a311a8120228022c028ee7", "GobDecoder", nil},
  1108  	// Issue 10491.
  1109  	{"10fe010f020102fe01100001fe010e000016fe010d030102fe010e00010101015801fe01100000000bfe011000f85555555555555555", "exceeds input size", nil},
  1110  }
  1111  
  1112  // TestBadData tests that various problems caused by malformed input
  1113  // are caught as errors and do not cause panics.
  1114  func TestBadData(t *testing.T) {
  1115  	for i, test := range badDataTests {
  1116  		data, err := hex.DecodeString(test.input)
  1117  		if err != nil {
  1118  			t.Fatalf("#%d: hex error: %s", i, err)
  1119  		}
  1120  		d := NewDecoder(bytes.NewReader(data))
  1121  		err = d.Decode(test.data)
  1122  		if err == nil {
  1123  			t.Errorf("decode: no error")
  1124  			continue
  1125  		}
  1126  		if !strings.Contains(err.Error(), test.error) {
  1127  			t.Errorf("#%d: decode: expected %q error, got %s", i, test.error, err.Error())
  1128  		}
  1129  	}
  1130  }
  1131  
  1132  // TestHugeWriteFails tests that enormous messages trigger an error.
  1133  func TestHugeWriteFails(t *testing.T) {
  1134  	if runtime.GOARCH == "wasm" {
  1135  		t.Skip("out of memory on wasm")
  1136  	}
  1137  	if testing.Short() {
  1138  		// Requires allocating a monster, so don't do this from all.bash.
  1139  		t.Skip("skipping huge allocation in short mode")
  1140  	}
  1141  	huge := make([]byte, tooBig)
  1142  	huge[0] = 7 // Make sure it's not all zeros.
  1143  	buf := new(bytes.Buffer)
  1144  	err := NewEncoder(buf).Encode(huge)
  1145  	if err == nil {
  1146  		t.Fatalf("expected error for huge slice")
  1147  	}
  1148  	if !strings.Contains(err.Error(), "message too big") {
  1149  		t.Fatalf("expected 'too big' error; got %s\n", err.Error())
  1150  	}
  1151  }
  1152  

View as plain text