...

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

View as plain text