libgo, compiler: Upgrade libgo to Go 1.4, except for runtime.
[official-gcc.git] / libgo / go / encoding / gob / encoder_test.go
blob0ea4c0ec8e5f479c5eff8d973353d03ea08d30ae
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.
5 package gob
7 import (
8 "bytes"
9 "fmt"
10 "io"
11 "reflect"
12 "strings"
13 "testing"
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"),
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)
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)
51 if !reflect.DeepEqual(value, result.Elem().Interface()) {
52 t.Fatalf("%T: expected %v got %v", value, value, result.Elem().Interface())
57 type ET0 struct {
58 A int
59 B string
62 type ET2 struct {
63 X string
66 type ET1 struct {
67 A int
68 Et2 *ET2
69 Next *ET1
72 // Like ET1 but with a different name for a field
73 type ET3 struct {
74 A int
75 Et2 *ET2
76 DifferentNext *ET1
79 // Like ET1 but with a different type for a field
80 type ET4 struct {
81 A int
82 Et2 float64
83 Next int
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)
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)
105 if !reflect.DeepEqual(et0, newEt0) {
106 t.Fatalf("invalid data for et0: expected %+v; got %+v", *et0, *newEt0)
108 if b.Len() != 0 {
109 t.Error("not at eof;", b.Len(), "bytes left")
111 // t.FailNow()
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)
122 dec = NewDecoder(b)
123 newEt1 := new(ET1)
124 err = dec.Decode(newEt1)
125 if err != nil {
126 t.Fatal("error decoding ET1:", err)
129 if !reflect.DeepEqual(et1, newEt1) {
130 t.Fatalf("invalid data for et1: expected %+v; got %+v", *et1, *newEt1)
132 if b.Len() != 0 {
133 t.Error("not at eof;", b.Len(), "bytes left")
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)
142 if !reflect.DeepEqual(et1, newEt1) {
143 t.Fatalf("round 2: invalid data for et1: expected %+v; got %+v", *et1, *newEt1)
145 if b.Len() != 0 {
146 t.Error("round 2: not at eof;", b.Len(), "bytes left")
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)
154 newEt2 := new(ET2)
155 err = dec.Decode(newEt2)
156 if err == nil {
157 t.Fatal("round 3: expected `bad type' error decoding ET2")
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)
173 dec := NewDecoder(b)
174 err = dec.Decode(e)
175 if shouldFail && err == nil {
176 t.Error("expected error for", msg)
178 if !shouldFail && err != nil {
179 t.Error("unexpected error for", msg, err)
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)
190 func corruptDataCheck(s string, err error, t *testing.T) {
191 b := bytes.NewBufferString(s)
192 dec := NewDecoder(b)
193 err1 := dec.Decode(new(ET2))
194 if err1 != err {
195 t.Errorf("from %q expected error %s; got %s", s, err, err1)
199 // Check that we survive bad data.
200 func TestBadData(t *testing.T) {
201 corruptDataCheck("", io.EOF, t)
202 corruptDataCheck("\x7Fhi", io.ErrUnexpectedEOF, t)
203 corruptDataCheck("\x03now is the time for all good men", errBadType, t)
204 // issue 6323.
205 corruptDataCheck("\x04\x24foo", errRange, t)
208 // Types not supported at top level by the Encoder.
209 var unsupportedValues = []interface{}{
210 make(chan int),
211 func(a int) bool { return true },
214 func TestUnsupported(t *testing.T) {
215 var b bytes.Buffer
216 enc := NewEncoder(&b)
217 for _, v := range unsupportedValues {
218 err := enc.Encode(v)
219 if err == nil {
220 t.Errorf("expected error for %T; got none", v)
225 func encAndDec(in, out interface{}) error {
226 b := new(bytes.Buffer)
227 enc := NewEncoder(b)
228 err := enc.Encode(in)
229 if err != nil {
230 return err
232 dec := NewDecoder(b)
233 err = dec.Decode(out)
234 if err != nil {
235 return err
237 return nil
240 func TestTypeToPtrType(t *testing.T) {
241 // Encode a T, decode a *T
242 type Type0 struct {
243 A int
245 t0 := Type0{7}
246 t0p := new(Type0)
247 if err := encAndDec(t0, t0p); err != nil {
248 t.Error(err)
252 func TestPtrTypeToType(t *testing.T) {
253 // Encode a *T, decode a T
254 type Type1 struct {
255 A uint
257 t1p := &Type1{17}
258 var t1 Type1
259 if err := encAndDec(t1, t1p); err != nil {
260 t.Error(err)
264 func TestTypeToPtrPtrPtrPtrType(t *testing.T) {
265 type Type2 struct {
266 A ****float64
268 t2 := Type2{}
269 t2.A = new(***float64)
270 *t2.A = new(**float64)
271 **t2.A = new(*float64)
272 ***t2.A = new(float64)
273 ****t2.A = 27.4
274 t2pppp := new(***Type2)
275 if err := encAndDec(t2, t2pppp); err != nil {
276 t.Fatal(err)
278 if ****(****t2pppp).A != ****t2.A {
279 t.Errorf("wrong value after decode: %g not %g", ****(****t2pppp).A, ****t2.A)
283 func TestSlice(t *testing.T) {
284 type Type3 struct {
285 A []string
287 t3p := &Type3{[]string{"hello", "world"}}
288 var t3 Type3
289 if err := encAndDec(t3, t3p); err != nil {
290 t.Error(err)
294 func TestValueError(t *testing.T) {
295 // Encode a *T, decode a T
296 type Type4 struct {
297 A int
299 t4p := &Type4{3}
300 var t4 Type4 // note: not a pointer.
301 if err := encAndDec(t4p, t4); err == nil || strings.Index(err.Error(), "pointer") < 0 {
302 t.Error("expected error about pointer; got", err)
306 func TestArray(t *testing.T) {
307 type Type5 struct {
308 A [3]string
309 B [3]byte
311 type Type6 struct {
312 A [2]string // can't hold t5.a
314 t5 := Type5{[3]string{"hello", ",", "world"}, [3]byte{1, 2, 3}}
315 var t5p Type5
316 if err := encAndDec(t5, &t5p); err != nil {
317 t.Error(err)
319 var t6 Type6
320 if err := encAndDec(t5, &t6); err == nil {
321 t.Error("should fail with mismatched array sizes")
325 func TestRecursiveMapType(t *testing.T) {
326 type recursiveMap map[string]recursiveMap
327 r1 := recursiveMap{"A": recursiveMap{"B": nil, "C": nil}, "D": nil}
328 r2 := make(recursiveMap)
329 if err := encAndDec(r1, &r2); err != nil {
330 t.Error(err)
334 func TestRecursiveSliceType(t *testing.T) {
335 type recursiveSlice []recursiveSlice
336 r1 := recursiveSlice{0: recursiveSlice{0: nil}, 1: nil}
337 r2 := make(recursiveSlice, 0)
338 if err := encAndDec(r1, &r2); err != nil {
339 t.Error(err)
343 // Regression test for bug: must send zero values inside arrays
344 func TestDefaultsInArray(t *testing.T) {
345 type Type7 struct {
346 B []bool
347 I []int
348 S []string
349 F []float64
351 t7 := Type7{
352 []bool{false, false, true},
353 []int{0, 0, 1},
354 []string{"hi", "", "there"},
355 []float64{0, 0, 1},
357 var t7p Type7
358 if err := encAndDec(t7, &t7p); err != nil {
359 t.Error(err)
363 var testInt int
364 var testFloat32 float32
365 var testString string
366 var testSlice []string
367 var testMap map[string]int
368 var testArray [7]int
370 type SingleTest struct {
371 in interface{}
372 out interface{}
373 err string
376 var singleTests = []SingleTest{
377 {17, &testInt, ""},
378 {float32(17.5), &testFloat32, ""},
379 {"bike shed", &testString, ""},
380 {[]string{"bike", "shed", "paint", "color"}, &testSlice, ""},
381 {map[string]int{"seven": 7, "twelve": 12}, &testMap, ""},
382 {[7]int{4, 55, 0, 0, 0, 0, 0}, &testArray, ""}, // case that once triggered a bug
383 {[7]int{4, 55, 1, 44, 22, 66, 1234}, &testArray, ""},
385 // Decode errors
386 {172, &testFloat32, "type"},
389 func TestSingletons(t *testing.T) {
390 b := new(bytes.Buffer)
391 enc := NewEncoder(b)
392 dec := NewDecoder(b)
393 for _, test := range singleTests {
394 b.Reset()
395 err := enc.Encode(test.in)
396 if err != nil {
397 t.Errorf("error encoding %v: %s", test.in, err)
398 continue
400 err = dec.Decode(test.out)
401 switch {
402 case err != nil && test.err == "":
403 t.Errorf("error decoding %v: %s", test.in, err)
404 continue
405 case err == nil && test.err != "":
406 t.Errorf("expected error decoding %v: %s", test.in, test.err)
407 continue
408 case err != nil && test.err != "":
409 if strings.Index(err.Error(), test.err) < 0 {
410 t.Errorf("wrong error decoding %v: wanted %s, got %v", test.in, test.err, err)
412 continue
414 // Get rid of the pointer in the rhs
415 val := reflect.ValueOf(test.out).Elem().Interface()
416 if !reflect.DeepEqual(test.in, val) {
417 t.Errorf("decoding singleton: expected %v got %v", test.in, val)
422 func TestStructNonStruct(t *testing.T) {
423 type Struct struct {
424 A string
426 type NonStruct string
427 s := Struct{"hello"}
428 var sp Struct
429 if err := encAndDec(s, &sp); err != nil {
430 t.Error(err)
432 var ns NonStruct
433 if err := encAndDec(s, &ns); err == nil {
434 t.Error("should get error for struct/non-struct")
435 } else if strings.Index(err.Error(), "type") < 0 {
436 t.Error("for struct/non-struct expected type error; got", err)
438 // Now try the other way
439 var nsp NonStruct
440 if err := encAndDec(ns, &nsp); err != nil {
441 t.Error(err)
443 if err := encAndDec(ns, &s); err == nil {
444 t.Error("should get error for non-struct/struct")
445 } else if strings.Index(err.Error(), "type") < 0 {
446 t.Error("for non-struct/struct expected type error; got", err)
450 type interfaceIndirectTestI interface {
451 F() bool
454 type interfaceIndirectTestT struct{}
456 func (this *interfaceIndirectTestT) F() bool {
457 return true
460 // A version of a bug reported on golang-nuts. Also tests top-level
461 // slice of interfaces. The issue was registering *T caused T to be
462 // stored as the concrete type.
463 func TestInterfaceIndirect(t *testing.T) {
464 Register(&interfaceIndirectTestT{})
465 b := new(bytes.Buffer)
466 w := []interfaceIndirectTestI{&interfaceIndirectTestT{}}
467 err := NewEncoder(b).Encode(w)
468 if err != nil {
469 t.Fatal("encode error:", err)
472 var r []interfaceIndirectTestI
473 err = NewDecoder(b).Decode(&r)
474 if err != nil {
475 t.Fatal("decode error:", err)
479 // Now follow various tests that decode into things that can't represent the
480 // encoded value, all of which should be legal.
482 // Also, when the ignored object contains an interface value, it may define
483 // types. Make sure that skipping the value still defines the types by using
484 // the encoder/decoder pair to send a value afterwards. If an interface
485 // is sent, its type in the test is always NewType0, so this checks that the
486 // encoder and decoder don't skew with respect to type definitions.
488 type Struct0 struct {
489 I interface{}
492 type NewType0 struct {
493 S string
496 type ignoreTest struct {
497 in, out interface{}
500 var ignoreTests = []ignoreTest{
501 // Decode normal struct into an empty struct
502 {&struct{ A int }{23}, &struct{}{}},
503 // Decode normal struct into a nil.
504 {&struct{ A int }{23}, nil},
505 // Decode singleton string into a nil.
506 {"hello, world", nil},
507 // Decode singleton slice into a nil.
508 {[]int{1, 2, 3, 4}, nil},
509 // Decode struct containing an interface into a nil.
510 {&Struct0{&NewType0{"value0"}}, nil},
511 // Decode singleton slice of interfaces into a nil.
512 {[]interface{}{"hi", &NewType0{"value1"}, 23}, nil},
515 func TestDecodeIntoNothing(t *testing.T) {
516 Register(new(NewType0))
517 for i, test := range ignoreTests {
518 b := new(bytes.Buffer)
519 enc := NewEncoder(b)
520 err := enc.Encode(test.in)
521 if err != nil {
522 t.Errorf("%d: encode error %s:", i, err)
523 continue
525 dec := NewDecoder(b)
526 err = dec.Decode(test.out)
527 if err != nil {
528 t.Errorf("%d: decode error: %s", i, err)
529 continue
531 // Now see if the encoder and decoder are in a consistent state.
532 str := fmt.Sprintf("Value %d", i)
533 err = enc.Encode(&NewType0{str})
534 if err != nil {
535 t.Fatalf("%d: NewType0 encode error: %s", i, err)
537 ns := new(NewType0)
538 err = dec.Decode(ns)
539 if err != nil {
540 t.Fatalf("%d: NewType0 decode error: %s", i, err)
542 if ns.S != str {
543 t.Fatalf("%d: expected %q got %q", i, str, ns.S)
548 // Another bug from golang-nuts, involving nested interfaces.
549 type Bug0Outer struct {
550 Bug0Field interface{}
553 type Bug0Inner struct {
554 A int
557 func TestNestedInterfaces(t *testing.T) {
558 var buf bytes.Buffer
559 e := NewEncoder(&buf)
560 d := NewDecoder(&buf)
561 Register(new(Bug0Outer))
562 Register(new(Bug0Inner))
563 f := &Bug0Outer{&Bug0Outer{&Bug0Inner{7}}}
564 var v interface{} = f
565 err := e.Encode(&v)
566 if err != nil {
567 t.Fatal("Encode:", err)
569 err = d.Decode(&v)
570 if err != nil {
571 t.Fatal("Decode:", err)
573 // Make sure it decoded correctly.
574 outer1, ok := v.(*Bug0Outer)
575 if !ok {
576 t.Fatalf("v not Bug0Outer: %T", v)
578 outer2, ok := outer1.Bug0Field.(*Bug0Outer)
579 if !ok {
580 t.Fatalf("v.Bug0Field not Bug0Outer: %T", outer1.Bug0Field)
582 inner, ok := outer2.Bug0Field.(*Bug0Inner)
583 if !ok {
584 t.Fatalf("v.Bug0Field.Bug0Field not Bug0Inner: %T", outer2.Bug0Field)
586 if inner.A != 7 {
587 t.Fatalf("final value %d; expected %d", inner.A, 7)
591 // The bugs keep coming. We forgot to send map subtypes before the map.
593 type Bug1Elem struct {
594 Name string
595 Id int
598 type Bug1StructMap map[string]Bug1Elem
600 func bug1EncDec(in Bug1StructMap, out *Bug1StructMap) error {
601 return nil
604 func TestMapBug1(t *testing.T) {
605 in := make(Bug1StructMap)
606 in["val1"] = Bug1Elem{"elem1", 1}
607 in["val2"] = Bug1Elem{"elem2", 2}
609 b := new(bytes.Buffer)
610 enc := NewEncoder(b)
611 err := enc.Encode(in)
612 if err != nil {
613 t.Fatal("encode:", err)
615 dec := NewDecoder(b)
616 out := make(Bug1StructMap)
617 err = dec.Decode(&out)
618 if err != nil {
619 t.Fatal("decode:", err)
621 if !reflect.DeepEqual(in, out) {
622 t.Errorf("mismatch: %v %v", in, out)
626 func TestGobMapInterfaceEncode(t *testing.T) {
627 m := map[string]interface{}{
628 "up": uintptr(0),
629 "i0": []int{-1},
630 "i1": []int8{-1},
631 "i2": []int16{-1},
632 "i3": []int32{-1},
633 "i4": []int64{-1},
634 "u0": []uint{1},
635 "u1": []uint8{1},
636 "u2": []uint16{1},
637 "u3": []uint32{1},
638 "u4": []uint64{1},
639 "f0": []float32{1},
640 "f1": []float64{1},
641 "c0": []complex64{complex(2, -2)},
642 "c1": []complex128{complex(2, float64(-2))},
643 "us": []uintptr{0},
644 "bo": []bool{false},
645 "st": []string{"s"},
647 enc := NewEncoder(new(bytes.Buffer))
648 err := enc.Encode(m)
649 if err != nil {
650 t.Errorf("encode map: %s", err)
654 func TestSliceReusesMemory(t *testing.T) {
655 buf := new(bytes.Buffer)
656 // Bytes
658 x := []byte("abcd")
659 enc := NewEncoder(buf)
660 err := enc.Encode(x)
661 if err != nil {
662 t.Errorf("bytes: encode: %s", err)
664 // Decode into y, which is big enough.
665 y := []byte("ABCDE")
666 addr := &y[0]
667 dec := NewDecoder(buf)
668 err = dec.Decode(&y)
669 if err != nil {
670 t.Fatal("bytes: decode:", err)
672 if !bytes.Equal(x, y) {
673 t.Errorf("bytes: expected %q got %q\n", x, y)
675 if addr != &y[0] {
676 t.Errorf("bytes: unnecessary reallocation")
679 // general slice
681 x := []rune("abcd")
682 enc := NewEncoder(buf)
683 err := enc.Encode(x)
684 if err != nil {
685 t.Errorf("ints: encode: %s", err)
687 // Decode into y, which is big enough.
688 y := []rune("ABCDE")
689 addr := &y[0]
690 dec := NewDecoder(buf)
691 err = dec.Decode(&y)
692 if err != nil {
693 t.Fatal("ints: decode:", err)
695 if !reflect.DeepEqual(x, y) {
696 t.Errorf("ints: expected %q got %q\n", x, y)
698 if addr != &y[0] {
699 t.Errorf("ints: unnecessary reallocation")
704 // Used to crash: negative count in recvMessage.
705 func TestBadCount(t *testing.T) {
706 b := []byte{0xfb, 0xa5, 0x82, 0x2f, 0xca, 0x1}
707 if err := NewDecoder(bytes.NewReader(b)).Decode(nil); err == nil {
708 t.Error("expected error from bad count")
709 } else if err.Error() != errBadCount.Error() {
710 t.Error("expected bad count error; got", err)
714 // Verify that sequential Decoders built on a single input will
715 // succeed if the input implements ReadByte and there is no
716 // type information in the stream.
717 func TestSequentialDecoder(t *testing.T) {
718 b := new(bytes.Buffer)
719 enc := NewEncoder(b)
720 const count = 10
721 for i := 0; i < count; i++ {
722 s := fmt.Sprintf("%d", i)
723 if err := enc.Encode(s); err != nil {
724 t.Error("encoder fail:", err)
727 for i := 0; i < count; i++ {
728 dec := NewDecoder(b)
729 var s string
730 if err := dec.Decode(&s); err != nil {
731 t.Fatal("decoder fail:", err)
733 if s != fmt.Sprintf("%d", i) {
734 t.Fatalf("decode expected %d got %s", i, s)
739 // Should be able to have unrepresentable fields (chan, func, *chan etc.); we just ignore them.
740 type Bug2 struct {
741 A int
742 C chan int
743 CP *chan int
744 F func()
745 FPP **func()
748 func TestChanFuncIgnored(t *testing.T) {
749 c := make(chan int)
750 f := func() {}
751 fp := &f
752 b0 := Bug2{23, c, &c, f, &fp}
753 var buf bytes.Buffer
754 enc := NewEncoder(&buf)
755 if err := enc.Encode(b0); err != nil {
756 t.Fatal("error encoding:", err)
758 var b1 Bug2
759 err := NewDecoder(&buf).Decode(&b1)
760 if err != nil {
761 t.Fatal("decode:", err)
763 if b1.A != b0.A {
764 t.Fatalf("got %d want %d", b1.A, b0.A)
766 if b1.C != nil || b1.CP != nil || b1.F != nil || b1.FPP != nil {
767 t.Fatal("unexpected value for chan or func")
771 func TestSliceIncompatibility(t *testing.T) {
772 var in = []byte{1, 2, 3}
773 var out []int
774 if err := encAndDec(in, &out); err == nil {
775 t.Error("expected compatibility error")
779 // Mutually recursive slices of structs caused problems.
780 type Bug3 struct {
781 Num int
782 Children []*Bug3
785 func TestGobPtrSlices(t *testing.T) {
786 in := []*Bug3{
787 {1, nil},
788 {2, nil},
790 b := new(bytes.Buffer)
791 err := NewEncoder(b).Encode(&in)
792 if err != nil {
793 t.Fatal("encode:", err)
796 var out []*Bug3
797 err = NewDecoder(b).Decode(&out)
798 if err != nil {
799 t.Fatal("decode:", err)
801 if !reflect.DeepEqual(in, out) {
802 t.Fatalf("got %v; wanted %v", out, in)
806 // getDecEnginePtr cached engine for ut.base instead of ut.user so we passed
807 // a *map and then tried to reuse its engine to decode the inner map.
808 func TestPtrToMapOfMap(t *testing.T) {
809 Register(make(map[string]interface{}))
810 subdata := make(map[string]interface{})
811 subdata["bar"] = "baz"
812 data := make(map[string]interface{})
813 data["foo"] = subdata
815 b := new(bytes.Buffer)
816 err := NewEncoder(b).Encode(data)
817 if err != nil {
818 t.Fatal("encode:", err)
820 var newData map[string]interface{}
821 err = NewDecoder(b).Decode(&newData)
822 if err != nil {
823 t.Fatal("decode:", err)
825 if !reflect.DeepEqual(data, newData) {
826 t.Fatalf("expected %v got %v", data, newData)
830 // A top-level nil pointer generates a panic with a helpful string-valued message.
831 func TestTopLevelNilPointer(t *testing.T) {
832 errMsg := topLevelNilPanic(t)
833 if errMsg == "" {
834 t.Fatal("top-level nil pointer did not panic")
836 if !strings.Contains(errMsg, "nil pointer") {
837 t.Fatal("expected nil pointer error, got:", errMsg)
841 func topLevelNilPanic(t *testing.T) (panicErr string) {
842 defer func() {
843 e := recover()
844 if err, ok := e.(string); ok {
845 panicErr = err
848 var ip *int
849 buf := new(bytes.Buffer)
850 if err := NewEncoder(buf).Encode(ip); err != nil {
851 t.Fatal("error in encode:", err)
853 return
856 func TestNilPointerInsideInterface(t *testing.T) {
857 var ip *int
858 si := struct {
859 I interface{}
861 I: ip,
863 buf := new(bytes.Buffer)
864 err := NewEncoder(buf).Encode(si)
865 if err == nil {
866 t.Fatal("expected error, got none")
868 errMsg := err.Error()
869 if !strings.Contains(errMsg, "nil pointer") || !strings.Contains(errMsg, "interface") {
870 t.Fatal("expected error about nil pointer and interface, got:", errMsg)
874 type Bug4Public struct {
875 Name string
876 Secret Bug4Secret
879 type Bug4Secret struct {
880 a int // error: no exported fields.
883 // Test that a failed compilation doesn't leave around an executable encoder.
884 // Issue 3273.
885 func TestMutipleEncodingsOfBadType(t *testing.T) {
886 x := Bug4Public{
887 Name: "name",
888 Secret: Bug4Secret{1},
890 buf := new(bytes.Buffer)
891 enc := NewEncoder(buf)
892 err := enc.Encode(x)
893 if err == nil {
894 t.Fatal("first encoding: expected error")
896 buf.Reset()
897 enc = NewEncoder(buf)
898 err = enc.Encode(x)
899 if err == nil {
900 t.Fatal("second encoding: expected error")
902 if !strings.Contains(err.Error(), "no exported fields") {
903 t.Errorf("expected error about no exported fields; got %v", err)
907 // There was an error check comparing the length of the input with the
908 // length of the slice being decoded. It was wrong because the next
909 // thing in the input might be a type definition, which would lead to
910 // an incorrect length check. This test reproduces the corner case.
912 type Z struct {
915 func Test29ElementSlice(t *testing.T) {
916 Register(Z{})
917 src := make([]interface{}, 100) // Size needs to be bigger than size of type definition.
918 for i := range src {
919 src[i] = Z{}
921 buf := new(bytes.Buffer)
922 err := NewEncoder(buf).Encode(src)
923 if err != nil {
924 t.Fatalf("encode: %v", err)
925 return
928 var dst []interface{}
929 err = NewDecoder(buf).Decode(&dst)
930 if err != nil {
931 t.Errorf("decode: %v", err)
932 return
936 // Don't crash, just give error when allocating a huge slice.
937 // Issue 8084.
938 func TestErrorForHugeSlice(t *testing.T) {
939 // Encode an int slice.
940 buf := new(bytes.Buffer)
941 slice := []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
942 err := NewEncoder(buf).Encode(slice)
943 if err != nil {
944 t.Fatal("encode:", err)
946 // Reach into the buffer and smash the count to make the encoded slice very long.
947 buf.Bytes()[buf.Len()-len(slice)-1] = 0xfa
948 // Decode and see error.
949 err = NewDecoder(buf).Decode(&slice)
950 if err == nil {
951 t.Fatal("decode: no error")
953 if !strings.Contains(err.Error(), "slice too big") {
954 t.Fatal("decode: expected slice too big error, got %s", err.Error())