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.
19 func TestBool(t *testing.T) {
22 t.Fatal("ValueOf(true).Bool() = false")
39 func isDigit(c uint8) bool { return '0' <= c && c <= '9' }
41 func assert(t *testing.T, s, want string) {
43 t.Errorf("have %#q want %#q", s, want)
47 func typestring(i interface{}) string { return TypeOf(i).String() }
49 var typeTests = []pair{
50 {struct{ x int }{}, "int"},
51 {struct{ x int8 }{}, "int8"},
52 {struct{ x int16 }{}, "int16"},
53 {struct{ x int32 }{}, "int32"},
54 {struct{ x int64 }{}, "int64"},
55 {struct{ x uint }{}, "uint"},
56 {struct{ x uint8 }{}, "uint8"},
57 {struct{ x uint16 }{}, "uint16"},
58 {struct{ x uint32 }{}, "uint32"},
59 {struct{ x uint64 }{}, "uint64"},
60 {struct{ x float32 }{}, "float32"},
61 {struct{ x float64 }{}, "float64"},
62 {struct{ x int8 }{}, "int8"},
63 {struct{ x (**int8) }{}, "**int8"},
64 {struct{ x (**integer) }{}, "**reflect_test.integer"},
65 {struct{ x ([32]int32) }{}, "[32]int32"},
66 {struct{ x ([]int8) }{}, "[]int8"},
67 {struct{ x (map[string]int32) }{}, "map[string]int32"},
68 {struct{ x (chan<- string) }{}, "chan<- string"},
75 "struct { c chan *int32; d float32 }",
77 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
80 c func(chan *integer, *int8)
83 "struct { c func(chan *reflect_test.integer, *int8) }",
91 "struct { a int8; b int32 }",
100 "struct { a int8; b int8; c int32 }",
110 "struct { a int8; b int8; c int8; d int32 }",
121 "struct { a int8; b int8; c int8; d int8; e int32 }",
133 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
137 a int8 `reflect:"hi there"`
140 `struct { a int8 "reflect:\"hi there\"" }`,
144 a int8 `reflect:"hi \x00there\t\n\"\\"`
147 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
154 "struct { f func(...int) }",
158 a(func(func(int) int) func(func(int)) int)
162 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
166 var valueTests = []pair{
175 {new(float32), "256.25"},
176 {new(float64), "512.125"},
177 {new(string), "stringy cheese"},
179 {new(*int8), "*int8(0)"},
180 {new(**int8), "**int8(0)"},
181 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
182 {new(**integer), "**reflect_test.integer(0)"},
183 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
184 {new(chan<- string), "chan<- string"},
185 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
190 "struct { c chan *int32; d float32 }{chan *int32, 0}",
192 {new(struct{ c func(chan *integer, *int8) }),
193 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
199 "struct { a int8; b int32 }{0, 0}",
206 "struct { a int8; b int8; c int32 }{0, 0, 0}",
210 func testType(t *testing.T, i int, typ Type, want string) {
213 t.Errorf("#%d: have %#q, want %#q", i, s, want)
217 func TestTypes(t *testing.T) {
218 for i, tt := range typeTests {
219 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
223 func TestSet(t *testing.T) {
224 for i, tt := range valueTests {
253 v.SetComplex(532.125 + 10i)
255 v.SetComplex(564.25 + 1i)
257 v.SetString("stringy cheese")
261 s := valueToString(v)
263 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
268 func TestSetValue(t *testing.T) {
269 for i, tt := range valueTests {
270 v := ValueOf(tt.i).Elem()
273 v.Set(ValueOf(int(132)))
275 v.Set(ValueOf(int8(8)))
277 v.Set(ValueOf(int16(16)))
279 v.Set(ValueOf(int32(32)))
281 v.Set(ValueOf(int64(64)))
283 v.Set(ValueOf(uint(132)))
285 v.Set(ValueOf(uint8(8)))
287 v.Set(ValueOf(uint16(16)))
289 v.Set(ValueOf(uint32(32)))
291 v.Set(ValueOf(uint64(64)))
293 v.Set(ValueOf(float32(256.25)))
295 v.Set(ValueOf(512.125))
297 v.Set(ValueOf(complex64(532.125 + 10i)))
299 v.Set(ValueOf(complex128(564.25 + 1i)))
301 v.Set(ValueOf("stringy cheese"))
305 s := valueToString(v)
307 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
314 var valueToStringTests = []pair{
319 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
320 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
321 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
322 {&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[10]int(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
323 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
324 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
327 func TestValueToString(t *testing.T) {
328 for i, test := range valueToStringTests {
329 s := valueToString(ValueOf(test.i))
331 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
336 func TestArrayElemSet(t *testing.T) {
337 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
338 v.Index(4).SetInt(123)
339 s := valueToString(v)
340 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
342 t.Errorf("[10]int: have %#q want %#q", s, want)
345 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
346 v.Index(4).SetInt(123)
348 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
350 t.Errorf("[]int: have %#q want %#q", s, want1)
354 func TestPtrPointTo(t *testing.T) {
358 vi := ValueOf(&i).Elem()
359 vip.Elem().Set(vi.Addr())
361 t.Errorf("got %d, want 1234", *ip)
365 vp := ValueOf(&ip).Elem()
366 vp.Set(Zero(vp.Type()))
368 t.Errorf("got non-nil (%p), want nil", ip)
372 func TestPtrSetNil(t *testing.T) {
376 vip.Elem().Set(Zero(vip.Elem().Type()))
378 t.Errorf("got non-nil (%d), want nil", *ip)
382 func TestMapSetNil(t *testing.T) {
383 m := make(map[string]int)
385 vm.Elem().Set(Zero(vm.Elem().Type()))
387 t.Errorf("got non-nil (%p), want nil", m)
391 func TestAll(t *testing.T) {
392 testType(t, 1, TypeOf((int8)(0)), "int8")
393 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
395 typ := TypeOf((*struct {
399 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
401 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
404 testType(t, 5, f.Type, "chan *int32")
406 f, present := styp.FieldByName("d")
408 t.Errorf("FieldByName says present field is absent")
410 testType(t, 6, f.Type, "float32")
412 f, present = styp.FieldByName("absent")
414 t.Errorf("FieldByName says absent field is present")
417 typ = TypeOf([32]int32{})
418 testType(t, 7, typ, "[32]int32")
419 testType(t, 8, typ.Elem(), "int32")
421 typ = TypeOf((map[string]*int32)(nil))
422 testType(t, 9, typ, "map[string]*int32")
424 testType(t, 10, mtyp.Key(), "string")
425 testType(t, 11, mtyp.Elem(), "*int32")
427 typ = TypeOf((chan<- string)(nil))
428 testType(t, 12, typ, "chan<- string")
429 testType(t, 13, typ.Elem(), "string")
431 // make sure tag strings are not part of element type
432 typ = TypeOf(struct {
433 d []uint32 `reflect:"TAG"`
435 testType(t, 14, typ, "[]uint32")
438 func TestInterfaceGet(t *testing.T) {
443 v1 := ValueOf(&inter)
444 v2 := v1.Elem().Field(0)
445 assert(t, v2.Type().String(), "interface {}")
448 assert(t, v3.Type().String(), "float64")
451 func TestInterfaceValue(t *testing.T) {
456 v1 := ValueOf(&inter)
457 v2 := v1.Elem().Field(0)
458 assert(t, v2.Type().String(), "interface {}")
460 assert(t, v3.Type().String(), "float64")
463 if _, ok := i3.(float64); !ok {
464 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
468 func TestFunctionValue(t *testing.T) {
469 var x interface{} = func() {}
471 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
472 t.Fatalf("TestFunction returned wrong pointer")
474 assert(t, v.Type().String(), "func()")
477 var appendTests = []struct {
480 {make([]int, 2, 4), []int{22}},
481 {make([]int, 2, 4), []int{22, 33, 44}},
484 func sameInts(x, y []int) bool {
485 if len(x) != len(y) {
488 for i, xx := range x {
496 func TestAppend(t *testing.T) {
497 for i, test := range appendTests {
498 origLen, extraLen := len(test.orig), len(test.extra)
499 want := append(test.orig, test.extra...)
500 // Convert extra from []int to []Value.
501 e0 := make([]Value, len(test.extra))
502 for j, e := range test.extra {
505 // Convert extra from []int to *SliceValue.
506 e1 := ValueOf(test.extra)
508 a0 := ValueOf(test.orig)
509 have0 := Append(a0, e0...).Interface().([]int)
510 if !sameInts(have0, want) {
511 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
513 // Check that the orig and extra slices were not modified.
514 if len(test.orig) != origLen {
515 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
517 if len(test.extra) != extraLen {
518 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
521 a1 := ValueOf(test.orig)
522 have1 := AppendSlice(a1, e1).Interface().([]int)
523 if !sameInts(have1, want) {
524 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
526 // Check that the orig and extra slices were not modified.
527 if len(test.orig) != origLen {
528 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
530 if len(test.extra) != extraLen {
531 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
536 func TestCopy(t *testing.T) {
537 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
538 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
539 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
540 for i := 0; i < len(b); i++ {
542 t.Fatalf("b != c before test")
547 aa := ValueOf(&a1).Elem()
548 ab := ValueOf(&b1).Elem()
549 for tocopy := 1; tocopy <= 7; tocopy++ {
553 for i := 0; i < tocopy; i++ {
555 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
556 tocopy, i, a[i], i, b[i])
559 for i := tocopy; i < len(b); i++ {
562 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
563 tocopy, i, a[i], i, b[i], i, c[i])
565 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
566 tocopy, i, b[i], i, c[i])
569 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
575 func TestCopyArray(t *testing.T) {
576 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
577 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
579 aa := ValueOf(&a).Elem()
580 ab := ValueOf(&b).Elem()
582 for i := 0; i < len(a); i++ {
584 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
587 for i := len(a); i < len(b); i++ {
589 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
591 t.Logf("elem %d is okay\n", i)
596 func TestBigUnnamedStruct(t *testing.T) {
597 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
599 b1 := v.Interface().(struct {
602 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
603 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
611 func TestBigStruct(t *testing.T) {
612 b := big{1, 2, 3, 4, 5}
614 b1 := v.Interface().(big)
615 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
616 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
627 type DeepEqualTest struct {
632 // Simple functions for DeepEqual tests.
636 fn3 = func() { fn1() } // Not nil.
639 var deepEqualTests = []DeepEqualTest{
643 {int32(1), int32(1), true},
645 {float32(0.5), float32(0.5), true},
646 {"hello", "hello", true},
647 {make([]int, 10), make([]int, 10), true},
648 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
649 {Basic{1, 0.5}, Basic{1, 0.5}, true},
650 {error(nil), error(nil), true},
651 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
656 {int32(1), int32(2), false},
658 {float32(0.5), float32(0.6), false},
659 {"hello", "hey", false},
660 {make([]int, 10), make([]int, 11), false},
661 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
662 {Basic{1, 0.5}, Basic{1, 0.6}, false},
663 {Basic{1, 0}, Basic{2, 0}, false},
664 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
665 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
666 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
667 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
673 // Nil vs empty: not the same.
674 {[]int{}, []int(nil), false},
675 {[]int{}, []int{}, true},
676 {[]int(nil), []int(nil), true},
677 {map[int]int{}, map[int]int(nil), false},
678 {map[int]int{}, map[int]int{}, true},
679 {map[int]int(nil), map[int]int(nil), true},
683 {int32(1), int64(1), false},
684 {0.5, "hello", false},
685 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
686 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
687 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
688 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
691 func TestDeepEqual(t *testing.T) {
692 for _, test := range deepEqualTests {
693 if r := DeepEqual(test.a, test.b); r != test.eq {
694 t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
699 func TestTypeOf(t *testing.T) {
700 // Special case for nil
701 if typ := TypeOf(nil); typ != nil {
702 t.Errorf("expected nil type for nil value; got %v", typ)
704 for _, test := range deepEqualTests {
709 typ := TypeOf(test.a)
711 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
716 type Recursive struct {
721 func TestDeepEqualRecursiveStruct(t *testing.T) {
722 a, b := new(Recursive), new(Recursive)
723 *a = Recursive{12, a}
724 *b = Recursive{12, b}
725 if !DeepEqual(a, b) {
726 t.Error("DeepEqual(recursive same) = false, want true")
730 type _Complex struct {
734 d map[float64]float64
737 func TestDeepEqualComplexStruct(t *testing.T) {
738 m := make(map[float64]float64)
739 stra, strb := "hello", "hello"
740 a, b := new(_Complex), new(_Complex)
741 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
742 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
743 if !DeepEqual(a, b) {
744 t.Error("DeepEqual(complex same) = false, want true")
748 func TestDeepEqualComplexStructInequality(t *testing.T) {
749 m := make(map[float64]float64)
750 stra, strb := "hello", "helloo" // Difference is here
751 a, b := new(_Complex), new(_Complex)
752 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
753 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
755 t.Error("DeepEqual(complex different) = true, want false")
763 func TestDeepEqualUnexportedMap(t *testing.T) {
764 // Check that DeepEqual can look at unexported fields.
765 x1 := UnexpT{map[int]int{1: 2}}
766 x2 := UnexpT{map[int]int{1: 2}}
767 if !DeepEqual(&x1, &x2) {
768 t.Error("DeepEqual(x1, x2) = false, want true")
771 y1 := UnexpT{map[int]int{2: 3}}
772 if DeepEqual(&x1, &y1) {
773 t.Error("DeepEqual(x1, y1) = true, want false")
777 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
779 f := s.Type().Field(1)
780 if f.Offset != offs {
781 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
785 // Check that structure alignment & offsets viewed through reflect agree with those
786 // from the compiler itself.
787 func TestAlignment(t *testing.T) {
788 type T1inner struct {
795 type T2inner struct {
803 x := T1{T1inner{2}, 17}
804 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
806 x1 := T2{T2inner{2, 3}, 17}
807 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
810 func Nil(a interface{}, t *testing.T) {
811 n := ValueOf(a).Field(0)
813 t.Errorf("%v should be nil", a)
817 func NotNil(a interface{}, t *testing.T) {
818 n := ValueOf(a).Field(0)
820 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
824 func TestIsNil(t *testing.T) {
825 // These implement IsNil.
826 // Wrap in extra struct to hide interface type.
827 doNil := []interface{}{
829 struct{ x interface{} }{},
830 struct{ x map[string]int }{},
831 struct{ x func() bool }{},
832 struct{ x chan int }{},
833 struct{ x []string }{},
835 for _, ts := range doNil {
836 ty := TypeOf(ts).Field(0).Type
838 v.IsNil() // panics if not okay to call
841 // Check the implementations
853 si.x = make([]int, 10)
860 ci.x = make(chan int)
867 mi.x = make(map[int]int)
885 func TestInterfaceExtraction(t *testing.T) {
891 v := Indirect(ValueOf(&s)).Field(0).Interface()
892 if v != s.W.(interface{}) {
893 t.Error("Interface() on interface: ", v, s.W)
897 func TestNilPtrValueSub(t *testing.T) {
899 if pv := ValueOf(pi); pv.Elem().IsValid() {
900 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
904 func TestMap(t *testing.T) {
905 m := map[string]int{"a": 1, "b": 2}
907 if n := mv.Len(); n != len(m) {
908 t.Errorf("Len = %d, want %d", n, len(m))
911 newmap := MakeMap(mv.Type())
912 for k, v := range m {
913 // Check that returned Keys match keys in range.
914 // These aren't required to be in the same order.
916 for _, kv := range keys {
917 if kv.String() == k {
923 t.Errorf("Missing key %q", k)
926 // Check that value lookup is correct.
927 vv := mv.MapIndex(ValueOf(k))
928 if vi := vv.Int(); vi != int64(v) {
929 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
932 // Copy into new map.
933 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
935 vv := mv.MapIndex(ValueOf("not-present"))
937 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
940 newm := newmap.Interface().(map[string]int)
941 if len(newm) != len(m) {
942 t.Errorf("length after copy: newm=%d, m=%d", newm, m)
945 for k, v := range newm {
948 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
952 newmap.SetMapIndex(ValueOf("a"), Value{})
955 t.Errorf("newm[\"a\"] = %d after delete", v)
958 mv = ValueOf(&m).Elem()
959 mv.Set(Zero(mv.Type()))
961 t.Errorf("mv.Set(nil) failed")
965 func TestChan(t *testing.T) {
966 for loop := 0; loop < 2; loop++ {
970 // check both ways to allocate channels
973 c = make(chan int, 1)
976 cv = MakeChan(TypeOf(c), 1)
977 c = cv.Interface().(chan int)
982 if i := <-c; i != 2 {
983 t.Errorf("reflect Send 2, native recv %d", i)
988 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
989 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
993 val, ok := cv.TryRecv()
994 if val.IsValid() || ok {
995 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1000 val, ok = cv.TryRecv()
1002 t.Errorf("TryRecv on ready chan got nil")
1003 } else if i := val.Int(); i != 4 || !ok {
1004 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1009 ok = cv.TrySend(ValueOf(5))
1012 t.Errorf("TrySend on full chan succeeded: value %d", i)
1016 ok = cv.TrySend(ValueOf(6))
1018 t.Errorf("TrySend on empty chan failed")
1020 if i = <-c; i != 6 {
1021 t.Errorf("TrySend 6, recv %d", i)
1028 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1029 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1031 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1032 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1036 // check creation of unbuffered channel
1038 cv := MakeChan(TypeOf(c), 0)
1039 c = cv.Interface().(chan int)
1040 if cv.TrySend(ValueOf(7)) {
1041 t.Errorf("TrySend on sync chan succeeded")
1043 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1044 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1048 cv = MakeChan(TypeOf(c), 10)
1049 c = cv.Interface().(chan int)
1050 for i := 0; i < 3; i++ {
1053 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1054 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1059 // Difficult test for function call because of
1060 // implicit padding between arguments.
1061 func dummy(b byte, c int, d byte) (i byte, j int, k byte) {
1065 func TestFunc(t *testing.T) {
1066 ret := ValueOf(dummy).Call([]Value{ValueOf(byte(10)), ValueOf(20), ValueOf(byte(30))})
1068 t.Fatalf("Call returned %d values, want 3", len(ret))
1071 i := byte(ret[0].Uint())
1072 j := int(ret[1].Int())
1073 k := byte(ret[2].Uint())
1074 if i != 10 || j != 20 || k != 30 {
1075 t.Errorf("Call returned %d, %d, %d; want 10, 20, 30", i, j, k)
1083 // This will be index 0.
1084 func (p Point) AnotherMethod(scale int) int {
1088 // This will be index 1.
1089 func (p Point) Dist(scale int) int {
1090 // println("Point.Dist", p.x, p.y, scale)
1091 return p.x*p.x*scale + p.y*p.y*scale
1094 func TestMethod(t *testing.T) {
1095 // Non-curried method of type.
1097 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1099 t.Errorf("Type Method returned %d; want 250", i)
1102 m, ok := TypeOf(p).MethodByName("Dist")
1104 t.Fatalf("method by name failed")
1106 m.Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1108 t.Errorf("Type MethodByName returned %d; want 250", i)
1111 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(10)})[0].Int()
1113 t.Errorf("Pointer Type Method returned %d; want 250", i)
1116 m, ok = TypeOf(&p).MethodByName("Dist")
1118 t.Fatalf("ptr method by name failed")
1120 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(10)})[0].Int()
1122 t.Errorf("Pointer Type MethodByName returned %d; want 250", i)
1125 // Curried method of value.
1126 tfunc := TypeOf(func(int) int(nil))
1127 v := ValueOf(p).Method(1)
1128 if tt := v.Type(); tt != tfunc {
1129 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1131 i = v.Call([]Value{ValueOf(10)})[0].Int()
1133 t.Errorf("Value Method returned %d; want 250", i)
1135 v = ValueOf(p).MethodByName("Dist")
1136 if tt := v.Type(); tt != tfunc {
1137 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1139 i = v.Call([]Value{ValueOf(10)})[0].Int()
1141 t.Errorf("Value MethodByName returned %d; want 250", i)
1144 // Curried method of pointer.
1145 v = ValueOf(&p).Method(1)
1146 if tt := v.Type(); tt != tfunc {
1147 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1149 i = v.Call([]Value{ValueOf(10)})[0].Int()
1151 t.Errorf("Pointer Value Method returned %d; want 250", i)
1153 v = ValueOf(&p).MethodByName("Dist")
1154 if tt := v.Type(); tt != tfunc {
1155 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1157 i = v.Call([]Value{ValueOf(10)})[0].Int()
1159 t.Errorf("Pointer Value MethodByName returned %d; want 250", i)
1162 // Curried method of interface value.
1163 // Have to wrap interface value in a struct to get at it.
1164 // Passing it to ValueOf directly would
1165 // access the underlying Point, not the interface.
1171 pv := ValueOf(s).Field(0)
1173 if tt := v.Type(); tt != tfunc {
1174 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1176 i = v.Call([]Value{ValueOf(10)})[0].Int()
1178 t.Errorf("Interface Method returned %d; want 250", i)
1180 v = pv.MethodByName("Dist")
1181 if tt := v.Type(); tt != tfunc {
1182 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1184 i = v.Call([]Value{ValueOf(10)})[0].Int()
1186 t.Errorf("Interface MethodByName returned %d; want 250", i)
1190 func TestInterfaceSet(t *testing.T) {
1199 sv := ValueOf(&s).Elem()
1200 sv.Field(0).Set(ValueOf(p))
1201 if q := s.I.(*Point); q != p {
1202 t.Errorf("i: have %p want %p", q, p)
1207 if q := s.P.(*Point); q != p {
1208 t.Errorf("i: have %p want %p", q, p)
1211 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
1213 t.Errorf("Interface Method returned %d; want 250", i)
1222 func TestAnonymousFields(t *testing.T) {
1223 var field StructField
1227 if field, ok = type1.FieldByName("int"); !ok {
1228 t.Error("no field 'int'")
1230 if field.Index[0] != 1 {
1231 t.Error("field index should be 1; is", field.Index)
1285 var fieldTests = []FTest{
1286 {struct{}{}, "", nil, 0},
1287 {struct{}{}, "Foo", nil, 0},
1288 {S0{A: 'a'}, "A", []int{0}, 'a'},
1289 {S0{}, "D", nil, 0},
1290 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
1291 {S1{B: 'b'}, "B", []int{0}, 'b'},
1292 {S1{}, "S0", []int{1}, 0},
1293 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
1294 {S2{A: 'a'}, "A", []int{0}, 'a'},
1295 {S2{}, "S1", []int{1}, 0},
1296 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
1297 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
1298 {S2{}, "D", nil, 0},
1299 {S3{}, "S1", nil, 0},
1300 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
1301 {S3{}, "B", nil, 0},
1302 {S3{D: 'd'}, "D", []int{2}, 0},
1303 {S3{E: 'e'}, "E", []int{3}, 'e'},
1304 {S4{A: 'a'}, "A", []int{1}, 'a'},
1305 {S4{}, "B", nil, 0},
1308 func TestFieldByIndex(t *testing.T) {
1309 for _, test := range fieldTests {
1311 f := s.FieldByIndex(test.index)
1313 if test.index != nil {
1314 if f.Name != test.name {
1315 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
1318 t.Errorf("%s.%s found", s.Name(), f.Name)
1320 } else if len(test.index) > 0 {
1321 t.Errorf("%s.%s not found", s.Name(), test.name)
1324 if test.value != 0 {
1325 v := ValueOf(test.s).FieldByIndex(test.index)
1327 if x, ok := v.Interface().(int); ok {
1328 if x != test.value {
1329 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
1332 t.Errorf("%s%v value not an int", s.Name(), test.index)
1335 t.Errorf("%s%v value not found", s.Name(), test.index)
1341 func TestFieldByName(t *testing.T) {
1342 for _, test := range fieldTests {
1344 f, found := s.FieldByName(test.name)
1346 if test.index != nil {
1347 // Verify field depth and index.
1348 if len(f.Index) != len(test.index) {
1349 t.Errorf("%s.%s depth %d; want %d", s.Name(), test.name, len(f.Index), len(test.index))
1351 for i, x := range f.Index {
1352 if x != test.index[i] {
1353 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
1358 t.Errorf("%s.%s found", s.Name(), f.Name)
1360 } else if len(test.index) > 0 {
1361 t.Errorf("%s.%s not found", s.Name(), test.name)
1364 if test.value != 0 {
1365 v := ValueOf(test.s).FieldByName(test.name)
1367 if x, ok := v.Interface().(int); ok {
1368 if x != test.value {
1369 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
1372 t.Errorf("%s.%s value not an int", s.Name(), test.name)
1375 t.Errorf("%s.%s value not found", s.Name(), test.name)
1381 func TestImportPath(t *testing.T) {
1386 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
1387 {TypeOf(int(0)), ""},
1388 {TypeOf(int8(0)), ""},
1389 {TypeOf(int16(0)), ""},
1390 {TypeOf(int32(0)), ""},
1391 {TypeOf(int64(0)), ""},
1392 {TypeOf(uint(0)), ""},
1393 {TypeOf(uint8(0)), ""},
1394 {TypeOf(uint16(0)), ""},
1395 {TypeOf(uint32(0)), ""},
1396 {TypeOf(uint64(0)), ""},
1397 {TypeOf(uintptr(0)), ""},
1398 {TypeOf(float32(0)), ""},
1399 {TypeOf(float64(0)), ""},
1400 {TypeOf(complex64(0)), ""},
1401 {TypeOf(complex128(0)), ""},
1402 {TypeOf(byte(0)), ""},
1403 {TypeOf(rune(0)), ""},
1404 {TypeOf([]byte(nil)), ""},
1405 {TypeOf([]rune(nil)), ""},
1406 {TypeOf(string("")), ""},
1407 {TypeOf((*interface{})(nil)).Elem(), ""},
1408 {TypeOf((*byte)(nil)), ""},
1409 {TypeOf((*rune)(nil)), ""},
1410 {TypeOf((*int64)(nil)), ""},
1411 {TypeOf(map[string]int{}), ""},
1412 {TypeOf((*error)(nil)).Elem(), ""},
1414 for _, test := range tests {
1415 if path := test.t.PkgPath(); path != test.path {
1416 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
1421 func TestVariadicType(t *testing.T) {
1422 // Test example from Type documentation.
1423 var f func(x int, y ...float64)
1425 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
1427 if sl.Kind() == Slice {
1428 if sl.Elem() == TypeOf(0.0) {
1436 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
1437 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
1438 for i := 0; i < typ.NumIn(); i++ {
1439 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
1453 func (*inner) m() {}
1454 func (*outer) m() {}
1456 func TestNestedMethods(t *testing.T) {
1457 typ := TypeOf((*outer)(nil))
1458 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
1459 t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
1460 for i := 0; i < typ.NumMethod(); i++ {
1462 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
1467 type InnerInt struct {
1471 type OuterInt struct {
1476 func (i *InnerInt) M() int {
1480 func TestEmbeddedMethods(t *testing.T) {
1481 typ := TypeOf((*OuterInt)(nil))
1482 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
1483 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
1484 for i := 0; i < typ.NumMethod(); i++ {
1486 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
1491 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
1492 t.Errorf("i.M() = %d, want 3", v)
1495 o := &OuterInt{1, InnerInt{2}}
1496 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
1497 t.Errorf("i.M() = %d, want 2", v)
1501 if v := f(o); v != 2 {
1502 t.Errorf("f(o) = %d, want 2", v)
1506 func TestPtrTo(t *testing.T) {
1510 for i = 0; i < 100; i++ {
1513 for i = 0; i < 100; i++ {
1516 if typ != TypeOf(i) {
1517 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
1521 func TestAddr(t *testing.T) {
1533 t.Errorf("Addr.Elem.Set failed to set value")
1536 // Again but take address of the ValueOf value.
1537 // Exercises generation of PtrTypes not present in the binary.
1539 v = ValueOf(&q).Elem()
1548 t.Errorf("Addr.Elem.Set failed to set value")
1551 // Starting without pointer we should get changed value
1554 v = ValueOf(&qq).Elem()
1560 if p.X != 3 { // should be unchanged from last time
1561 t.Errorf("somehow value Set changed original p")
1563 p = v0.Interface().(struct {
1567 t.Errorf("Addr.Elem.Set valued to set value in top value")
1570 // Verify that taking the address of a type gives us a pointer
1571 // which we can convert back using the usual interface
1576 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
1577 *(ps.(**bool)) = new(bool)
1579 t.Errorf("Addr.Interface direct assignment failed")
1583 /* gccgo does do allocations here.
1585 func noAlloc(t *testing.T, n int, f func(int)) {
1586 // once to prime everything
1588 memstats := new(runtime.MemStats)
1589 runtime.ReadMemStats(memstats)
1590 oldmallocs := memstats.Mallocs
1592 for j := 0; j < n; j++ {
1595 // A few allocs may happen in the testing package when GOMAXPROCS > 1, so don't
1596 // require zero mallocs.
1597 runtime.ReadMemStats(memstats)
1598 mallocs := memstats.Mallocs - oldmallocs
1600 t.Fatalf("%d mallocs after %d iterations", mallocs, n)
1604 func TestAllocations(t *testing.T) {
1605 noAlloc(t, 100, func(j int) {
1610 if int(v.Int()) != 42+j {
1618 func TestSmallNegativeInt(t *testing.T) {
1622 t.Errorf("int16(-1).Int() returned %v", v.Int())
1626 func TestSlice(t *testing.T) {
1627 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
1628 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
1630 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
1633 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
1635 if !DeepEqual(v[0:5], xs[3:]) {
1636 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
1639 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
1640 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
1642 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
1645 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
1647 if !DeepEqual(v[0:6], xa[2:]) {
1648 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
1652 func TestVariadic(t *testing.T) {
1657 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
1658 if b.String() != "hello, 42 world" {
1659 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
1663 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
1664 if b.String() != "hello, 42 world" {
1665 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
1669 var tagGetTests = []struct {
1674 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
1675 {`protobuf:"PB(1,2)"`, `foo`, ``},
1676 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
1677 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
1678 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
1681 func TestTagGet(t *testing.T) {
1682 for _, tt := range tagGetTests {
1683 if v := tt.Tag.Get(tt.Key); v != tt.Value {
1684 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
1689 func TestBytes(t *testing.T) {
1692 y := ValueOf(x).Bytes()
1693 if !bytes.Equal(x, y) {
1694 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
1697 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
1701 func TestSetBytes(t *testing.T) {
1704 y := []byte{1, 2, 3, 4}
1705 ValueOf(&x).Elem().SetBytes(y)
1706 if !bytes.Equal(x, y) {
1707 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
1710 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
1714 type Private struct {
1719 func (p *Private) m() {
1722 type Public struct {
1727 func (p *Public) M() {
1730 func TestUnexported(t *testing.T) {
1733 isValid(v.Elem().Field(0))
1734 isValid(v.Elem().Field(1))
1735 isValid(v.Elem().FieldByName("X"))
1736 isValid(v.Elem().FieldByName("Y"))
1737 isValid(v.Type().Method(0).Func)
1738 isNonNil(v.Elem().Field(0).Interface())
1739 isNonNil(v.Elem().Field(1).Interface())
1740 isNonNil(v.Elem().FieldByName("X").Interface())
1741 isNonNil(v.Elem().FieldByName("Y").Interface())
1742 isNonNil(v.Type().Method(0).Func.Interface())
1746 isValid(v.Elem().Field(0))
1747 isValid(v.Elem().Field(1))
1748 isValid(v.Elem().FieldByName("x"))
1749 isValid(v.Elem().FieldByName("y"))
1750 isValid(v.Type().Method(0).Func)
1751 shouldPanic(func() { v.Elem().Field(0).Interface() })
1752 shouldPanic(func() { v.Elem().Field(1).Interface() })
1753 shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
1754 shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
1755 shouldPanic(func() { v.Type().Method(0).Func.Interface() })
1758 func shouldPanic(f func()) {
1760 if recover() == nil {
1761 panic("did not panic")
1767 func isNonNil(x interface{}) {
1769 panic("nil interface")
1773 func isValid(v Value) {
1779 func TestAlias(t *testing.T) {
1780 x := string("hello")
1781 v := ValueOf(&x).Elem()
1782 oldvalue := v.Interface()
1783 v.SetString("world")
1784 newvalue := v.Interface()
1786 if oldvalue != "hello" || newvalue != "world" {
1787 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)