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