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 var deepEqualTests = []DeepEqualTest{
635 {int32(1), int32(1), true},
637 {float32(0.5), float32(0.5), true},
638 {"hello", "hello", true},
639 {make([]int, 10), make([]int, 10), true},
640 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
641 {Basic{1, 0.5}, Basic{1, 0.5}, true},
642 {error(nil), error(nil), true},
643 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
647 {int32(1), int32(2), false},
649 {float32(0.5), float32(0.6), false},
650 {"hello", "hey", false},
651 {make([]int, 10), make([]int, 11), false},
652 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
653 {Basic{1, 0.5}, Basic{1, 0.6}, false},
654 {Basic{1, 0}, Basic{2, 0}, false},
655 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
656 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
657 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
658 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
662 // Nil vs empty: not the same.
663 {[]int{}, []int(nil), false},
664 {[]int{}, []int{}, true},
665 {[]int(nil), []int(nil), true},
666 {map[int]int{}, map[int]int(nil), false},
667 {map[int]int{}, map[int]int{}, true},
668 {map[int]int(nil), map[int]int(nil), true},
672 {int32(1), int64(1), false},
673 {0.5, "hello", false},
674 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
675 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
676 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
677 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
680 func TestDeepEqual(t *testing.T) {
681 for _, test := range deepEqualTests {
682 if r := DeepEqual(test.a, test.b); r != test.eq {
683 t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
688 func TestTypeOf(t *testing.T) {
689 for _, test := range deepEqualTests {
694 typ := TypeOf(test.a)
696 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
701 type Recursive struct {
706 func TestDeepEqualRecursiveStruct(t *testing.T) {
707 a, b := new(Recursive), new(Recursive)
708 *a = Recursive{12, a}
709 *b = Recursive{12, b}
710 if !DeepEqual(a, b) {
711 t.Error("DeepEqual(recursive same) = false, want true")
715 type _Complex struct {
719 d map[float64]float64
722 func TestDeepEqualComplexStruct(t *testing.T) {
723 m := make(map[float64]float64)
724 stra, strb := "hello", "hello"
725 a, b := new(_Complex), new(_Complex)
726 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
727 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
728 if !DeepEqual(a, b) {
729 t.Error("DeepEqual(complex same) = false, want true")
733 func TestDeepEqualComplexStructInequality(t *testing.T) {
734 m := make(map[float64]float64)
735 stra, strb := "hello", "helloo" // Difference is here
736 a, b := new(_Complex), new(_Complex)
737 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
738 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
740 t.Error("DeepEqual(complex different) = true, want false")
748 func TestDeepEqualUnexportedMap(t *testing.T) {
749 // Check that DeepEqual can look at unexported fields.
750 x1 := UnexpT{map[int]int{1: 2}}
751 x2 := UnexpT{map[int]int{1: 2}}
752 if !DeepEqual(&x1, &x2) {
753 t.Error("DeepEqual(x1, x2) = false, want true")
756 y1 := UnexpT{map[int]int{2: 3}}
757 if DeepEqual(&x1, &y1) {
758 t.Error("DeepEqual(x1, y1) = true, want false")
762 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
764 f := s.Type().Field(1)
765 if f.Offset != offs {
766 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
770 // Check that structure alignment & offsets viewed through reflect agree with those
771 // from the compiler itself.
772 func TestAlignment(t *testing.T) {
773 type T1inner struct {
780 type T2inner struct {
788 x := T1{T1inner{2}, 17}
789 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
791 x1 := T2{T2inner{2, 3}, 17}
792 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
795 func Nil(a interface{}, t *testing.T) {
796 n := ValueOf(a).Field(0)
798 t.Errorf("%v should be nil", a)
802 func NotNil(a interface{}, t *testing.T) {
803 n := ValueOf(a).Field(0)
805 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
809 func TestIsNil(t *testing.T) {
810 // These implement IsNil.
811 // Wrap in extra struct to hide interface type.
812 doNil := []interface{}{
814 struct{ x interface{} }{},
815 struct{ x map[string]int }{},
816 struct{ x func() bool }{},
817 struct{ x chan int }{},
818 struct{ x []string }{},
820 for _, ts := range doNil {
821 ty := TypeOf(ts).Field(0).Type
823 v.IsNil() // panics if not okay to call
826 // Check the implementations
838 si.x = make([]int, 10)
845 ci.x = make(chan int)
852 mi.x = make(map[int]int)
870 func TestInterfaceExtraction(t *testing.T) {
876 v := Indirect(ValueOf(&s)).Field(0).Interface()
877 if v != s.W.(interface{}) {
878 t.Error("Interface() on interface: ", v, s.W)
882 func TestNilPtrValueSub(t *testing.T) {
884 if pv := ValueOf(pi); pv.Elem().IsValid() {
885 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
889 func TestMap(t *testing.T) {
890 m := map[string]int{"a": 1, "b": 2}
892 if n := mv.Len(); n != len(m) {
893 t.Errorf("Len = %d, want %d", n, len(m))
896 newmap := MakeMap(mv.Type())
897 for k, v := range m {
898 // Check that returned Keys match keys in range.
899 // These aren't required to be in the same order.
901 for _, kv := range keys {
902 if kv.String() == k {
908 t.Errorf("Missing key %q", k)
911 // Check that value lookup is correct.
912 vv := mv.MapIndex(ValueOf(k))
913 if vi := vv.Int(); vi != int64(v) {
914 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
917 // Copy into new map.
918 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
920 vv := mv.MapIndex(ValueOf("not-present"))
922 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
925 newm := newmap.Interface().(map[string]int)
926 if len(newm) != len(m) {
927 t.Errorf("length after copy: newm=%d, m=%d", newm, m)
930 for k, v := range newm {
933 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
937 newmap.SetMapIndex(ValueOf("a"), Value{})
940 t.Errorf("newm[\"a\"] = %d after delete", v)
943 mv = ValueOf(&m).Elem()
944 mv.Set(Zero(mv.Type()))
946 t.Errorf("mv.Set(nil) failed")
950 func TestChan(t *testing.T) {
951 for loop := 0; loop < 2; loop++ {
955 // check both ways to allocate channels
958 c = make(chan int, 1)
961 cv = MakeChan(TypeOf(c), 1)
962 c = cv.Interface().(chan int)
967 if i := <-c; i != 2 {
968 t.Errorf("reflect Send 2, native recv %d", i)
973 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
974 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
978 val, ok := cv.TryRecv()
979 if val.IsValid() || ok {
980 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
985 val, ok = cv.TryRecv()
987 t.Errorf("TryRecv on ready chan got nil")
988 } else if i := val.Int(); i != 4 || !ok {
989 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
994 ok = cv.TrySend(ValueOf(5))
997 t.Errorf("TrySend on full chan succeeded: value %d", i)
1001 ok = cv.TrySend(ValueOf(6))
1003 t.Errorf("TrySend on empty chan failed")
1005 if i = <-c; i != 6 {
1006 t.Errorf("TrySend 6, recv %d", i)
1013 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1014 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1016 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1017 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1021 // check creation of unbuffered channel
1023 cv := MakeChan(TypeOf(c), 0)
1024 c = cv.Interface().(chan int)
1025 if cv.TrySend(ValueOf(7)) {
1026 t.Errorf("TrySend on sync chan succeeded")
1028 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1029 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1033 cv = MakeChan(TypeOf(c), 10)
1034 c = cv.Interface().(chan int)
1035 for i := 0; i < 3; i++ {
1038 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1039 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1044 // Difficult test for function call because of
1045 // implicit padding between arguments.
1046 func dummy(b byte, c int, d byte) (i byte, j int, k byte) {
1050 func TestFunc(t *testing.T) {
1051 ret := ValueOf(dummy).Call([]Value{ValueOf(byte(10)), ValueOf(20), ValueOf(byte(30))})
1053 t.Fatalf("Call returned %d values, want 3", len(ret))
1056 i := byte(ret[0].Uint())
1057 j := int(ret[1].Int())
1058 k := byte(ret[2].Uint())
1059 if i != 10 || j != 20 || k != 30 {
1060 t.Errorf("Call returned %d, %d, %d; want 10, 20, 30", i, j, k)
1068 // This will be index 0.
1069 func (p Point) AnotherMethod(scale int) int {
1073 // This will be index 1.
1074 func (p Point) Dist(scale int) int {
1075 // println("Point.Dist", p.x, p.y, scale)
1076 return p.x*p.x*scale + p.y*p.y*scale
1079 func TestMethod(t *testing.T) {
1080 // Non-curried method of type.
1082 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1084 t.Errorf("Type Method returned %d; want 250", i)
1087 m, ok := TypeOf(p).MethodByName("Dist")
1089 t.Fatalf("method by name failed")
1091 m.Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1093 t.Errorf("Type MethodByName returned %d; want 250", i)
1096 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(10)})[0].Int()
1098 t.Errorf("Pointer Type Method returned %d; want 250", i)
1101 m, ok = TypeOf(&p).MethodByName("Dist")
1103 t.Fatalf("ptr method by name failed")
1105 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(10)})[0].Int()
1107 t.Errorf("Pointer Type MethodByName returned %d; want 250", i)
1110 // Curried method of value.
1111 tfunc := TypeOf(func(int) int(nil))
1112 v := ValueOf(p).Method(1)
1113 if tt := v.Type(); tt != tfunc {
1114 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1116 i = v.Call([]Value{ValueOf(10)})[0].Int()
1118 t.Errorf("Value Method returned %d; want 250", i)
1120 v = ValueOf(p).MethodByName("Dist")
1121 if tt := v.Type(); tt != tfunc {
1122 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1124 i = v.Call([]Value{ValueOf(10)})[0].Int()
1126 t.Errorf("Value MethodByName returned %d; want 250", i)
1129 // Curried method of pointer.
1130 v = ValueOf(&p).Method(1)
1131 if tt := v.Type(); tt != tfunc {
1132 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1134 i = v.Call([]Value{ValueOf(10)})[0].Int()
1136 t.Errorf("Pointer Value Method returned %d; want 250", i)
1138 v = ValueOf(&p).MethodByName("Dist")
1139 if tt := v.Type(); tt != tfunc {
1140 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1142 i = v.Call([]Value{ValueOf(10)})[0].Int()
1144 t.Errorf("Pointer Value MethodByName returned %d; want 250", i)
1147 // Curried method of interface value.
1148 // Have to wrap interface value in a struct to get at it.
1149 // Passing it to ValueOf directly would
1150 // access the underlying Point, not the interface.
1156 pv := ValueOf(s).Field(0)
1158 if tt := v.Type(); tt != tfunc {
1159 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1161 i = v.Call([]Value{ValueOf(10)})[0].Int()
1163 t.Errorf("Interface Method returned %d; want 250", i)
1165 v = pv.MethodByName("Dist")
1166 if tt := v.Type(); tt != tfunc {
1167 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1169 i = v.Call([]Value{ValueOf(10)})[0].Int()
1171 t.Errorf("Interface MethodByName returned %d; want 250", i)
1175 func TestInterfaceSet(t *testing.T) {
1184 sv := ValueOf(&s).Elem()
1185 sv.Field(0).Set(ValueOf(p))
1186 if q := s.I.(*Point); q != p {
1187 t.Errorf("i: have %p want %p", q, p)
1192 if q := s.P.(*Point); q != p {
1193 t.Errorf("i: have %p want %p", q, p)
1196 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
1198 t.Errorf("Interface Method returned %d; want 250", i)
1207 func TestAnonymousFields(t *testing.T) {
1208 var field StructField
1212 if field, ok = type1.FieldByName("int"); !ok {
1213 t.Error("no field 'int'")
1215 if field.Index[0] != 1 {
1216 t.Error("field index should be 1; is", field.Index)
1270 var fieldTests = []FTest{
1271 {struct{}{}, "", nil, 0},
1272 {struct{}{}, "Foo", nil, 0},
1273 {S0{A: 'a'}, "A", []int{0}, 'a'},
1274 {S0{}, "D", nil, 0},
1275 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
1276 {S1{B: 'b'}, "B", []int{0}, 'b'},
1277 {S1{}, "S0", []int{1}, 0},
1278 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
1279 {S2{A: 'a'}, "A", []int{0}, 'a'},
1280 {S2{}, "S1", []int{1}, 0},
1281 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
1282 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
1283 {S2{}, "D", nil, 0},
1284 {S3{}, "S1", nil, 0},
1285 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
1286 {S3{}, "B", nil, 0},
1287 {S3{D: 'd'}, "D", []int{2}, 0},
1288 {S3{E: 'e'}, "E", []int{3}, 'e'},
1289 {S4{A: 'a'}, "A", []int{1}, 'a'},
1290 {S4{}, "B", nil, 0},
1293 func TestFieldByIndex(t *testing.T) {
1294 for _, test := range fieldTests {
1296 f := s.FieldByIndex(test.index)
1298 if test.index != nil {
1299 if f.Name != test.name {
1300 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
1303 t.Errorf("%s.%s found", s.Name(), f.Name)
1305 } else if len(test.index) > 0 {
1306 t.Errorf("%s.%s not found", s.Name(), test.name)
1309 if test.value != 0 {
1310 v := ValueOf(test.s).FieldByIndex(test.index)
1312 if x, ok := v.Interface().(int); ok {
1313 if x != test.value {
1314 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
1317 t.Errorf("%s%v value not an int", s.Name(), test.index)
1320 t.Errorf("%s%v value not found", s.Name(), test.index)
1326 func TestFieldByName(t *testing.T) {
1327 for _, test := range fieldTests {
1329 f, found := s.FieldByName(test.name)
1331 if test.index != nil {
1332 // Verify field depth and index.
1333 if len(f.Index) != len(test.index) {
1334 t.Errorf("%s.%s depth %d; want %d", s.Name(), test.name, len(f.Index), len(test.index))
1336 for i, x := range f.Index {
1337 if x != test.index[i] {
1338 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
1343 t.Errorf("%s.%s found", s.Name(), f.Name)
1345 } else if len(test.index) > 0 {
1346 t.Errorf("%s.%s not found", s.Name(), test.name)
1349 if test.value != 0 {
1350 v := ValueOf(test.s).FieldByName(test.name)
1352 if x, ok := v.Interface().(int); ok {
1353 if x != test.value {
1354 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
1357 t.Errorf("%s.%s value not an int", s.Name(), test.name)
1360 t.Errorf("%s.%s value not found", s.Name(), test.name)
1366 func TestImportPath(t *testing.T) {
1371 {TypeOf(&base64.Encoding{}).Elem(), "libgo_encoding.base64"},
1372 {TypeOf(uint(0)), ""},
1373 {TypeOf(map[string]int{}), ""},
1374 {TypeOf((*error)(nil)).Elem(), ""},
1376 for _, test := range tests {
1377 if path := test.t.PkgPath(); path != test.path {
1378 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
1383 func TestVariadicType(t *testing.T) {
1384 // Test example from Type documentation.
1385 var f func(x int, y ...float64)
1387 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
1389 if sl.Kind() == Slice {
1390 if sl.Elem() == TypeOf(0.0) {
1398 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
1399 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
1400 for i := 0; i < typ.NumIn(); i++ {
1401 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
1415 func (*inner) m() {}
1416 func (*outer) m() {}
1418 func TestNestedMethods(t *testing.T) {
1419 typ := TypeOf((*outer)(nil))
1420 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
1421 t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
1422 for i := 0; i < typ.NumMethod(); i++ {
1424 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
1429 type InnerInt struct {
1433 type OuterInt struct {
1438 func (i *InnerInt) M() int {
1442 func TestEmbeddedMethods(t *testing.T) {
1443 typ := TypeOf((*OuterInt)(nil))
1444 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
1445 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
1446 for i := 0; i < typ.NumMethod(); i++ {
1448 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
1453 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
1454 t.Errorf("i.M() = %d, want 3", v)
1457 o := &OuterInt{1, InnerInt{2}}
1458 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
1459 t.Errorf("i.M() = %d, want 2", v)
1463 if v := f(o); v != 2 {
1464 t.Errorf("f(o) = %d, want 2", v)
1468 func TestPtrTo(t *testing.T) {
1472 for i = 0; i < 100; i++ {
1475 for i = 0; i < 100; i++ {
1478 if typ != TypeOf(i) {
1479 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
1483 func TestAddr(t *testing.T) {
1495 t.Errorf("Addr.Elem.Set failed to set value")
1498 // Again but take address of the ValueOf value.
1499 // Exercises generation of PtrTypes not present in the binary.
1501 v = ValueOf(&q).Elem()
1510 t.Errorf("Addr.Elem.Set failed to set value")
1513 // Starting without pointer we should get changed value
1516 v = ValueOf(&qq).Elem()
1522 if p.X != 3 { // should be unchanged from last time
1523 t.Errorf("somehow value Set changed original p")
1525 p = v0.Interface().(struct {
1529 t.Errorf("Addr.Elem.Set valued to set value in top value")
1533 /* gccgo does do allocations here.
1535 func noAlloc(t *testing.T, n int, f func(int)) {
1536 // once to prime everything
1538 runtime.MemStats.Mallocs = 0
1540 for j := 0; j < n; j++ {
1543 // A few allocs may happen in the testing package when GOMAXPROCS > 1, so don't
1544 // require zero mallocs.
1545 if runtime.MemStats.Mallocs > 5 {
1546 t.Fatalf("%d mallocs after %d iterations", runtime.MemStats.Mallocs, n)
1550 func TestAllocations(t *testing.T) {
1551 noAlloc(t, 100, func(j int) {
1556 if int(v.Int()) != 42+j {
1564 func TestSmallNegativeInt(t *testing.T) {
1568 t.Errorf("int16(-1).Int() returned %v", v.Int())
1572 func TestSlice(t *testing.T) {
1573 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
1574 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
1576 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
1579 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
1581 if !DeepEqual(v[0:5], xs[3:]) {
1582 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
1585 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
1586 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
1588 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
1591 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
1593 if !DeepEqual(v[0:6], xa[2:]) {
1594 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
1598 func TestVariadic(t *testing.T) {
1603 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
1604 if b.String() != "hello, 42 world" {
1605 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
1609 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
1610 if b.String() != "hello, 42 world" {
1611 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
1615 var tagGetTests = []struct {
1620 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
1621 {`protobuf:"PB(1,2)"`, `foo`, ``},
1622 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
1623 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
1624 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
1627 func TestTagGet(t *testing.T) {
1628 for _, tt := range tagGetTests {
1629 if v := tt.Tag.Get(tt.Key); v != tt.Value {
1630 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
1635 func TestBytes(t *testing.T) {
1638 y := ValueOf(x).Bytes()
1639 if !bytes.Equal(x, y) {
1640 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
1643 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
1647 func TestSetBytes(t *testing.T) {
1650 y := []byte{1, 2, 3, 4}
1651 ValueOf(&x).Elem().SetBytes(y)
1652 if !bytes.Equal(x, y) {
1653 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
1656 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
1660 type Private struct {
1665 func (p *Private) m() {
1668 type Public struct {
1673 func (p *Public) M() {
1676 func TestUnexported(t *testing.T) {
1679 isValid(v.Elem().Field(0))
1680 isValid(v.Elem().Field(1))
1681 isValid(v.Elem().FieldByName("X"))
1682 isValid(v.Elem().FieldByName("Y"))
1683 isValid(v.Type().Method(0).Func)
1684 isNonNil(v.Elem().Field(0).Interface())
1685 isNonNil(v.Elem().Field(1).Interface())
1686 isNonNil(v.Elem().FieldByName("X").Interface())
1687 isNonNil(v.Elem().FieldByName("Y").Interface())
1688 isNonNil(v.Type().Method(0).Func.Interface())
1692 isValid(v.Elem().Field(0))
1693 isValid(v.Elem().Field(1))
1694 isValid(v.Elem().FieldByName("x"))
1695 isValid(v.Elem().FieldByName("y"))
1696 isValid(v.Type().Method(0).Func)
1697 shouldPanic(func() { v.Elem().Field(0).Interface() })
1698 shouldPanic(func() { v.Elem().Field(1).Interface() })
1699 shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
1700 shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
1701 shouldPanic(func() { v.Type().Method(0).Func.Interface() })
1704 func shouldPanic(f func()) {
1706 if recover() == nil {
1707 panic("did not panic")
1713 func isNonNil(x interface{}) {
1715 panic("nil interface")
1719 func isValid(v Value) {