github.com/gocuntian/go@v0.0.0-20160610041250-fee02d270bf8/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.Contains(err.Error(), "pointer") { 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.Contains(err.Error(), test.err) { 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.Contains(err.Error(), "type") { 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.Contains(err.Error(), "type") { 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 TestMapBug1(t *testing.T) { 607 in := make(Bug1StructMap) 608 in["val1"] = Bug1Elem{"elem1", 1} 609 in["val2"] = Bug1Elem{"elem2", 2} 610 611 b := new(bytes.Buffer) 612 enc := NewEncoder(b) 613 err := enc.Encode(in) 614 if err != nil { 615 t.Fatal("encode:", err) 616 } 617 dec := NewDecoder(b) 618 out := make(Bug1StructMap) 619 err = dec.Decode(&out) 620 if err != nil { 621 t.Fatal("decode:", err) 622 } 623 if !reflect.DeepEqual(in, out) { 624 t.Errorf("mismatch: %v %v", in, out) 625 } 626 } 627 628 func TestGobMapInterfaceEncode(t *testing.T) { 629 m := map[string]interface{}{ 630 "up": uintptr(0), 631 "i0": []int{-1}, 632 "i1": []int8{-1}, 633 "i2": []int16{-1}, 634 "i3": []int32{-1}, 635 "i4": []int64{-1}, 636 "u0": []uint{1}, 637 "u1": []uint8{1}, 638 "u2": []uint16{1}, 639 "u3": []uint32{1}, 640 "u4": []uint64{1}, 641 "f0": []float32{1}, 642 "f1": []float64{1}, 643 "c0": []complex64{complex(2, -2)}, 644 "c1": []complex128{complex(2, float64(-2))}, 645 "us": []uintptr{0}, 646 "bo": []bool{false}, 647 "st": []string{"s"}, 648 } 649 enc := NewEncoder(new(bytes.Buffer)) 650 err := enc.Encode(m) 651 if err != nil { 652 t.Errorf("encode map: %s", err) 653 } 654 } 655 656 func TestSliceReusesMemory(t *testing.T) { 657 buf := new(bytes.Buffer) 658 // Bytes 659 { 660 x := []byte("abcd") 661 enc := NewEncoder(buf) 662 err := enc.Encode(x) 663 if err != nil { 664 t.Errorf("bytes: encode: %s", err) 665 } 666 // Decode into y, which is big enough. 667 y := []byte("ABCDE") 668 addr := &y[0] 669 dec := NewDecoder(buf) 670 err = dec.Decode(&y) 671 if err != nil { 672 t.Fatal("bytes: decode:", err) 673 } 674 if !bytes.Equal(x, y) { 675 t.Errorf("bytes: expected %q got %q\n", x, y) 676 } 677 if addr != &y[0] { 678 t.Errorf("bytes: unnecessary reallocation") 679 } 680 } 681 // general slice 682 { 683 x := []rune("abcd") 684 enc := NewEncoder(buf) 685 err := enc.Encode(x) 686 if err != nil { 687 t.Errorf("ints: encode: %s", err) 688 } 689 // Decode into y, which is big enough. 690 y := []rune("ABCDE") 691 addr := &y[0] 692 dec := NewDecoder(buf) 693 err = dec.Decode(&y) 694 if err != nil { 695 t.Fatal("ints: decode:", err) 696 } 697 if !reflect.DeepEqual(x, y) { 698 t.Errorf("ints: expected %q got %q\n", x, y) 699 } 700 if addr != &y[0] { 701 t.Errorf("ints: unnecessary reallocation") 702 } 703 } 704 } 705 706 // Used to crash: negative count in recvMessage. 707 func TestBadCount(t *testing.T) { 708 b := []byte{0xfb, 0xa5, 0x82, 0x2f, 0xca, 0x1} 709 if err := NewDecoder(bytes.NewReader(b)).Decode(nil); err == nil { 710 t.Error("expected error from bad count") 711 } else if err.Error() != errBadCount.Error() { 712 t.Error("expected bad count error; got", err) 713 } 714 } 715 716 // Verify that sequential Decoders built on a single input will 717 // succeed if the input implements ReadByte and there is no 718 // type information in the stream. 719 func TestSequentialDecoder(t *testing.T) { 720 b := new(bytes.Buffer) 721 enc := NewEncoder(b) 722 const count = 10 723 for i := 0; i < count; i++ { 724 s := fmt.Sprintf("%d", i) 725 if err := enc.Encode(s); err != nil { 726 t.Error("encoder fail:", err) 727 } 728 } 729 for i := 0; i < count; i++ { 730 dec := NewDecoder(b) 731 var s string 732 if err := dec.Decode(&s); err != nil { 733 t.Fatal("decoder fail:", err) 734 } 735 if s != fmt.Sprintf("%d", i) { 736 t.Fatalf("decode expected %d got %s", i, s) 737 } 738 } 739 } 740 741 // Should be able to have unrepresentable fields (chan, func, *chan etc.); we just ignore them. 742 type Bug2 struct { 743 A int 744 C chan int 745 CP *chan int 746 F func() 747 FPP **func() 748 } 749 750 func TestChanFuncIgnored(t *testing.T) { 751 c := make(chan int) 752 f := func() {} 753 fp := &f 754 b0 := Bug2{23, c, &c, f, &fp} 755 var buf bytes.Buffer 756 enc := NewEncoder(&buf) 757 if err := enc.Encode(b0); err != nil { 758 t.Fatal("error encoding:", err) 759 } 760 var b1 Bug2 761 err := NewDecoder(&buf).Decode(&b1) 762 if err != nil { 763 t.Fatal("decode:", err) 764 } 765 if b1.A != b0.A { 766 t.Fatalf("got %d want %d", b1.A, b0.A) 767 } 768 if b1.C != nil || b1.CP != nil || b1.F != nil || b1.FPP != nil { 769 t.Fatal("unexpected value for chan or func") 770 } 771 } 772 773 func TestSliceIncompatibility(t *testing.T) { 774 var in = []byte{1, 2, 3} 775 var out []int 776 if err := encAndDec(in, &out); err == nil { 777 t.Error("expected compatibility error") 778 } 779 } 780 781 // Mutually recursive slices of structs caused problems. 782 type Bug3 struct { 783 Num int 784 Children []*Bug3 785 } 786 787 func TestGobPtrSlices(t *testing.T) { 788 in := []*Bug3{ 789 {1, nil}, 790 {2, nil}, 791 } 792 b := new(bytes.Buffer) 793 err := NewEncoder(b).Encode(&in) 794 if err != nil { 795 t.Fatal("encode:", err) 796 } 797 798 var out []*Bug3 799 err = NewDecoder(b).Decode(&out) 800 if err != nil { 801 t.Fatal("decode:", err) 802 } 803 if !reflect.DeepEqual(in, out) { 804 t.Fatalf("got %v; wanted %v", out, in) 805 } 806 } 807 808 // getDecEnginePtr cached engine for ut.base instead of ut.user so we passed 809 // a *map and then tried to reuse its engine to decode the inner map. 810 func TestPtrToMapOfMap(t *testing.T) { 811 Register(make(map[string]interface{})) 812 subdata := make(map[string]interface{}) 813 subdata["bar"] = "baz" 814 data := make(map[string]interface{}) 815 data["foo"] = subdata 816 817 b := new(bytes.Buffer) 818 err := NewEncoder(b).Encode(data) 819 if err != nil { 820 t.Fatal("encode:", err) 821 } 822 var newData map[string]interface{} 823 err = NewDecoder(b).Decode(&newData) 824 if err != nil { 825 t.Fatal("decode:", err) 826 } 827 if !reflect.DeepEqual(data, newData) { 828 t.Fatalf("expected %v got %v", data, newData) 829 } 830 } 831 832 // A top-level nil pointer generates a panic with a helpful string-valued message. 833 func TestTopLevelNilPointer(t *testing.T) { 834 errMsg := topLevelNilPanic(t) 835 if errMsg == "" { 836 t.Fatal("top-level nil pointer did not panic") 837 } 838 if !strings.Contains(errMsg, "nil pointer") { 839 t.Fatal("expected nil pointer error, got:", errMsg) 840 } 841 } 842 843 func topLevelNilPanic(t *testing.T) (panicErr string) { 844 defer func() { 845 e := recover() 846 if err, ok := e.(string); ok { 847 panicErr = err 848 } 849 }() 850 var ip *int 851 buf := new(bytes.Buffer) 852 if err := NewEncoder(buf).Encode(ip); err != nil { 853 t.Fatal("error in encode:", err) 854 } 855 return 856 } 857 858 func TestNilPointerInsideInterface(t *testing.T) { 859 var ip *int 860 si := struct { 861 I interface{} 862 }{ 863 I: ip, 864 } 865 buf := new(bytes.Buffer) 866 err := NewEncoder(buf).Encode(si) 867 if err == nil { 868 t.Fatal("expected error, got none") 869 } 870 errMsg := err.Error() 871 if !strings.Contains(errMsg, "nil pointer") || !strings.Contains(errMsg, "interface") { 872 t.Fatal("expected error about nil pointer and interface, got:", errMsg) 873 } 874 } 875 876 type Bug4Public struct { 877 Name string 878 Secret Bug4Secret 879 } 880 881 type Bug4Secret struct { 882 a int // error: no exported fields. 883 } 884 885 // Test that a failed compilation doesn't leave around an executable encoder. 886 // Issue 3273. 887 func TestMutipleEncodingsOfBadType(t *testing.T) { 888 x := Bug4Public{ 889 Name: "name", 890 Secret: Bug4Secret{1}, 891 } 892 buf := new(bytes.Buffer) 893 enc := NewEncoder(buf) 894 err := enc.Encode(x) 895 if err == nil { 896 t.Fatal("first encoding: expected error") 897 } 898 buf.Reset() 899 enc = NewEncoder(buf) 900 err = enc.Encode(x) 901 if err == nil { 902 t.Fatal("second encoding: expected error") 903 } 904 if !strings.Contains(err.Error(), "no exported fields") { 905 t.Errorf("expected error about no exported fields; got %v", err) 906 } 907 } 908 909 // There was an error check comparing the length of the input with the 910 // length of the slice being decoded. It was wrong because the next 911 // thing in the input might be a type definition, which would lead to 912 // an incorrect length check. This test reproduces the corner case. 913 914 type Z struct { 915 } 916 917 func Test29ElementSlice(t *testing.T) { 918 Register(Z{}) 919 src := make([]interface{}, 100) // Size needs to be bigger than size of type definition. 920 for i := range src { 921 src[i] = Z{} 922 } 923 buf := new(bytes.Buffer) 924 err := NewEncoder(buf).Encode(src) 925 if err != nil { 926 t.Fatalf("encode: %v", err) 927 return 928 } 929 930 var dst []interface{} 931 err = NewDecoder(buf).Decode(&dst) 932 if err != nil { 933 t.Errorf("decode: %v", err) 934 return 935 } 936 } 937 938 // Don't crash, just give error when allocating a huge slice. 939 // Issue 8084. 940 func TestErrorForHugeSlice(t *testing.T) { 941 // Encode an int slice. 942 buf := new(bytes.Buffer) 943 slice := []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1} 944 err := NewEncoder(buf).Encode(slice) 945 if err != nil { 946 t.Fatal("encode:", err) 947 } 948 // Reach into the buffer and smash the count to make the encoded slice very long. 949 buf.Bytes()[buf.Len()-len(slice)-1] = 0xfa 950 // Decode and see error. 951 err = NewDecoder(buf).Decode(&slice) 952 if err == nil { 953 t.Fatal("decode: no error") 954 } 955 if !strings.Contains(err.Error(), "slice too big") { 956 t.Fatalf("decode: expected slice too big error, got %s", err.Error()) 957 } 958 } 959 960 type badDataTest struct { 961 input string // The input encoded as a hex string. 962 error string // A substring of the error that should result. 963 data interface{} // What to decode into. 964 } 965 966 var badDataTests = []badDataTest{ 967 {"", "EOF", nil}, 968 {"7F6869", "unexpected EOF", nil}, 969 {"036e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e", "unknown type id", new(ET2)}, 970 {"0424666f6f", "field numbers out of bounds", new(ET2)}, // Issue 6323. 971 {"05100028557b02027f8302", "interface encoding", nil}, // Issue 10270. 972 // Issue 10273. 973 {"130a00fb5dad0bf8ff020263e70002fa28020202a89859", "slice length too large", nil}, 974 {"0f1000fb285d003316020735ff023a65c5", "interface encoding", nil}, 975 {"03fffb0616fffc00f902ff02ff03bf005d02885802a311a8120228022c028ee7", "GobDecoder", nil}, 976 // Issue 10491. 977 {"10fe010f020102fe01100001fe010e000016fe010d030102fe010e00010101015801fe01100000000bfe011000f85555555555555555", "exceeds input size", nil}, 978 } 979 980 // TestBadData tests that various problems caused by malformed input 981 // are caught as errors and do not cause panics. 982 func TestBadData(t *testing.T) { 983 for i, test := range badDataTests { 984 data, err := hex.DecodeString(test.input) 985 if err != nil { 986 t.Fatalf("#%d: hex error: %s", i, err) 987 } 988 d := NewDecoder(bytes.NewReader(data)) 989 err = d.Decode(test.data) 990 if err == nil { 991 t.Errorf("decode: no error") 992 continue 993 } 994 if !strings.Contains(err.Error(), test.error) { 995 t.Errorf("#%d: decode: expected %q error, got %s", i, test.error, err.Error()) 996 } 997 } 998 } 999 1000 // TestHugeWriteFails tests that enormous messages trigger an error. 1001 func TestHugeWriteFails(t *testing.T) { 1002 if testing.Short() { 1003 // Requires allocating a monster, so don't do this from all.bash. 1004 t.Skip("skipping huge allocation in short mode") 1005 } 1006 huge := make([]byte, tooBig) 1007 huge[0] = 7 // Make sure it's not all zeros. 1008 buf := new(bytes.Buffer) 1009 err := NewEncoder(buf).Encode(huge) 1010 if err == nil { 1011 t.Fatalf("expected error for huge slice") 1012 } 1013 if !strings.Contains(err.Error(), "message too big") { 1014 t.Fatalf("expected 'too big' error; got %s\n", err.Error()) 1015 } 1016 }