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.
16 // Test basic operations in a safe manner.
17 func TestBasicEncoderDecoder(t
*testing
.T
) {
18 var values
= []interface{}{
33 complex64(1.2345 + 2.3456i
),
34 complex128(1.2345678 + 2.3456789i
),
38 for _
, value
:= range values
{
39 b
:= new(bytes
.Buffer
)
41 err
:= enc
.Encode(value
)
43 t
.Error("encoder fail:", err
)
46 result
:= reflect
.New(reflect
.TypeOf(value
))
47 err
= dec
.Decode(result
.Interface())
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())
72 // Like ET1 but with a different name for a field
79 // Like ET1 but with a different type for a field
86 func TestEncoderDecoder(t
*testing
.T
) {
87 b
:= new(bytes
.Buffer
)
92 err
:= enc
.Encode(et0
)
94 t
.Error("encoder fail:", err
)
96 //fmt.Printf("% x %q\n", b, b)
100 err
= dec
.Decode(newEt0
)
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
)
109 t
.Error("not at eof;", b
.Len(), "bytes left")
113 b
= new(bytes
.Buffer
)
118 err
= enc
.Encode(et1
)
120 t
.Error("encoder fail:", err
)
124 err
= dec
.Decode(newEt1
)
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
)
133 t
.Error("not at eof;", b
.Len(), "bytes left")
138 err
= dec
.Decode(newEt1
)
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
)
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
)
152 t
.Error("round 3: encoder fail:", err
)
155 err
= dec
.Decode(newEt2
)
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
)
169 err
:= enc
.Encode(et1
)
171 t
.Error("encoder fail:", err
)
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
)
193 err1
:= dec
.Decode(new(ET2
))
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
)
205 corruptDataCheck("\x04\x24foo", errRange
, t
)
208 // Types not supported at top level by the Encoder.
209 var unsupportedValues
= []interface{}{
211 func(a
int) bool { return true },
214 func TestUnsupported(t
*testing
.T
) {
216 enc
:= NewEncoder(&b
)
217 for _
, v
:= range unsupportedValues
{
220 t
.Errorf("expected error for %T; got none", v
)
225 func encAndDec(in
, out
interface{}) error
{
226 b
:= new(bytes
.Buffer
)
228 err
:= enc
.Encode(in
)
233 err
= dec
.Decode(out
)
240 func TestTypeToPtrType(t
*testing
.T
) {
241 // Encode a T, decode a *T
247 if err
:= encAndDec(t0
, t0p
); err
!= nil {
252 func TestPtrTypeToType(t
*testing
.T
) {
253 // Encode a *T, decode a T
259 if err
:= encAndDec(t1
, t1p
); err
!= nil {
264 func TestTypeToPtrPtrPtrPtrType(t
*testing
.T
) {
269 t2
.A
= new(***float64)
270 *t2
.A
= new(**float64)
271 **t2
.A
= new(*float64)
272 ***t2
.A
= new(float64)
274 t2pppp
:= new(***Type2
)
275 if err
:= encAndDec(t2
, t2pppp
); err
!= nil {
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
) {
287 t3p
:= &Type3
{[]string{"hello", "world"}}
289 if err
:= encAndDec(t3
, t3p
); err
!= nil {
294 func TestValueError(t
*testing
.T
) {
295 // Encode a *T, decode a T
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
) {
312 A
[2]string // can't hold t5.a
314 t5
:= Type5
{[3]string{"hello", ",", "world"}, [3]byte{1, 2, 3}}
316 if err
:= encAndDec(t5
, &t5p
); err
!= nil {
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 {
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 {
343 // Regression test for bug: must send zero values inside arrays
344 func TestDefaultsInArray(t
*testing
.T
) {
352 []bool{false, false, true},
354 []string{"hi", "", "there"},
358 if err
:= encAndDec(t7
, &t7p
); err
!= nil {
364 var testFloat32
float32
365 var testString
string
366 var testSlice
[]string
367 var testMap
map[string]int
370 type SingleTest
struct {
376 var singleTests
= []SingleTest
{
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
, ""},
386 {172, &testFloat32
, "type"},
389 func TestSingletons(t
*testing
.T
) {
390 b
:= new(bytes
.Buffer
)
393 for _
, test
:= range singleTests
{
395 err
:= enc
.Encode(test
.in
)
397 t
.Errorf("error encoding %v: %s", test
.in
, err
)
400 err
= dec
.Decode(test
.out
)
402 case err
!= nil && test
.err
== "":
403 t
.Errorf("error decoding %v: %s", test
.in
, err
)
405 case err
== nil && test
.err
!= "":
406 t
.Errorf("expected error decoding %v: %s", test
.in
, test
.err
)
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
)
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
) {
426 type NonStruct
string
429 if err
:= encAndDec(s
, &sp
); err
!= nil {
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
440 if err
:= encAndDec(ns
, &nsp
); err
!= nil {
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 {
454 type interfaceIndirectTestT
struct{}
456 func (this
*interfaceIndirectTestT
) F() bool {
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
)
469 t
.Fatal("encode error:", err
)
472 var r
[]interfaceIndirectTestI
473 err
= NewDecoder(b
).Decode(&r
)
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 {
492 type NewType0
struct {
496 type ignoreTest
struct {
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
)
520 err
:= enc
.Encode(test
.in
)
522 t
.Errorf("%d: encode error %s:", i
, err
)
526 err
= dec
.Decode(test
.out
)
528 t
.Errorf("%d: decode error: %s", i
, err
)
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
})
535 t
.Fatalf("%d: NewType0 encode error: %s", i
, err
)
540 t
.Fatalf("%d: NewType0 decode error: %s", i
, err
)
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 {
557 func TestNestedInterfaces(t
*testing
.T
) {
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
567 t
.Fatal("Encode:", err
)
571 t
.Fatal("Decode:", err
)
573 // Make sure it decoded correctly.
574 outer1
, ok
:= v
.(*Bug0Outer
)
576 t
.Fatalf("v not Bug0Outer: %T", v
)
578 outer2
, ok
:= outer1
.Bug0Field
.(*Bug0Outer
)
580 t
.Fatalf("v.Bug0Field not Bug0Outer: %T", outer1
.Bug0Field
)
582 inner
, ok
:= outer2
.Bug0Field
.(*Bug0Inner
)
584 t
.Fatalf("v.Bug0Field.Bug0Field not Bug0Inner: %T", outer2
.Bug0Field
)
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 {
598 type Bug1StructMap
map[string]Bug1Elem
600 func bug1EncDec(in Bug1StructMap
, out
*Bug1StructMap
) error
{
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
)
611 err
:= enc
.Encode(in
)
613 t
.Fatal("encode:", err
)
616 out
:= make(Bug1StructMap
)
617 err
= dec
.Decode(&out
)
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{}{
641 "c0": []complex64
{complex(2, -2)},
642 "c1": []complex128
{complex(2, float64(-2))},
647 enc
:= NewEncoder(new(bytes
.Buffer
))
650 t
.Errorf("encode map: %s", err
)
654 func TestSliceReusesMemory(t
*testing
.T
) {
655 buf
:= new(bytes
.Buffer
)
659 enc
:= NewEncoder(buf
)
662 t
.Errorf("bytes: encode: %s", err
)
664 // Decode into y, which is big enough.
667 dec
:= NewDecoder(buf
)
670 t
.Fatal("bytes: decode:", err
)
672 if !bytes
.Equal(x
, y
) {
673 t
.Errorf("bytes: expected %q got %q\n", x
, y
)
676 t
.Errorf("bytes: unnecessary reallocation")
682 enc
:= NewEncoder(buf
)
685 t
.Errorf("ints: encode: %s", err
)
687 // Decode into y, which is big enough.
690 dec
:= NewDecoder(buf
)
693 t
.Fatal("ints: decode:", err
)
695 if !reflect
.DeepEqual(x
, y
) {
696 t
.Errorf("ints: expected %q got %q\n", x
, y
)
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
)
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
++ {
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.
748 func TestChanFuncIgnored(t
*testing
.T
) {
752 b0
:= Bug2
{23, c
, &c
, f
, &fp
}
754 enc
:= NewEncoder(&buf
)
755 if err
:= enc
.Encode(b0
); err
!= nil {
756 t
.Fatal("error encoding:", err
)
759 err
:= NewDecoder(&buf
).Decode(&b1
)
761 t
.Fatal("decode:", err
)
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}
774 if err
:= encAndDec(in
, &out
); err
== nil {
775 t
.Error("expected compatibility error")
779 // Mutually recursive slices of structs caused problems.
785 func TestGobPtrSlices(t
*testing
.T
) {
790 b
:= new(bytes
.Buffer
)
791 err
:= NewEncoder(b
).Encode(&in
)
793 t
.Fatal("encode:", err
)
797 err
= NewDecoder(b
).Decode(&out
)
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
)
818 t
.Fatal("encode:", err
)
820 var newData
map[string]interface{}
821 err
= NewDecoder(b
).Decode(&newData
)
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
)
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) {
844 if err
, ok
:= e
.(string); ok
{
849 buf
:= new(bytes
.Buffer
)
850 if err
:= NewEncoder(buf
).Encode(ip
); err
!= nil {
851 t
.Fatal("error in encode:", err
)
856 func TestNilPointerInsideInterface(t
*testing
.T
) {
863 buf
:= new(bytes
.Buffer
)
864 err
:= NewEncoder(buf
).Encode(si
)
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 {
879 type Bug4Secret
struct {
880 a
int // error: no exported fields.
883 // Test that a failed compilation doesn't leave around an executable encoder.
885 func TestMutipleEncodingsOfBadType(t
*testing
.T
) {
888 Secret
: Bug4Secret
{1},
890 buf
:= new(bytes
.Buffer
)
891 enc
:= NewEncoder(buf
)
894 t
.Fatal("first encoding: expected error")
897 enc
= NewEncoder(buf
)
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.
915 func Test29ElementSlice(t
*testing
.T
) {
917 src
:= make([]interface{}, 100) // Size needs to be bigger than size of type definition.
921 buf
:= new(bytes
.Buffer
)
922 err
:= NewEncoder(buf
).Encode(src
)
924 t
.Fatalf("encode: %v", err
)
928 var dst
[]interface{}
929 err
= NewDecoder(buf
).Decode(&dst
)
931 t
.Errorf("decode: %v", err
)
936 // Don't crash, just give error when allocating a huge slice.
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
)
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
)
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())