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.
18 // Test basic operations in a safe manner.
19 func TestBasicEncoderDecoder(t
*testing
.T
) {
20 var values
= []interface{}{
35 complex64(1.2345 + 2.3456i
),
36 complex128(1.2345678 + 2.3456789i
),
40 for _
, value
:= range values
{
41 b
:= new(bytes
.Buffer
)
43 err
:= enc
.Encode(value
)
45 t
.Error("encoder fail:", err
)
48 result
:= reflect
.New(reflect
.TypeOf(value
))
49 err
= dec
.Decode(result
.Interface())
51 t
.Fatalf("error decoding %T: %v:", reflect
.TypeOf(value
), err
)
53 if !reflect
.DeepEqual(value
, result
.Elem().Interface()) {
54 t
.Fatalf("%T: expected %v got %v", value
, value
, result
.Elem().Interface())
59 func TestEncodeIntSlice(t
*testing
.T
) {
61 s8
:= []int8{1, 5, 12, 22, 35, 51, 70, 92, 117}
62 s16
:= []int16{145, 176, 210, 247, 287, 330, 376, 425, 477}
63 s32
:= []int32{532, 590, 651, 715, 782, 852, 925, 1001, 1080}
64 s64
:= []int64{1162, 1247, 1335, 1426, 1520, 1617, 1717, 1820, 1926}
66 t
.Run("int8", func(t
*testing
.T
) {
68 enc
:= NewEncoder(&sink
)
71 dec
:= NewDecoder(&sink
)
72 res
:= make([]int8, 9)
75 if !reflect
.DeepEqual(s8
, res
) {
76 t
.Fatalf("EncodeIntSlice: expected %v, got %v", s8
, res
)
80 t
.Run("int16", func(t
*testing
.T
) {
82 enc
:= NewEncoder(&sink
)
85 dec
:= NewDecoder(&sink
)
86 res
:= make([]int16, 9)
89 if !reflect
.DeepEqual(s16
, res
) {
90 t
.Fatalf("EncodeIntSlice: expected %v, got %v", s16
, res
)
94 t
.Run("int32", func(t
*testing
.T
) {
96 enc
:= NewEncoder(&sink
)
99 dec
:= NewDecoder(&sink
)
100 res
:= make([]int32, 9)
103 if !reflect
.DeepEqual(s32
, res
) {
104 t
.Fatalf("EncodeIntSlice: expected %v, got %v", s32
, res
)
108 t
.Run("int64", func(t
*testing
.T
) {
109 var sink bytes
.Buffer
110 enc
:= NewEncoder(&sink
)
113 dec
:= NewDecoder(&sink
)
114 res
:= make([]int64, 9)
117 if !reflect
.DeepEqual(s64
, res
) {
118 t
.Fatalf("EncodeIntSlice: expected %v, got %v", s64
, res
)
139 // Like ET1 but with a different name for a field
146 // Like ET1 but with a different type for a field
153 func TestEncoderDecoder(t
*testing
.T
) {
154 b
:= new(bytes
.Buffer
)
158 et0
.B
= "gobs of fun"
159 err
:= enc
.Encode(et0
)
161 t
.Error("encoder fail:", err
)
163 //fmt.Printf("% x %q\n", b, b)
167 err
= dec
.Decode(newEt0
)
169 t
.Fatal("error decoding ET0:", err
)
172 if !reflect
.DeepEqual(et0
, newEt0
) {
173 t
.Fatalf("invalid data for et0: expected %+v; got %+v", *et0
, *newEt0
)
176 t
.Error("not at eof;", b
.Len(), "bytes left")
180 b
= new(bytes
.Buffer
)
185 err
= enc
.Encode(et1
)
187 t
.Error("encoder fail:", err
)
191 err
= dec
.Decode(newEt1
)
193 t
.Fatal("error decoding ET1:", err
)
196 if !reflect
.DeepEqual(et1
, newEt1
) {
197 t
.Fatalf("invalid data for et1: expected %+v; got %+v", *et1
, *newEt1
)
200 t
.Error("not at eof;", b
.Len(), "bytes left")
205 err
= dec
.Decode(newEt1
)
207 t
.Fatal("round 2: error decoding ET1:", err
)
209 if !reflect
.DeepEqual(et1
, newEt1
) {
210 t
.Fatalf("round 2: invalid data for et1: expected %+v; got %+v", *et1
, *newEt1
)
213 t
.Error("round 2: not at eof;", b
.Len(), "bytes left")
216 // Now test with a running encoder/decoder pair that we recognize a type mismatch.
217 err
= enc
.Encode(et1
)
219 t
.Error("round 3: encoder fail:", err
)
222 err
= dec
.Decode(newEt2
)
224 t
.Fatal("round 3: expected `bad type' error decoding ET2")
228 // Run one value through the encoder/decoder, but use the wrong type.
229 // Input is always an ET1; we compare it to whatever is under 'e'.
230 func badTypeCheck(e
interface{}, shouldFail
bool, msg
string, t
*testing
.T
) {
231 b
:= new(bytes
.Buffer
)
236 err
:= enc
.Encode(et1
)
238 t
.Error("encoder fail:", err
)
242 if shouldFail
&& err
== nil {
243 t
.Error("expected error for", msg
)
245 if !shouldFail
&& err
!= nil {
246 t
.Error("unexpected error for", msg
, err
)
250 // Test that we recognize a bad type the first time.
251 func TestWrongTypeDecoder(t
*testing
.T
) {
252 badTypeCheck(new(ET2
), true, "no fields in common", t
)
253 badTypeCheck(new(ET3
), false, "different name of field", t
)
254 badTypeCheck(new(ET4
), true, "different type of field", t
)
257 // Types not supported at top level by the Encoder.
258 var unsupportedValues
= []interface{}{
260 func(a
int) bool { return true },
263 func TestUnsupported(t
*testing
.T
) {
265 enc
:= NewEncoder(&b
)
266 for _
, v
:= range unsupportedValues
{
269 t
.Errorf("expected error for %T; got none", v
)
274 func encAndDec(in
, out
interface{}) error
{
275 b
:= new(bytes
.Buffer
)
277 err
:= enc
.Encode(in
)
282 err
= dec
.Decode(out
)
289 func TestTypeToPtrType(t
*testing
.T
) {
290 // Encode a T, decode a *T
296 if err
:= encAndDec(t0
, t0p
); err
!= nil {
301 func TestPtrTypeToType(t
*testing
.T
) {
302 // Encode a *T, decode a T
308 if err
:= encAndDec(t1
, t1p
); err
!= nil {
313 func TestTypeToPtrPtrPtrPtrType(t
*testing
.T
) {
318 t2
.A
= new(***float64)
319 *t2
.A
= new(**float64)
320 **t2
.A
= new(*float64)
321 ***t2
.A
= new(float64)
323 t2pppp
:= new(***Type2
)
324 if err
:= encAndDec(t2
, t2pppp
); err
!= nil {
327 if ****(****t2pppp
).A
!= ****t2
.A
{
328 t
.Errorf("wrong value after decode: %g not %g", ****(****t2pppp
).A
, ****t2
.A
)
332 func TestSlice(t
*testing
.T
) {
336 t3p
:= &Type3
{[]string{"hello", "world"}}
338 if err
:= encAndDec(t3
, t3p
); err
!= nil {
343 func TestValueError(t
*testing
.T
) {
344 // Encode a *T, decode a T
349 var t4 Type4
// note: not a pointer.
350 if err
:= encAndDec(t4p
, t4
); err
== nil ||
!strings
.Contains(err
.Error(), "pointer") {
351 t
.Error("expected error about pointer; got", err
)
355 func TestArray(t
*testing
.T
) {
361 A
[2]string // can't hold t5.a
363 t5
:= Type5
{[3]string{"hello", ",", "world"}, [3]byte{1, 2, 3}}
365 if err
:= encAndDec(t5
, &t5p
); err
!= nil {
369 if err
:= encAndDec(t5
, &t6
); err
== nil {
370 t
.Error("should fail with mismatched array sizes")
374 func TestRecursiveMapType(t
*testing
.T
) {
375 type recursiveMap
map[string]recursiveMap
376 r1
:= recursiveMap
{"A": recursiveMap
{"B": nil, "C": nil}, "D": nil}
377 r2
:= make(recursiveMap
)
378 if err
:= encAndDec(r1
, &r2
); err
!= nil {
383 func TestRecursiveSliceType(t
*testing
.T
) {
384 type recursiveSlice
[]recursiveSlice
385 r1
:= recursiveSlice
{0: recursiveSlice
{0: nil}, 1: nil}
386 r2
:= make(recursiveSlice
, 0)
387 if err
:= encAndDec(r1
, &r2
); err
!= nil {
392 // Regression test for bug: must send zero values inside arrays
393 func TestDefaultsInArray(t
*testing
.T
) {
401 []bool{false, false, true},
403 []string{"hi", "", "there"},
407 if err
:= encAndDec(t7
, &t7p
); err
!= nil {
413 var testFloat32
float32
414 var testString
string
415 var testSlice
[]string
416 var testMap
map[string]int
419 type SingleTest
struct {
425 var singleTests
= []SingleTest
{
427 {float32(17.5), &testFloat32
, ""},
428 {"bike shed", &testString
, ""},
429 {[]string{"bike", "shed", "paint", "color"}, &testSlice
, ""},
430 {map[string]int{"seven": 7, "twelve": 12}, &testMap
, ""},
431 {[7]int{4, 55, 0, 0, 0, 0, 0}, &testArray
, ""}, // case that once triggered a bug
432 {[7]int{4, 55, 1, 44, 22, 66, 1234}, &testArray
, ""},
435 {172, &testFloat32
, "type"},
438 func TestSingletons(t
*testing
.T
) {
439 b
:= new(bytes
.Buffer
)
442 for _
, test
:= range singleTests
{
444 err
:= enc
.Encode(test
.in
)
446 t
.Errorf("error encoding %v: %s", test
.in
, err
)
449 err
= dec
.Decode(test
.out
)
451 case err
!= nil && test
.err
== "":
452 t
.Errorf("error decoding %v: %s", test
.in
, err
)
454 case err
== nil && test
.err
!= "":
455 t
.Errorf("expected error decoding %v: %s", test
.in
, test
.err
)
457 case err
!= nil && test
.err
!= "":
458 if !strings
.Contains(err
.Error(), test
.err
) {
459 t
.Errorf("wrong error decoding %v: wanted %s, got %v", test
.in
, test
.err
, err
)
463 // Get rid of the pointer in the rhs
464 val
:= reflect
.ValueOf(test
.out
).Elem().Interface()
465 if !reflect
.DeepEqual(test
.in
, val
) {
466 t
.Errorf("decoding singleton: expected %v got %v", test
.in
, val
)
471 func TestStructNonStruct(t
*testing
.T
) {
475 type NonStruct
string
478 if err
:= encAndDec(s
, &sp
); err
!= nil {
482 if err
:= encAndDec(s
, &ns
); err
== nil {
483 t
.Error("should get error for struct/non-struct")
484 } else if !strings
.Contains(err
.Error(), "type") {
485 t
.Error("for struct/non-struct expected type error; got", err
)
487 // Now try the other way
489 if err
:= encAndDec(ns
, &nsp
); err
!= nil {
492 if err
:= encAndDec(ns
, &s
); err
== nil {
493 t
.Error("should get error for non-struct/struct")
494 } else if !strings
.Contains(err
.Error(), "type") {
495 t
.Error("for non-struct/struct expected type error; got", err
)
499 type interfaceIndirectTestI
interface {
503 type interfaceIndirectTestT
struct{}
505 func (this
*interfaceIndirectTestT
) F() bool {
509 // A version of a bug reported on golang-nuts. Also tests top-level
510 // slice of interfaces. The issue was registering *T caused T to be
511 // stored as the concrete type.
512 func TestInterfaceIndirect(t
*testing
.T
) {
513 Register(&interfaceIndirectTestT
{})
514 b
:= new(bytes
.Buffer
)
515 w
:= []interfaceIndirectTestI
{&interfaceIndirectTestT
{}}
516 err
:= NewEncoder(b
).Encode(w
)
518 t
.Fatal("encode error:", err
)
521 var r
[]interfaceIndirectTestI
522 err
= NewDecoder(b
).Decode(&r
)
524 t
.Fatal("decode error:", err
)
528 // Now follow various tests that decode into things that can't represent the
529 // encoded value, all of which should be legal.
531 // Also, when the ignored object contains an interface value, it may define
532 // types. Make sure that skipping the value still defines the types by using
533 // the encoder/decoder pair to send a value afterwards. If an interface
534 // is sent, its type in the test is always NewType0, so this checks that the
535 // encoder and decoder don't skew with respect to type definitions.
537 type Struct0
struct {
541 type NewType0
struct {
545 type ignoreTest
struct {
549 var ignoreTests
= []ignoreTest
{
550 // Decode normal struct into an empty struct
551 {&struct{ A
int }{23}, &struct{}{}},
552 // Decode normal struct into a nil.
553 {&struct{ A
int }{23}, nil},
554 // Decode singleton string into a nil.
555 {"hello, world", nil},
556 // Decode singleton slice into a nil.
557 {[]int{1, 2, 3, 4}, nil},
558 // Decode struct containing an interface into a nil.
559 {&Struct0
{&NewType0
{"value0"}}, nil},
560 // Decode singleton slice of interfaces into a nil.
561 {[]interface{}{"hi", &NewType0
{"value1"}, 23}, nil},
564 func TestDecodeIntoNothing(t
*testing
.T
) {
565 Register(new(NewType0
))
566 for i
, test
:= range ignoreTests
{
567 b
:= new(bytes
.Buffer
)
569 err
:= enc
.Encode(test
.in
)
571 t
.Errorf("%d: encode error %s:", i
, err
)
575 err
= dec
.Decode(test
.out
)
577 t
.Errorf("%d: decode error: %s", i
, err
)
580 // Now see if the encoder and decoder are in a consistent state.
581 str
:= fmt
.Sprintf("Value %d", i
)
582 err
= enc
.Encode(&NewType0
{str
})
584 t
.Fatalf("%d: NewType0 encode error: %s", i
, err
)
589 t
.Fatalf("%d: NewType0 decode error: %s", i
, err
)
592 t
.Fatalf("%d: expected %q got %q", i
, str
, ns
.S
)
597 func TestIgnoreRecursiveType(t
*testing
.T
) {
598 // It's hard to build a self-contained test for this because
599 // we can't build compatible types in one package with
600 // different items so something is ignored. Here is
601 // some data that represents, according to debug.go:
603 // slice "recursiveSlice" id=106
607 0x1d, 0xff, 0xd3, 0x02, 0x01, 0x01, 0x0e, 0x72,
608 0x65, 0x63, 0x75, 0x72, 0x73, 0x69, 0x76, 0x65,
609 0x53, 0x6c, 0x69, 0x63, 0x65, 0x01, 0xff, 0xd4,
610 0x00, 0x01, 0xff, 0xd4, 0x00, 0x00, 0x07, 0xff,
611 0xd4, 0x00, 0x02, 0x01, 0x00, 0x00,
613 dec
:= NewDecoder(bytes
.NewReader(data
))
614 // Issue 10415: This caused infinite recursion.
615 err
:= dec
.Decode(nil)
621 // Another bug from golang-nuts, involving nested interfaces.
622 type Bug0Outer
struct {
623 Bug0Field
interface{}
626 type Bug0Inner
struct {
630 func TestNestedInterfaces(t
*testing
.T
) {
632 e
:= NewEncoder(&buf
)
633 d
:= NewDecoder(&buf
)
634 Register(new(Bug0Outer
))
635 Register(new(Bug0Inner
))
636 f
:= &Bug0Outer
{&Bug0Outer
{&Bug0Inner
{7}}}
637 var v
interface{} = f
640 t
.Fatal("Encode:", err
)
644 t
.Fatal("Decode:", err
)
646 // Make sure it decoded correctly.
647 outer1
, ok
:= v
.(*Bug0Outer
)
649 t
.Fatalf("v not Bug0Outer: %T", v
)
651 outer2
, ok
:= outer1
.Bug0Field
.(*Bug0Outer
)
653 t
.Fatalf("v.Bug0Field not Bug0Outer: %T", outer1
.Bug0Field
)
655 inner
, ok
:= outer2
.Bug0Field
.(*Bug0Inner
)
657 t
.Fatalf("v.Bug0Field.Bug0Field not Bug0Inner: %T", outer2
.Bug0Field
)
660 t
.Fatalf("final value %d; expected %d", inner
.A
, 7)
664 // The bugs keep coming. We forgot to send map subtypes before the map.
666 type Bug1Elem
struct {
671 type Bug1StructMap
map[string]Bug1Elem
673 func TestMapBug1(t
*testing
.T
) {
674 in
:= make(Bug1StructMap
)
675 in
["val1"] = Bug1Elem
{"elem1", 1}
676 in
["val2"] = Bug1Elem
{"elem2", 2}
678 b
:= new(bytes
.Buffer
)
680 err
:= enc
.Encode(in
)
682 t
.Fatal("encode:", err
)
685 out
:= make(Bug1StructMap
)
686 err
= dec
.Decode(&out
)
688 t
.Fatal("decode:", err
)
690 if !reflect
.DeepEqual(in
, out
) {
691 t
.Errorf("mismatch: %v %v", in
, out
)
695 func TestGobMapInterfaceEncode(t
*testing
.T
) {
696 m
:= map[string]interface{}{
710 "c0": []complex64
{complex(2, -2)},
711 "c1": []complex128
{complex(2, float64(-2))},
716 enc
:= NewEncoder(new(bytes
.Buffer
))
719 t
.Errorf("encode map: %s", err
)
723 func TestSliceReusesMemory(t
*testing
.T
) {
724 buf
:= new(bytes
.Buffer
)
728 enc
:= NewEncoder(buf
)
731 t
.Errorf("bytes: encode: %s", err
)
733 // Decode into y, which is big enough.
736 dec
:= NewDecoder(buf
)
739 t
.Fatal("bytes: decode:", err
)
741 if !bytes
.Equal(x
, y
) {
742 t
.Errorf("bytes: expected %q got %q\n", x
, y
)
745 t
.Errorf("bytes: unnecessary reallocation")
751 enc
:= NewEncoder(buf
)
754 t
.Errorf("ints: encode: %s", err
)
756 // Decode into y, which is big enough.
759 dec
:= NewDecoder(buf
)
762 t
.Fatal("ints: decode:", err
)
764 if !reflect
.DeepEqual(x
, y
) {
765 t
.Errorf("ints: expected %q got %q\n", x
, y
)
768 t
.Errorf("ints: unnecessary reallocation")
773 // Used to crash: negative count in recvMessage.
774 func TestBadCount(t
*testing
.T
) {
775 b
:= []byte{0xfb, 0xa5, 0x82, 0x2f, 0xca, 0x1}
776 if err
:= NewDecoder(bytes
.NewReader(b
)).Decode(nil); err
== nil {
777 t
.Error("expected error from bad count")
778 } else if err
.Error() != errBadCount
.Error() {
779 t
.Error("expected bad count error; got", err
)
783 // Verify that sequential Decoders built on a single input will
784 // succeed if the input implements ReadByte and there is no
785 // type information in the stream.
786 func TestSequentialDecoder(t
*testing
.T
) {
787 b
:= new(bytes
.Buffer
)
790 for i
:= 0; i
< count
; i
++ {
791 s
:= fmt
.Sprintf("%d", i
)
792 if err
:= enc
.Encode(s
); err
!= nil {
793 t
.Error("encoder fail:", err
)
796 for i
:= 0; i
< count
; i
++ {
799 if err
:= dec
.Decode(&s
); err
!= nil {
800 t
.Fatal("decoder fail:", err
)
802 if s
!= fmt
.Sprintf("%d", i
) {
803 t
.Fatalf("decode expected %d got %s", i
, s
)
808 // Should be able to have unrepresentable fields (chan, func, *chan etc.); we just ignore them.
817 func TestChanFuncIgnored(t
*testing
.T
) {
821 b0
:= Bug2
{23, c
, &c
, f
, &fp
}
823 enc
:= NewEncoder(&buf
)
824 if err
:= enc
.Encode(b0
); err
!= nil {
825 t
.Fatal("error encoding:", err
)
828 err
:= NewDecoder(&buf
).Decode(&b1
)
830 t
.Fatal("decode:", err
)
833 t
.Fatalf("got %d want %d", b1
.A
, b0
.A
)
835 if b1
.C
!= nil || b1
.CP
!= nil || b1
.F
!= nil || b1
.FPP
!= nil {
836 t
.Fatal("unexpected value for chan or func")
840 func TestSliceIncompatibility(t
*testing
.T
) {
841 var in
= []byte{1, 2, 3}
843 if err
:= encAndDec(in
, &out
); err
== nil {
844 t
.Error("expected compatibility error")
848 // Mutually recursive slices of structs caused problems.
854 func TestGobPtrSlices(t
*testing
.T
) {
859 b
:= new(bytes
.Buffer
)
860 err
:= NewEncoder(b
).Encode(&in
)
862 t
.Fatal("encode:", err
)
866 err
= NewDecoder(b
).Decode(&out
)
868 t
.Fatal("decode:", err
)
870 if !reflect
.DeepEqual(in
, out
) {
871 t
.Fatalf("got %v; wanted %v", out
, in
)
875 // getDecEnginePtr cached engine for ut.base instead of ut.user so we passed
876 // a *map and then tried to reuse its engine to decode the inner map.
877 func TestPtrToMapOfMap(t
*testing
.T
) {
878 Register(make(map[string]interface{}))
879 subdata
:= make(map[string]interface{})
880 subdata
["bar"] = "baz"
881 data
:= make(map[string]interface{})
882 data
["foo"] = subdata
884 b
:= new(bytes
.Buffer
)
885 err
:= NewEncoder(b
).Encode(data
)
887 t
.Fatal("encode:", err
)
889 var newData
map[string]interface{}
890 err
= NewDecoder(b
).Decode(&newData
)
892 t
.Fatal("decode:", err
)
894 if !reflect
.DeepEqual(data
, newData
) {
895 t
.Fatalf("expected %v got %v", data
, newData
)
899 // Test that untyped nils generate an error, not a panic.
901 func TestCatchInvalidNilValue(t
*testing
.T
) {
902 encodeErr
, panicErr
:= encodeAndRecover(nil)
904 t
.Fatalf("panicErr=%v, should not panic encoding untyped nil", panicErr
)
906 if encodeErr
== nil {
907 t
.Errorf("got err=nil, want non-nil error when encoding untyped nil value")
908 } else if !strings
.Contains(encodeErr
.Error(), "nil value") {
909 t
.Errorf("expected 'nil value' error; got err=%v", encodeErr
)
913 // A top-level nil pointer generates a panic with a helpful string-valued message.
914 func TestTopLevelNilPointer(t
*testing
.T
) {
916 encodeErr
, panicErr
:= encodeAndRecover(ip
)
917 if encodeErr
!= nil {
918 t
.Fatal("error in encode:", encodeErr
)
921 t
.Fatal("top-level nil pointer did not panic")
923 errMsg
:= panicErr
.Error()
924 if !strings
.Contains(errMsg
, "nil pointer") {
925 t
.Fatal("expected nil pointer error, got:", errMsg
)
929 func encodeAndRecover(value
interface{}) (encodeErr
, panicErr error
) {
933 switch err
:= e
.(type) {
937 panicErr
= fmt
.Errorf("%v", err
)
942 encodeErr
= NewEncoder(ioutil
.Discard
).Encode(value
)
946 func TestNilPointerPanics(t
*testing
.T
) {
949 intMap
= make(map[int]int)
951 nilIntMapPtr
*map[int]int
953 nilBoolChannel
chan bool
954 nilBoolChannelPtr
*chan bool
955 nilStringSlice
[]string
956 stringSlice
= make([]string, 1)
957 nilStringSlicePtr
*[]string
960 testCases
:= []struct {
964 {nilStringPtr
, true},
967 {nilIntMapPtr
, true},
969 {nilStringSlice
, false},
970 {stringSlice
, false},
971 {nilStringSlicePtr
, true},
972 {nilBoolChannel
, false},
973 {nilBoolChannelPtr
, true},
976 for _
, tt
:= range testCases
{
977 _
, panicErr
:= encodeAndRecover(tt
.value
)
980 t
.Errorf("expected panic with input %#v, did not panic", tt
.value
)
985 t
.Fatalf("expected no panic with input %#v, got panic=%v", tt
.value
, panicErr
)
990 func TestNilPointerInsideInterface(t
*testing
.T
) {
997 buf
:= new(bytes
.Buffer
)
998 err
:= NewEncoder(buf
).Encode(si
)
1000 t
.Fatal("expected error, got none")
1002 errMsg
:= err
.Error()
1003 if !strings
.Contains(errMsg
, "nil pointer") ||
!strings
.Contains(errMsg
, "interface") {
1004 t
.Fatal("expected error about nil pointer and interface, got:", errMsg
)
1008 type Bug4Public
struct {
1013 type Bug4Secret
struct {
1014 a
int // error: no exported fields.
1017 // Test that a failed compilation doesn't leave around an executable encoder.
1019 func TestMutipleEncodingsOfBadType(t
*testing
.T
) {
1022 Secret
: Bug4Secret
{1},
1024 buf
:= new(bytes
.Buffer
)
1025 enc
:= NewEncoder(buf
)
1026 err
:= enc
.Encode(x
)
1028 t
.Fatal("first encoding: expected error")
1031 enc
= NewEncoder(buf
)
1034 t
.Fatal("second encoding: expected error")
1036 if !strings
.Contains(err
.Error(), "no exported fields") {
1037 t
.Errorf("expected error about no exported fields; got %v", err
)
1041 // There was an error check comparing the length of the input with the
1042 // length of the slice being decoded. It was wrong because the next
1043 // thing in the input might be a type definition, which would lead to
1044 // an incorrect length check. This test reproduces the corner case.
1049 func Test29ElementSlice(t
*testing
.T
) {
1051 src
:= make([]interface{}, 100) // Size needs to be bigger than size of type definition.
1052 for i
:= range src
{
1055 buf
:= new(bytes
.Buffer
)
1056 err
:= NewEncoder(buf
).Encode(src
)
1058 t
.Fatalf("encode: %v", err
)
1062 var dst
[]interface{}
1063 err
= NewDecoder(buf
).Decode(&dst
)
1065 t
.Errorf("decode: %v", err
)
1070 // Don't crash, just give error when allocating a huge slice.
1072 func TestErrorForHugeSlice(t
*testing
.T
) {
1073 // Encode an int slice.
1074 buf
:= new(bytes
.Buffer
)
1075 slice
:= []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
1076 err
:= NewEncoder(buf
).Encode(slice
)
1078 t
.Fatal("encode:", err
)
1080 // Reach into the buffer and smash the count to make the encoded slice very long.
1081 buf
.Bytes()[buf
.Len()-len(slice
)-1] = 0xfa
1082 // Decode and see error.
1083 err
= NewDecoder(buf
).Decode(&slice
)
1085 t
.Fatal("decode: no error")
1087 if !strings
.Contains(err
.Error(), "slice too big") {
1088 t
.Fatalf("decode: expected slice too big error, got %s", err
.Error())
1092 type badDataTest
struct {
1093 input
string // The input encoded as a hex string.
1094 error
string // A substring of the error that should result.
1095 data
interface{} // What to decode into.
1098 var badDataTests
= []badDataTest
{
1100 {"7F6869", "unexpected EOF", nil},
1101 {"036e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e", "unknown type id", new(ET2
)},
1102 {"0424666f6f", "field numbers out of bounds", new(ET2
)}, // Issue 6323.
1103 {"05100028557b02027f8302", "interface encoding", nil}, // Issue 10270.
1105 {"130a00fb5dad0bf8ff020263e70002fa28020202a89859", "slice length too large", nil},
1106 {"0f1000fb285d003316020735ff023a65c5", "interface encoding", nil},
1107 {"03fffb0616fffc00f902ff02ff03bf005d02885802a311a8120228022c028ee7", "GobDecoder", nil},
1109 {"10fe010f020102fe01100001fe010e000016fe010d030102fe010e00010101015801fe01100000000bfe011000f85555555555555555", "exceeds input size", nil},
1112 // TestBadData tests that various problems caused by malformed input
1113 // are caught as errors and do not cause panics.
1114 func TestBadData(t
*testing
.T
) {
1115 for i
, test
:= range badDataTests
{
1116 data
, err
:= hex
.DecodeString(test
.input
)
1118 t
.Fatalf("#%d: hex error: %s", i
, err
)
1120 d
:= NewDecoder(bytes
.NewReader(data
))
1121 err
= d
.Decode(test
.data
)
1123 t
.Errorf("decode: no error")
1126 if !strings
.Contains(err
.Error(), test
.error
) {
1127 t
.Errorf("#%d: decode: expected %q error, got %s", i
, test
.error
, err
.Error())
1132 // TestHugeWriteFails tests that enormous messages trigger an error.
1133 func TestHugeWriteFails(t
*testing
.T
) {
1134 if runtime
.GOARCH
== "wasm" {
1135 t
.Skip("out of memory on wasm")
1137 if testing
.Short() {
1138 // Requires allocating a monster, so don't do this from all.bash.
1139 t
.Skip("skipping huge allocation in short mode")
1141 huge
:= make([]byte, tooBig
)
1142 huge
[0] = 7 // Make sure it's not all zeros.
1143 buf
:= new(bytes
.Buffer
)
1144 err
:= NewEncoder(buf
).Encode(huge
)
1146 t
.Fatalf("expected error for huge slice")
1148 if !strings
.Contains(err
.Error(), "message too big") {
1149 t
.Fatalf("expected 'too big' error; got %s\n", err
.Error())