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.
27 // Like ET1 but with a different name for a field
34 // Like ET1 but with a different type for a field
41 func TestEncoderDecoder(t *testing.T) {
42 b := new(bytes.Buffer)
47 err := enc.Encode(et1)
49 t.Error("encoder fail:", err)
53 err = dec.Decode(newEt1)
55 t.Fatal("error decoding ET1:", err)
58 if !reflect.DeepEqual(et1, newEt1) {
59 t.Fatalf("invalid data for et1: expected %+v; got %+v", *et1, *newEt1)
62 t.Error("not at eof;", b.Len(), "bytes left")
67 err = dec.Decode(newEt1)
69 t.Fatal("round 2: error decoding ET1:", err)
71 if !reflect.DeepEqual(et1, newEt1) {
72 t.Fatalf("round 2: invalid data for et1: expected %+v; got %+v", *et1, *newEt1)
75 t.Error("round 2: not at eof;", b.Len(), "bytes left")
78 // Now test with a running encoder/decoder pair that we recognize a type mismatch.
81 t.Error("round 3: encoder fail:", err)
84 err = dec.Decode(newEt2)
86 t.Fatal("round 3: expected `bad type' error decoding ET2")
90 // Run one value through the encoder/decoder, but use the wrong type.
91 // Input is always an ET1; we compare it to whatever is under 'e'.
92 func badTypeCheck(e interface{}, shouldFail bool, msg string, t *testing.T) {
93 b := new(bytes.Buffer)
98 err := enc.Encode(et1)
100 t.Error("encoder fail:", err)
104 if shouldFail && err == nil {
105 t.Error("expected error for", msg)
107 if !shouldFail && err != nil {
108 t.Error("unexpected error for", msg, err)
112 // Test that we recognize a bad type the first time.
113 func TestWrongTypeDecoder(t *testing.T) {
114 badTypeCheck(new(ET2), true, "no fields in common", t)
115 badTypeCheck(new(ET3), false, "different name of field", t)
116 badTypeCheck(new(ET4), true, "different type of field", t)
119 func corruptDataCheck(s string, err os.Error, t *testing.T) {
120 b := bytes.NewBufferString(s)
122 err1 := dec.Decode(new(ET2))
124 t.Errorf("from %q expected error %s; got %s", s, err, err1)
128 // Check that we survive bad data.
129 func TestBadData(t *testing.T) {
130 corruptDataCheck("", os.EOF, t)
131 corruptDataCheck("\x7Fhi", io.ErrUnexpectedEOF, t)
132 corruptDataCheck("\x03now is the time for all good men", errBadType, t)
135 // Types not supported by the Encoder.
136 var unsupportedValues = []interface{}{
138 func(a int) bool { return true },
141 func TestUnsupported(t *testing.T) {
143 enc := NewEncoder(&b)
144 for _, v := range unsupportedValues {
147 t.Errorf("expected error for %T; got none", v)
152 func encAndDec(in, out interface{}) os.Error {
153 b := new(bytes.Buffer)
155 err := enc.Encode(in)
160 err = dec.Decode(out)
167 func TestTypeToPtrType(t *testing.T) {
168 // Encode a T, decode a *T
174 if err := encAndDec(t0, t0p); err != nil {
179 func TestPtrTypeToType(t *testing.T) {
180 // Encode a *T, decode a T
186 if err := encAndDec(t1, t1p); err != nil {
191 func TestTypeToPtrPtrPtrPtrType(t *testing.T) {
196 t2.A = new(***float64)
197 *t2.A = new(**float64)
198 **t2.A = new(*float64)
199 ***t2.A = new(float64)
201 t2pppp := new(***Type2)
202 if err := encAndDec(t2, t2pppp); err != nil {
205 if ****(****t2pppp).A != ****t2.A {
206 t.Errorf("wrong value after decode: %g not %g", ****(****t2pppp).A, ****t2.A)
210 func TestSlice(t *testing.T) {
214 t3p := &Type3{[]string{"hello", "world"}}
216 if err := encAndDec(t3, t3p); err != nil {
221 func TestValueError(t *testing.T) {
222 // Encode a *T, decode a T
227 var t4 Type4 // note: not a pointer.
228 if err := encAndDec(t4p, t4); err == nil || strings.Index(err.String(), "pointer") < 0 {
229 t.Error("expected error about pointer; got", err)
233 func TestArray(t *testing.T) {
239 A [2]string // can't hold t5.a
241 t5 := Type5{[3]string{"hello", ",", "world"}, [3]byte{1, 2, 3}}
243 if err := encAndDec(t5, &t5p); err != nil {
247 if err := encAndDec(t5, &t6); err == nil {
248 t.Error("should fail with mismatched array sizes")
252 func TestRecursiveMapType(t *testing.T) {
253 type recursiveMap map[string]recursiveMap
254 r1 := recursiveMap{"A": recursiveMap{"B": nil, "C": nil}, "D": nil}
255 r2 := make(recursiveMap)
256 if err := encAndDec(r1, &r2); err != nil {
261 func TestRecursiveSliceType(t *testing.T) {
262 type recursiveSlice []recursiveSlice
263 r1 := recursiveSlice{0: recursiveSlice{0: nil}, 1: nil}
264 r2 := make(recursiveSlice, 0)
265 if err := encAndDec(r1, &r2); err != nil {
270 // Regression test for bug: must send zero values inside arrays
271 func TestDefaultsInArray(t *testing.T) {
279 []bool{false, false, true},
281 []string{"hi", "", "there"},
285 if err := encAndDec(t7, &t7p); err != nil {
291 var testFloat32 float32
292 var testString string
293 var testSlice []string
294 var testMap map[string]int
297 type SingleTest struct {
303 var singleTests = []SingleTest{
305 {float32(17.5), &testFloat32, ""},
306 {"bike shed", &testString, ""},
307 {[]string{"bike", "shed", "paint", "color"}, &testSlice, ""},
308 {map[string]int{"seven": 7, "twelve": 12}, &testMap, ""},
309 {[7]int{4, 55, 0, 0, 0, 0, 0}, &testArray, ""}, // case that once triggered a bug
310 {[7]int{4, 55, 1, 44, 22, 66, 1234}, &testArray, ""},
313 {172, &testFloat32, "wrong type"},
316 func TestSingletons(t *testing.T) {
317 b := new(bytes.Buffer)
320 for _, test := range singleTests {
322 err := enc.Encode(test.in)
324 t.Errorf("error encoding %v: %s", test.in, err)
327 err = dec.Decode(test.out)
329 case err != nil && test.err == "":
330 t.Errorf("error decoding %v: %s", test.in, err)
332 case err == nil && test.err != "":
333 t.Errorf("expected error decoding %v: %s", test.in, test.err)
335 case err != nil && test.err != "":
336 if strings.Index(err.String(), test.err) < 0 {
337 t.Errorf("wrong error decoding %v: wanted %s, got %v", test.in, test.err, err)
341 // Get rid of the pointer in the rhs
342 val := reflect.NewValue(test.out).(*reflect.PtrValue).Elem().Interface()
343 if !reflect.DeepEqual(test.in, val) {
344 t.Errorf("decoding singleton: expected %v got %v", test.in, val)
349 func TestStructNonStruct(t *testing.T) {
353 type NonStruct string
356 if err := encAndDec(s, &sp); err != nil {
360 if err := encAndDec(s, &ns); err == nil {
361 t.Error("should get error for struct/non-struct")
362 } else if strings.Index(err.String(), "type") < 0 {
363 t.Error("for struct/non-struct expected type error; got", err)
365 // Now try the other way
367 if err := encAndDec(ns, &nsp); err != nil {
370 if err := encAndDec(ns, &s); err == nil {
371 t.Error("should get error for non-struct/struct")
372 } else if strings.Index(err.String(), "type") < 0 {
373 t.Error("for non-struct/struct expected type error; got", err)
377 type interfaceIndirectTestI interface {
381 type interfaceIndirectTestT struct{}
383 func (this *interfaceIndirectTestT) F() bool {
387 // A version of a bug reported on golang-nuts. Also tests top-level
388 // slice of interfaces. The issue was registering *T caused T to be
389 // stored as the concrete type.
390 func TestInterfaceIndirect(t *testing.T) {
391 Register(&interfaceIndirectTestT{})
392 b := new(bytes.Buffer)
393 w := []interfaceIndirectTestI{&interfaceIndirectTestT{}}
394 err := NewEncoder(b).Encode(w)
396 t.Fatal("encode error:", err)
399 var r []interfaceIndirectTestI
400 err = NewDecoder(b).Decode(&r)
402 t.Fatal("decode error:", err)
406 // Now follow various tests that decode into things that can't represent the
407 // encoded value, all of which should be legal.
409 // Also, when the ignored object contains an interface value, it may define
410 // types. Make sure that skipping the value still defines the types by using
411 // the encoder/decoder pair to send a value afterwards. If an interface
412 // is sent, its type in the test is always NewType0, so this checks that the
413 // encoder and decoder don't skew with respect to type definitions.
415 type Struct0 struct {
419 type NewType0 struct {
423 type ignoreTest struct {
427 var ignoreTests = []ignoreTest{
428 // Decode normal struct into an empty struct
429 {&struct{ A int }{23}, &struct{}{}},
430 // Decode normal struct into a nil.
431 {&struct{ A int }{23}, nil},
432 // Decode singleton string into a nil.
433 {"hello, world", nil},
434 // Decode singleton slice into a nil.
435 {[]int{1, 2, 3, 4}, nil},
436 // Decode struct containing an interface into a nil.
437 {&Struct0{&NewType0{"value0"}}, nil},
438 // Decode singleton slice of interfaces into a nil.
439 {[]interface{}{"hi", &NewType0{"value1"}, 23}, nil},
442 func TestDecodeIntoNothing(t *testing.T) {
443 Register(new(NewType0))
444 for i, test := range ignoreTests {
445 b := new(bytes.Buffer)
447 err := enc.Encode(test.in)
449 t.Errorf("%d: encode error %s:", i, err)
453 err = dec.Decode(test.out)
455 t.Errorf("%d: decode error: %s", i, err)
458 // Now see if the encoder and decoder are in a consistent state.
459 str := fmt.Sprintf("Value %d", i)
460 err = enc.Encode(&NewType0{str})
462 t.Fatalf("%d: NewType0 encode error: %s", i, err)
467 t.Fatalf("%d: NewType0 decode error: %s", i, err)
470 t.Fatalf("%d: expected %q got %q", i, str, ns.S)
475 // Another bug from golang-nuts, involving nested interfaces.
476 type Bug0Outer struct {
477 Bug0Field interface{}
480 type Bug0Inner struct {
484 func TestNestedInterfaces(t *testing.T) {
486 e := NewEncoder(&buf)
487 d := NewDecoder(&buf)
488 Register(new(Bug0Outer))
489 Register(new(Bug0Inner))
490 f := &Bug0Outer{&Bug0Outer{&Bug0Inner{7}}}
491 var v interface{} = f
494 t.Fatal("Encode:", err)
498 t.Fatal("Decode:", err)
500 // Make sure it decoded correctly.
501 outer1, ok := v.(*Bug0Outer)
503 t.Fatalf("v not Bug0Outer: %T", v)
505 outer2, ok := outer1.Bug0Field.(*Bug0Outer)
507 t.Fatalf("v.Bug0Field not Bug0Outer: %T", outer1.Bug0Field)
509 inner, ok := outer2.Bug0Field.(*Bug0Inner)
511 t.Fatalf("v.Bug0Field.Bug0Field not Bug0Inner: %T", outer2.Bug0Field)
514 t.Fatalf("final value %d; expected %d", inner.A, 7)