github.com/huandu/go@v0.0.0-20151114150818-04e615e41150/src/encoding/gob/encoder_test.go (about)

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