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.
26 // Like ET1 but with a different name for a field
33 // Like ET1 but with a different type for a field
40 func TestEncoderDecoder(t *testing.T) {
41 b := new(bytes.Buffer)
46 err := enc.Encode(et1)
48 t.Error("encoder fail:", err)
52 err = dec.Decode(newEt1)
54 t.Fatal("error decoding ET1:", err)
57 if !reflect.DeepEqual(et1, newEt1) {
58 t.Fatalf("invalid data for et1: expected %+v; got %+v", *et1, *newEt1)
61 t.Error("not at eof;", b.Len(), "bytes left")
66 err = dec.Decode(newEt1)
68 t.Fatal("round 2: error decoding ET1:", err)
70 if !reflect.DeepEqual(et1, newEt1) {
71 t.Fatalf("round 2: invalid data for et1: expected %+v; got %+v", *et1, *newEt1)
74 t.Error("round 2: not at eof;", b.Len(), "bytes left")
77 // Now test with a running encoder/decoder pair that we recognize a type mismatch.
80 t.Error("round 3: encoder fail:", err)
83 err = dec.Decode(newEt2)
85 t.Fatal("round 3: expected `bad type' error decoding ET2")
89 // Run one value through the encoder/decoder, but use the wrong type.
90 // Input is always an ET1; we compare it to whatever is under 'e'.
91 func badTypeCheck(e interface{}, shouldFail bool, msg string, t *testing.T) {
92 b := new(bytes.Buffer)
97 err := enc.Encode(et1)
99 t.Error("encoder fail:", err)
103 if shouldFail && err == nil {
104 t.Error("expected error for", msg)
106 if !shouldFail && err != nil {
107 t.Error("unexpected error for", msg, err)
111 // Test that we recognize a bad type the first time.
112 func TestWrongTypeDecoder(t *testing.T) {
113 badTypeCheck(new(ET2), true, "no fields in common", t)
114 badTypeCheck(new(ET3), false, "different name of field", t)
115 badTypeCheck(new(ET4), true, "different type of field", t)
118 func corruptDataCheck(s string, err error, t *testing.T) {
119 b := bytes.NewBufferString(s)
121 err1 := dec.Decode(new(ET2))
123 t.Errorf("from %q expected error %s; got %s", s, err, err1)
127 // Check that we survive bad data.
128 func TestBadData(t *testing.T) {
129 corruptDataCheck("", io.EOF, t)
130 corruptDataCheck("\x7Fhi", io.ErrUnexpectedEOF, t)
131 corruptDataCheck("\x03now is the time for all good men", errBadType, t)
134 // Types not supported by the Encoder.
135 var unsupportedValues = []interface{}{
137 func(a int) bool { return true },
140 func TestUnsupported(t *testing.T) {
142 enc := NewEncoder(&b)
143 for _, v := range unsupportedValues {
146 t.Errorf("expected error for %T; got none", v)
151 func encAndDec(in, out interface{}) error {
152 b := new(bytes.Buffer)
154 err := enc.Encode(in)
159 err = dec.Decode(out)
166 func TestTypeToPtrType(t *testing.T) {
167 // Encode a T, decode a *T
173 if err := encAndDec(t0, t0p); err != nil {
178 func TestPtrTypeToType(t *testing.T) {
179 // Encode a *T, decode a T
185 if err := encAndDec(t1, t1p); err != nil {
190 func TestTypeToPtrPtrPtrPtrType(t *testing.T) {
195 t2.A = new(***float64)
196 *t2.A = new(**float64)
197 **t2.A = new(*float64)
198 ***t2.A = new(float64)
200 t2pppp := new(***Type2)
201 if err := encAndDec(t2, t2pppp); err != nil {
204 if ****(****t2pppp).A != ****t2.A {
205 t.Errorf("wrong value after decode: %g not %g", ****(****t2pppp).A, ****t2.A)
209 func TestSlice(t *testing.T) {
213 t3p := &Type3{[]string{"hello", "world"}}
215 if err := encAndDec(t3, t3p); err != nil {
220 func TestValueError(t *testing.T) {
221 // Encode a *T, decode a T
226 var t4 Type4 // note: not a pointer.
227 if err := encAndDec(t4p, t4); err == nil || strings.Index(err.Error(), "pointer") < 0 {
228 t.Error("expected error about pointer; got", err)
232 func TestArray(t *testing.T) {
238 A [2]string // can't hold t5.a
240 t5 := Type5{[3]string{"hello", ",", "world"}, [3]byte{1, 2, 3}}
242 if err := encAndDec(t5, &t5p); err != nil {
246 if err := encAndDec(t5, &t6); err == nil {
247 t.Error("should fail with mismatched array sizes")
251 func TestRecursiveMapType(t *testing.T) {
252 type recursiveMap map[string]recursiveMap
253 r1 := recursiveMap{"A": recursiveMap{"B": nil, "C": nil}, "D": nil}
254 r2 := make(recursiveMap)
255 if err := encAndDec(r1, &r2); err != nil {
260 func TestRecursiveSliceType(t *testing.T) {
261 type recursiveSlice []recursiveSlice
262 r1 := recursiveSlice{0: recursiveSlice{0: nil}, 1: nil}
263 r2 := make(recursiveSlice, 0)
264 if err := encAndDec(r1, &r2); err != nil {
269 // Regression test for bug: must send zero values inside arrays
270 func TestDefaultsInArray(t *testing.T) {
278 []bool{false, false, true},
280 []string{"hi", "", "there"},
284 if err := encAndDec(t7, &t7p); err != nil {
290 var testFloat32 float32
291 var testString string
292 var testSlice []string
293 var testMap map[string]int
296 type SingleTest struct {
302 var singleTests = []SingleTest{
304 {float32(17.5), &testFloat32, ""},
305 {"bike shed", &testString, ""},
306 {[]string{"bike", "shed", "paint", "color"}, &testSlice, ""},
307 {map[string]int{"seven": 7, "twelve": 12}, &testMap, ""},
308 {[7]int{4, 55, 0, 0, 0, 0, 0}, &testArray, ""}, // case that once triggered a bug
309 {[7]int{4, 55, 1, 44, 22, 66, 1234}, &testArray, ""},
312 {172, &testFloat32, "type"},
315 func TestSingletons(t *testing.T) {
316 b := new(bytes.Buffer)
319 for _, test := range singleTests {
321 err := enc.Encode(test.in)
323 t.Errorf("error encoding %v: %s", test.in, err)
326 err = dec.Decode(test.out)
328 case err != nil && test.err == "":
329 t.Errorf("error decoding %v: %s", test.in, err)
331 case err == nil && test.err != "":
332 t.Errorf("expected error decoding %v: %s", test.in, test.err)
334 case err != nil && test.err != "":
335 if strings.Index(err.Error(), test.err) < 0 {
336 t.Errorf("wrong error decoding %v: wanted %s, got %v", test.in, test.err, err)
340 // Get rid of the pointer in the rhs
341 val := reflect.ValueOf(test.out).Elem().Interface()
342 if !reflect.DeepEqual(test.in, val) {
343 t.Errorf("decoding singleton: expected %v got %v", test.in, val)
348 func TestStructNonStruct(t *testing.T) {
352 type NonStruct string
355 if err := encAndDec(s, &sp); err != nil {
359 if err := encAndDec(s, &ns); err == nil {
360 t.Error("should get error for struct/non-struct")
361 } else if strings.Index(err.Error(), "type") < 0 {
362 t.Error("for struct/non-struct expected type error; got", err)
364 // Now try the other way
366 if err := encAndDec(ns, &nsp); err != nil {
369 if err := encAndDec(ns, &s); err == nil {
370 t.Error("should get error for non-struct/struct")
371 } else if strings.Index(err.Error(), "type") < 0 {
372 t.Error("for non-struct/struct expected type error; got", err)
376 type interfaceIndirectTestI interface {
380 type interfaceIndirectTestT struct{}
382 func (this *interfaceIndirectTestT) F() bool {
386 // A version of a bug reported on golang-nuts. Also tests top-level
387 // slice of interfaces. The issue was registering *T caused T to be
388 // stored as the concrete type.
389 func TestInterfaceIndirect(t *testing.T) {
390 Register(&interfaceIndirectTestT{})
391 b := new(bytes.Buffer)
392 w := []interfaceIndirectTestI{&interfaceIndirectTestT{}}
393 err := NewEncoder(b).Encode(w)
395 t.Fatal("encode error:", err)
398 var r []interfaceIndirectTestI
399 err = NewDecoder(b).Decode(&r)
401 t.Fatal("decode error:", err)
405 // Now follow various tests that decode into things that can't represent the
406 // encoded value, all of which should be legal.
408 // Also, when the ignored object contains an interface value, it may define
409 // types. Make sure that skipping the value still defines the types by using
410 // the encoder/decoder pair to send a value afterwards. If an interface
411 // is sent, its type in the test is always NewType0, so this checks that the
412 // encoder and decoder don't skew with respect to type definitions.
414 type Struct0 struct {
418 type NewType0 struct {
422 type ignoreTest struct {
426 var ignoreTests = []ignoreTest{
427 // Decode normal struct into an empty struct
428 {&struct{ A int }{23}, &struct{}{}},
429 // Decode normal struct into a nil.
430 {&struct{ A int }{23}, nil},
431 // Decode singleton string into a nil.
432 {"hello, world", nil},
433 // Decode singleton slice into a nil.
434 {[]int{1, 2, 3, 4}, nil},
435 // Decode struct containing an interface into a nil.
436 {&Struct0{&NewType0{"value0"}}, nil},
437 // Decode singleton slice of interfaces into a nil.
438 {[]interface{}{"hi", &NewType0{"value1"}, 23}, nil},
441 func TestDecodeIntoNothing(t *testing.T) {
442 Register(new(NewType0))
443 for i, test := range ignoreTests {
444 b := new(bytes.Buffer)
446 err := enc.Encode(test.in)
448 t.Errorf("%d: encode error %s:", i, err)
452 err = dec.Decode(test.out)
454 t.Errorf("%d: decode error: %s", i, err)
457 // Now see if the encoder and decoder are in a consistent state.
458 str := fmt.Sprintf("Value %d", i)
459 err = enc.Encode(&NewType0{str})
461 t.Fatalf("%d: NewType0 encode error: %s", i, err)
466 t.Fatalf("%d: NewType0 decode error: %s", i, err)
469 t.Fatalf("%d: expected %q got %q", i, str, ns.S)
474 // Another bug from golang-nuts, involving nested interfaces.
475 type Bug0Outer struct {
476 Bug0Field interface{}
479 type Bug0Inner struct {
483 func TestNestedInterfaces(t *testing.T) {
485 e := NewEncoder(&buf)
486 d := NewDecoder(&buf)
487 Register(new(Bug0Outer))
488 Register(new(Bug0Inner))
489 f := &Bug0Outer{&Bug0Outer{&Bug0Inner{7}}}
490 var v interface{} = f
493 t.Fatal("Encode:", err)
497 t.Fatal("Decode:", err)
499 // Make sure it decoded correctly.
500 outer1, ok := v.(*Bug0Outer)
502 t.Fatalf("v not Bug0Outer: %T", v)
504 outer2, ok := outer1.Bug0Field.(*Bug0Outer)
506 t.Fatalf("v.Bug0Field not Bug0Outer: %T", outer1.Bug0Field)
508 inner, ok := outer2.Bug0Field.(*Bug0Inner)
510 t.Fatalf("v.Bug0Field.Bug0Field not Bug0Inner: %T", outer2.Bug0Field)
513 t.Fatalf("final value %d; expected %d", inner.A, 7)
517 // The bugs keep coming. We forgot to send map subtypes before the map.
519 type Bug1Elem struct {
524 type Bug1StructMap map[string]Bug1Elem
526 func bug1EncDec(in Bug1StructMap, out *Bug1StructMap) error {
530 func TestMapBug1(t *testing.T) {
531 in := make(Bug1StructMap)
532 in["val1"] = Bug1Elem{"elem1", 1}
533 in["val2"] = Bug1Elem{"elem2", 2}
535 b := new(bytes.Buffer)
537 err := enc.Encode(in)
539 t.Fatal("encode:", err)
542 out := make(Bug1StructMap)
543 err = dec.Decode(&out)
545 t.Fatal("decode:", err)
547 if !reflect.DeepEqual(in, out) {
548 t.Errorf("mismatch: %v %v", in, out)
552 func TestGobMapInterfaceEncode(t *testing.T) {
553 m := map[string]interface{}{
567 "c0": []complex64{complex(2, -2)},
568 "c1": []complex128{complex(2, float64(-2))},
573 enc := NewEncoder(new(bytes.Buffer))
576 t.Errorf("encode map: %s", err)
580 func TestSliceReusesMemory(t *testing.T) {
581 buf := new(bytes.Buffer)
585 enc := NewEncoder(buf)
588 t.Errorf("bytes: encode: %s", err)
590 // Decode into y, which is big enough.
593 dec := NewDecoder(buf)
596 t.Fatal("bytes: decode:", err)
598 if !bytes.Equal(x, y) {
599 t.Errorf("bytes: expected %q got %q\n", x, y)
602 t.Errorf("bytes: unnecessary reallocation")
608 enc := NewEncoder(buf)
611 t.Errorf("ints: encode: %s", err)
613 // Decode into y, which is big enough.
616 dec := NewDecoder(buf)
619 t.Fatal("ints: decode:", err)
621 if !reflect.DeepEqual(x, y) {
622 t.Errorf("ints: expected %q got %q\n", x, y)
625 t.Errorf("ints: unnecessary reallocation")
630 // Used to crash: negative count in recvMessage.
631 func TestBadCount(t *testing.T) {
632 b := []byte{0xfb, 0xa5, 0x82, 0x2f, 0xca, 0x1}
633 if err := NewDecoder(bytes.NewBuffer(b)).Decode(nil); err == nil {
634 t.Error("expected error from bad count")
635 } else if err.Error() != errBadCount.Error() {
636 t.Error("expected bad count error; got", err)
640 // Verify that sequential Decoders built on a single input will
641 // succeed if the input implements ReadByte and there is no
642 // type information in the stream.
643 func TestSequentialDecoder(t *testing.T) {
644 b := new(bytes.Buffer)
647 for i := 0; i < count; i++ {
648 s := fmt.Sprintf("%d", i)
649 if err := enc.Encode(s); err != nil {
650 t.Error("encoder fail:", err)
653 for i := 0; i < count; i++ {
656 if err := dec.Decode(&s); err != nil {
657 t.Fatal("decoder fail:", err)
659 if s != fmt.Sprintf("%d", i) {
660 t.Fatalf("decode expected %d got %s", i, s)
665 // Should be able to have unrepresentable fields (chan, func) as long as they
672 func TestUnexportedChan(t *testing.T) {
673 b := Bug2{23, make(chan int)}
674 var stream bytes.Buffer
675 enc := NewEncoder(&stream)
676 if err := enc.Encode(b); err != nil {
677 t.Fatalf("error encoding unexported channel: %s", err)
681 func TestSliceIncompatibility(t *testing.T) {
682 var in = []byte{1, 2, 3}
684 if err := encAndDec(in, &out); err == nil {
685 t.Error("expected compatibility error")
689 // Mutually recursive slices of structs caused problems.
695 func TestGobPtrSlices(t *testing.T) {
700 b := new(bytes.Buffer)
701 err := NewEncoder(b).Encode(&in)
703 t.Fatal("encode:", err)
707 err = NewDecoder(b).Decode(&out)
709 t.Fatal("decode:", err)
711 if !reflect.DeepEqual(in, out) {
712 t.Fatalf("got %v; wanted %v", out, in)
716 // getDecEnginePtr cached engine for ut.base instead of ut.user so we passed
717 // a *map and then tried to reuse its engine to decode the inner map.
718 func TestPtrToMapOfMap(t *testing.T) {
719 Register(make(map[string]interface{}))
720 subdata := make(map[string]interface{})
721 subdata["bar"] = "baz"
722 data := make(map[string]interface{})
723 data["foo"] = subdata
725 b := new(bytes.Buffer)
726 err := NewEncoder(b).Encode(data)
728 t.Fatal("encode:", err)
730 var newData map[string]interface{}
731 err = NewDecoder(b).Decode(&newData)
733 t.Fatal("decode:", err)
735 if !reflect.DeepEqual(data, newData) {
736 t.Fatalf("expected %v got %v", data, newData)
740 // A top-level nil pointer generates a panic with a helpful string-valued message.
741 func TestTopLevelNilPointer(t *testing.T) {
742 errMsg := topLevelNilPanic(t)
744 t.Fatal("top-level nil pointer did not panic")
746 if !strings.Contains(errMsg, "nil pointer") {
747 t.Fatal("expected nil pointer error, got:", errMsg)
751 func topLevelNilPanic(t *testing.T) (panicErr string) {
754 if err, ok := e.(string); ok {
759 buf := new(bytes.Buffer)
760 if err := NewEncoder(buf).Encode(ip); err != nil {
761 t.Fatal("error in encode:", err)
766 func TestNilPointerInsideInterface(t *testing.T) {
773 buf := new(bytes.Buffer)
774 err := NewEncoder(buf).Encode(si)
776 t.Fatal("expected error, got none")
778 errMsg := err.Error()
779 if !strings.Contains(errMsg, "nil pointer") || !strings.Contains(errMsg, "interface") {
780 t.Fatal("expected error about nil pointer and interface, got:", errMsg)
784 type Bug4Public struct {
789 type Bug4Secret struct {
790 a int // error: no exported fields.
793 // Test that a failed compilation doesn't leave around an executable encoder.
795 func TestMutipleEncodingsOfBadType(t *testing.T) {
798 Secret: Bug4Secret{1},
800 buf := new(bytes.Buffer)
801 enc := NewEncoder(buf)
804 t.Fatal("first encoding: expected error")
807 enc = NewEncoder(buf)
810 t.Fatal("second encoding: expected error")
812 if !strings.Contains(err.Error(), "no exported fields") {
813 t.Errorf("expected error about no exported fields; got %v", err)
817 // There was an error check comparing the length of the input with the
818 // length of the slice being decoded. It was wrong because the next
819 // thing in the input might be a type definition, which would lead to
820 // an incorrect length check. This test reproduces the corner case.
825 func Test29ElementSlice(t *testing.T) {
827 src := make([]interface{}, 100) // Size needs to be bigger than size of type definition.
831 buf := new(bytes.Buffer)
832 err := NewEncoder(buf).Encode(src)
834 t.Fatalf("encode: %v", err)
838 var dst []interface{}
839 err = NewDecoder(buf).Decode(&dst)
841 t.Errorf("decode: %v", err)