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.
32 func isDigit(c uint8) bool { return '0' <= c && c <= '9' }
34 func assert(t *testing.T, s, want string) {
36 t.Errorf("have %#q want %#q", s, want)
40 func typestring(i interface{}) string { return TypeOf(i).String() }
42 var typeTests = []pair{
43 {struct{ x int }{}, "int"},
44 {struct{ x int8 }{}, "int8"},
45 {struct{ x int16 }{}, "int16"},
46 {struct{ x int32 }{}, "int32"},
47 {struct{ x int64 }{}, "int64"},
48 {struct{ x uint }{}, "uint"},
49 {struct{ x uint8 }{}, "uint8"},
50 {struct{ x uint16 }{}, "uint16"},
51 {struct{ x uint32 }{}, "uint32"},
52 {struct{ x uint64 }{}, "uint64"},
53 {struct{ x float32 }{}, "float32"},
54 {struct{ x float64 }{}, "float64"},
55 {struct{ x int8 }{}, "int8"},
56 {struct{ x (**int8) }{}, "**int8"},
57 {struct{ x (**integer) }{}, "**reflect_test.integer"},
58 {struct{ x ([32]int32) }{}, "[32]int32"},
59 {struct{ x ([]int8) }{}, "[]int8"},
60 {struct{ x (map[string]int32) }{}, "map[string] int32"},
61 {struct{ x (chan<- string) }{}, "chan<- string"},
68 "struct { c chan *int32; d float32 }",
70 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
73 c func(chan *integer, *int8)
76 "struct { c func(chan *reflect_test.integer, *int8) }",
84 "struct { a int8; b int32 }",
93 "struct { a int8; b int8; c int32 }",
103 "struct { a int8; b int8; c int8; d int32 }",
114 "struct { a int8; b int8; c int8; d int8; e int32 }",
126 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
130 a int8 `reflect:"hi there"`
133 `struct { a int8 "reflect:\"hi there\"" }`,
137 a int8 `reflect:"hi \x00there\t\n\"\\"`
140 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
147 "struct { f func(...int) }",
151 a(func(func(int) int) func(func(int)) int)
155 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
159 var valueTests = []pair{
168 {new(float32), "256.25"},
169 {new(float64), "512.125"},
170 {new(string), "stringy cheese"},
172 {new(*int8), "*int8(0)"},
173 {new(**int8), "**int8(0)"},
174 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
175 {new(**integer), "**reflect_test.integer(0)"},
176 {new(map[string]int32), "map[string] int32{<can't iterate on maps>}"},
177 {new(chan<- string), "chan<- string"},
178 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
183 "struct { c chan *int32; d float32 }{chan *int32, 0}",
185 {new(struct{ c func(chan *integer, *int8) }),
186 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
192 "struct { a int8; b int32 }{0, 0}",
199 "struct { a int8; b int8; c int32 }{0, 0, 0}",
203 func testType(t *testing.T, i int, typ Type, want string) {
206 t.Errorf("#%d: have %#q, want %#q", i, s, want)
210 func TestTypes(t *testing.T) {
211 for i, tt := range typeTests {
212 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
216 func TestSet(t *testing.T) {
217 for i, tt := range valueTests {
218 v := ValueOf(tt.i).Elem()
245 v.SetComplex(532.125 + 10i)
247 v.SetComplex(564.25 + 1i)
249 v.SetString("stringy cheese")
253 s := valueToString(v)
255 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
260 func TestSetValue(t *testing.T) {
261 for i, tt := range valueTests {
262 v := ValueOf(tt.i).Elem()
265 v.Set(ValueOf(int(132)))
267 v.Set(ValueOf(int8(8)))
269 v.Set(ValueOf(int16(16)))
271 v.Set(ValueOf(int32(32)))
273 v.Set(ValueOf(int64(64)))
275 v.Set(ValueOf(uint(132)))
277 v.Set(ValueOf(uint8(8)))
279 v.Set(ValueOf(uint16(16)))
281 v.Set(ValueOf(uint32(32)))
283 v.Set(ValueOf(uint64(64)))
285 v.Set(ValueOf(float32(256.25)))
287 v.Set(ValueOf(512.125))
289 v.Set(ValueOf(complex64(532.125 + 10i)))
291 v.Set(ValueOf(complex128(564.25 + 1i)))
293 v.Set(ValueOf("stringy cheese"))
297 s := valueToString(v)
299 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
306 var valueToStringTests = []pair{
311 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
312 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
313 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
314 {&[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})"},
315 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
316 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
319 func TestValueToString(t *testing.T) {
320 for i, test := range valueToStringTests {
321 s := valueToString(ValueOf(test.i))
323 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
328 func TestArrayElemSet(t *testing.T) {
329 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
330 v.Index(4).SetInt(123)
331 s := valueToString(v)
332 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
334 t.Errorf("[10]int: have %#q want %#q", s, want)
337 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
338 v.Index(4).SetInt(123)
340 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
342 t.Errorf("[]int: have %#q want %#q", s, want1)
346 func TestPtrPointTo(t *testing.T) {
350 vi := ValueOf(&i).Elem()
351 vip.Elem().Set(vi.Addr())
353 t.Errorf("got %d, want 1234", *ip)
357 vp := ValueOf(&ip).Elem()
358 vp.Set(Zero(vp.Type()))
360 t.Errorf("got non-nil (%p), want nil", ip)
364 func TestPtrSetNil(t *testing.T) {
368 vip.Elem().Set(Zero(vip.Elem().Type()))
370 t.Errorf("got non-nil (%d), want nil", *ip)
374 func TestMapSetNil(t *testing.T) {
375 m := make(map[string]int)
377 vm.Elem().Set(Zero(vm.Elem().Type()))
379 t.Errorf("got non-nil (%p), want nil", m)
383 func TestAll(t *testing.T) {
384 testType(t, 1, TypeOf((int8)(0)), "int8")
385 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
387 typ := TypeOf((*struct {
391 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
393 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
396 testType(t, 5, f.Type, "chan *int32")
398 f, present := styp.FieldByName("d")
400 t.Errorf("FieldByName says present field is absent")
402 testType(t, 6, f.Type, "float32")
404 f, present = styp.FieldByName("absent")
406 t.Errorf("FieldByName says absent field is present")
409 typ = TypeOf([32]int32{})
410 testType(t, 7, typ, "[32]int32")
411 testType(t, 8, typ.Elem(), "int32")
413 typ = TypeOf((map[string]*int32)(nil))
414 testType(t, 9, typ, "map[string] *int32")
416 testType(t, 10, mtyp.Key(), "string")
417 testType(t, 11, mtyp.Elem(), "*int32")
419 typ = TypeOf((chan<- string)(nil))
420 testType(t, 12, typ, "chan<- string")
421 testType(t, 13, typ.Elem(), "string")
423 // make sure tag strings are not part of element type
424 typ = TypeOf(struct {
425 d []uint32 `reflect:"TAG"`
427 testType(t, 14, typ, "[]uint32")
430 func TestInterfaceGet(t *testing.T) {
435 v1 := ValueOf(&inter)
436 v2 := v1.Elem().Field(0)
437 assert(t, v2.Type().String(), "interface { }")
440 assert(t, v3.Type().String(), "float64")
443 func TestInterfaceValue(t *testing.T) {
448 v1 := ValueOf(&inter)
449 v2 := v1.Elem().Field(0)
450 assert(t, v2.Type().String(), "interface { }")
452 assert(t, v3.Type().String(), "float64")
455 if _, ok := i3.(float64); !ok {
456 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
460 func TestFunctionValue(t *testing.T) {
461 var x interface{} = func() {}
463 if v.Interface() != v.Interface() || v.Interface() != x {
464 t.Fatalf("TestFunction != itself")
466 assert(t, v.Type().String(), "func()")
469 var appendTests = []struct {
472 {make([]int, 2, 4), []int{22}},
473 {make([]int, 2, 4), []int{22, 33, 44}},
476 func sameInts(x, y []int) bool {
477 if len(x) != len(y) {
480 for i, xx := range x {
488 func TestAppend(t *testing.T) {
489 for i, test := range appendTests {
490 origLen, extraLen := len(test.orig), len(test.extra)
491 want := append(test.orig, test.extra...)
492 // Convert extra from []int to []Value.
493 e0 := make([]Value, len(test.extra))
494 for j, e := range test.extra {
497 // Convert extra from []int to *SliceValue.
498 e1 := ValueOf(test.extra)
500 a0 := ValueOf(test.orig)
501 have0 := Append(a0, e0...).Interface().([]int)
502 if !sameInts(have0, want) {
503 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
505 // Check that the orig and extra slices were not modified.
506 if len(test.orig) != origLen {
507 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
509 if len(test.extra) != extraLen {
510 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
513 a1 := ValueOf(test.orig)
514 have1 := AppendSlice(a1, e1).Interface().([]int)
515 if !sameInts(have1, want) {
516 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
518 // Check that the orig and extra slices were not modified.
519 if len(test.orig) != origLen {
520 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
522 if len(test.extra) != extraLen {
523 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
528 func TestCopy(t *testing.T) {
529 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
530 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
531 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
532 for i := 0; i < len(b); i++ {
534 t.Fatalf("b != c before test")
539 aa := ValueOf(&a1).Elem()
540 ab := ValueOf(&b1).Elem()
541 for tocopy := 1; tocopy <= 7; tocopy++ {
545 for i := 0; i < tocopy; i++ {
547 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
548 tocopy, i, a[i], i, b[i])
551 for i := tocopy; i < len(b); i++ {
554 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
555 tocopy, i, a[i], i, b[i], i, c[i])
557 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
558 tocopy, i, b[i], i, c[i])
561 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
567 func TestCopyArray(t *testing.T) {
568 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
569 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
571 aa := ValueOf(&a).Elem()
572 ab := ValueOf(&b).Elem()
574 for i := 0; i < len(a); i++ {
576 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
579 for i := len(a); i < len(b); i++ {
581 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
583 t.Logf("elem %d is okay\n", i)
588 func TestBigUnnamedStruct(t *testing.T) {
589 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
591 b1 := v.Interface().(struct {
594 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
595 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
603 func TestBigStruct(t *testing.T) {
604 b := big{1, 2, 3, 4, 5}
606 b1 := v.Interface().(big)
607 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
608 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
619 type DeepEqualTest struct {
624 var deepEqualTests = []DeepEqualTest{
627 {int32(1), int32(1), true},
629 {float32(0.5), float32(0.5), true},
630 {"hello", "hello", true},
631 {make([]int, 10), make([]int, 10), true},
632 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
633 {Basic{1, 0.5}, Basic{1, 0.5}, true},
634 {os.Error(nil), os.Error(nil), true},
635 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
639 {int32(1), int32(2), false},
641 {float32(0.5), float32(0.6), false},
642 {"hello", "hey", false},
643 {make([]int, 10), make([]int, 11), false},
644 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
645 {Basic{1, 0.5}, Basic{1, 0.6}, false},
646 {Basic{1, 0}, Basic{2, 0}, false},
647 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
648 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
649 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
650 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
656 {int32(1), int64(1), false},
657 {0.5, "hello", false},
658 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
659 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
660 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
661 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
664 func TestDeepEqual(t *testing.T) {
665 for _, test := range deepEqualTests {
666 if r := DeepEqual(test.a, test.b); r != test.eq {
667 t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
672 func TestTypeOf(t *testing.T) {
673 for _, test := range deepEqualTests {
678 typ := TypeOf(test.a)
680 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
685 type Recursive struct {
690 func TestDeepEqualRecursiveStruct(t *testing.T) {
691 a, b := new(Recursive), new(Recursive)
692 *a = Recursive{12, a}
693 *b = Recursive{12, b}
694 if !DeepEqual(a, b) {
695 t.Error("DeepEqual(recursive same) = false, want true")
699 type _Complex struct {
703 d map[float64]float64
706 func TestDeepEqualComplexStruct(t *testing.T) {
707 m := make(map[float64]float64)
708 stra, strb := "hello", "hello"
709 a, b := new(_Complex), new(_Complex)
710 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
711 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
712 if !DeepEqual(a, b) {
713 t.Error("DeepEqual(complex same) = false, want true")
717 func TestDeepEqualComplexStructInequality(t *testing.T) {
718 m := make(map[float64]float64)
719 stra, strb := "hello", "helloo" // Difference is here
720 a, b := new(_Complex), new(_Complex)
721 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
722 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
724 t.Error("DeepEqual(complex different) = true, want false")
732 func TestDeepEqualUnexportedMap(t *testing.T) {
733 // Check that DeepEqual can look at unexported fields.
734 x1 := UnexpT{map[int]int{1: 2}}
735 x2 := UnexpT{map[int]int{1: 2}}
736 if !DeepEqual(&x1, &x2) {
737 t.Error("DeepEqual(x1, x2) = false, want true")
740 y1 := UnexpT{map[int]int{2: 3}}
741 if DeepEqual(&x1, &y1) {
742 t.Error("DeepEqual(x1, y1) = true, want false")
746 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
748 f := s.Type().Field(1)
749 if f.Offset != offs {
750 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
754 // Check that structure alignment & offsets viewed through reflect agree with those
755 // from the compiler itself.
756 func TestAlignment(t *testing.T) {
757 type T1inner struct {
764 type T2inner struct {
772 x := T1{T1inner{2}, 17}
773 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
775 x1 := T2{T2inner{2, 3}, 17}
776 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
779 func Nil(a interface{}, t *testing.T) {
780 n := ValueOf(a).Field(0)
782 t.Errorf("%v should be nil", a)
786 func NotNil(a interface{}, t *testing.T) {
787 n := ValueOf(a).Field(0)
789 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
793 func TestIsNil(t *testing.T) {
794 // These implement IsNil.
795 // Wrap in extra struct to hide interface type.
796 doNil := []interface{}{
798 struct{ x interface{} }{},
799 struct{ x map[string]int }{},
800 struct{ x func() bool }{},
801 struct{ x chan int }{},
802 struct{ x []string }{},
804 for _, ts := range doNil {
805 ty := TypeOf(ts).Field(0).Type
807 v.IsNil() // panics if not okay to call
810 // Check the implementations
822 si.x = make([]int, 10)
829 ci.x = make(chan int)
836 mi.x = make(map[int]int)
854 func TestInterfaceExtraction(t *testing.T) {
860 v := Indirect(ValueOf(&s)).Field(0).Interface()
861 if v != s.W.(interface{}) {
862 t.Error("Interface() on interface: ", v, s.W)
866 func TestNilPtrValueSub(t *testing.T) {
868 if pv := ValueOf(pi); pv.Elem().IsValid() {
869 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
873 func TestMap(t *testing.T) {
874 m := map[string]int{"a": 1, "b": 2}
876 if n := mv.Len(); n != len(m) {
877 t.Errorf("Len = %d, want %d", n, len(m))
881 newmap := MakeMap(mv.Type())
882 for k, v := range m {
883 // Check that returned Keys match keys in range.
884 // These aren't required to be in the same order,
885 // but they are in this implementation, which makes
888 t.Errorf("Missing key #%d %q", i, k)
889 } else if kv := keys[i]; kv.String() != k {
890 t.Errorf("Keys[%q] = %d, want %d", i, kv.Int(), k)
894 // Check that value lookup is correct.
895 vv := mv.MapIndex(ValueOf(k))
896 if vi := vv.Int(); vi != int64(v) {
897 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
900 // Copy into new map.
901 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
903 vv := mv.MapIndex(ValueOf("not-present"))
905 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
908 newm := newmap.Interface().(map[string]int)
909 if len(newm) != len(m) {
910 t.Errorf("length after copy: newm=%d, m=%d", newm, m)
913 for k, v := range newm {
916 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
920 newmap.SetMapIndex(ValueOf("a"), Value{})
923 t.Errorf("newm[\"a\"] = %d after delete", v)
926 mv = ValueOf(&m).Elem()
927 mv.Set(Zero(mv.Type()))
929 t.Errorf("mv.Set(nil) failed")
933 func TestChan(t *testing.T) {
934 for loop := 0; loop < 2; loop++ {
938 // check both ways to allocate channels
941 c = make(chan int, 1)
944 cv = MakeChan(TypeOf(c), 1)
945 c = cv.Interface().(chan int)
950 if i := <-c; i != 2 {
951 t.Errorf("reflect Send 2, native recv %d", i)
956 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
957 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
961 val, ok := cv.TryRecv()
962 if val.IsValid() || ok {
963 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
968 val, ok = cv.TryRecv()
970 t.Errorf("TryRecv on ready chan got nil")
971 } else if i := val.Int(); i != 4 || !ok {
972 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
977 ok = cv.TrySend(ValueOf(5))
980 t.Errorf("TrySend on full chan succeeded: value %d", i)
984 ok = cv.TrySend(ValueOf(6))
986 t.Errorf("TrySend on empty chan failed")
989 t.Errorf("TrySend 6, recv %d", i)
996 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
997 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
999 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1000 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1004 // check creation of unbuffered channel
1006 cv := MakeChan(TypeOf(c), 0)
1007 c = cv.Interface().(chan int)
1008 if cv.TrySend(ValueOf(7)) {
1009 t.Errorf("TrySend on sync chan succeeded")
1011 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1012 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1016 cv = MakeChan(TypeOf(c), 10)
1017 c = cv.Interface().(chan int)
1018 for i := 0; i < 3; i++ {
1021 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1022 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1027 // Difficult test for function call because of
1028 // implicit padding between arguments.
1029 func dummy(b byte, c int, d byte) (i byte, j int, k byte) {
1033 func TestFunc(t *testing.T) {
1034 ret := ValueOf(dummy).Call([]Value{ValueOf(byte(10)), ValueOf(20), ValueOf(byte(30))})
1036 t.Fatalf("Call returned %d values, want 3", len(ret))
1039 i := byte(ret[0].Uint())
1040 j := int(ret[1].Int())
1041 k := byte(ret[2].Uint())
1042 if i != 10 || j != 20 || k != 30 {
1043 t.Errorf("Call returned %d, %d, %d; want 10, 20, 30", i, j, k)
1051 // This will be index 0.
1052 func (p Point) AnotherMethod(scale int) int {
1056 // This will be index 1.
1057 func (p Point) Dist(scale int) int {
1058 // println("Point.Dist", p.x, p.y, scale)
1059 return p.x*p.x*scale + p.y*p.y*scale
1062 func TestMethod(t *testing.T) {
1063 // Non-curried method of type.
1065 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1067 t.Errorf("Type Method returned %d; want 250", i)
1070 m, ok := TypeOf(p).MethodByName("Dist")
1072 t.Fatalf("method by name failed")
1074 m.Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1076 t.Errorf("Type MethodByName returned %d; want 250", i)
1079 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(10)})[0].Int()
1081 t.Errorf("Pointer Type Method returned %d; want 250", i)
1084 m, ok = TypeOf(&p).MethodByName("Dist")
1086 t.Fatalf("ptr method by name failed")
1088 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(10)})[0].Int()
1090 t.Errorf("Pointer Type MethodByName returned %d; want 250", i)
1093 // Curried method of value.
1094 i = ValueOf(p).Method(1).Call([]Value{ValueOf(10)})[0].Int()
1096 t.Errorf("Value Method returned %d; want 250", i)
1098 i = ValueOf(p).MethodByName("Dist").Call([]Value{ValueOf(10)})[0].Int()
1100 t.Errorf("Value MethodByName returned %d; want 250", i)
1103 // Curried method of pointer.
1104 i = ValueOf(&p).Method(1).Call([]Value{ValueOf(10)})[0].Int()
1106 t.Errorf("Pointer Value Method returned %d; want 250", i)
1108 i = ValueOf(&p).MethodByName("Dist").Call([]Value{ValueOf(10)})[0].Int()
1110 t.Errorf("Pointer Value MethodByName returned %d; want 250", i)
1113 // Curried method of interface value.
1114 // Have to wrap interface value in a struct to get at it.
1115 // Passing it to ValueOf directly would
1116 // access the underlying Point, not the interface.
1122 pv := ValueOf(s).Field(0)
1123 i = pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
1125 t.Errorf("Interface Method returned %d; want 250", i)
1127 i = pv.MethodByName("Dist").Call([]Value{ValueOf(10)})[0].Int()
1129 t.Errorf("Interface MethodByName returned %d; want 250", i)
1133 func TestInterfaceSet(t *testing.T) {
1142 sv := ValueOf(&s).Elem()
1143 sv.Field(0).Set(ValueOf(p))
1144 if q := s.I.(*Point); q != p {
1145 t.Errorf("i: have %p want %p", q, p)
1150 if q := s.P.(*Point); q != p {
1151 t.Errorf("i: have %p want %p", q, p)
1154 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
1156 t.Errorf("Interface Method returned %d; want 250", i)
1165 func TestAnonymousFields(t *testing.T) {
1166 var field StructField
1170 if field, ok = type1.FieldByName("int"); !ok {
1171 t.Error("no field 'int'")
1173 if field.Index[0] != 1 {
1174 t.Error("field index should be 1; is", field.Index)
1228 var fieldTests = []FTest{
1229 {struct{}{}, "", nil, 0},
1230 {struct{}{}, "Foo", nil, 0},
1231 {S0{A: 'a'}, "A", []int{0}, 'a'},
1232 {S0{}, "D", nil, 0},
1233 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
1234 {S1{B: 'b'}, "B", []int{0}, 'b'},
1235 {S1{}, "S0", []int{1}, 0},
1236 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
1237 {S2{A: 'a'}, "A", []int{0}, 'a'},
1238 {S2{}, "S1", []int{1}, 0},
1239 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
1240 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
1241 {S2{}, "D", nil, 0},
1242 {S3{}, "S1", nil, 0},
1243 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
1244 {S3{}, "B", nil, 0},
1245 {S3{D: 'd'}, "D", []int{2}, 0},
1246 {S3{E: 'e'}, "E", []int{3}, 'e'},
1247 {S4{A: 'a'}, "A", []int{1}, 'a'},
1248 {S4{}, "B", nil, 0},
1251 func TestFieldByIndex(t *testing.T) {
1252 for _, test := range fieldTests {
1254 f := s.FieldByIndex(test.index)
1256 if test.index != nil {
1257 if f.Name != test.name {
1258 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
1261 t.Errorf("%s.%s found", s.Name(), f.Name)
1263 } else if len(test.index) > 0 {
1264 t.Errorf("%s.%s not found", s.Name(), test.name)
1267 if test.value != 0 {
1268 v := ValueOf(test.s).FieldByIndex(test.index)
1270 if x, ok := v.Interface().(int); ok {
1271 if x != test.value {
1272 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
1275 t.Errorf("%s%v value not an int", s.Name(), test.index)
1278 t.Errorf("%s%v value not found", s.Name(), test.index)
1284 func TestFieldByName(t *testing.T) {
1285 for _, test := range fieldTests {
1287 f, found := s.FieldByName(test.name)
1289 if test.index != nil {
1290 // Verify field depth and index.
1291 if len(f.Index) != len(test.index) {
1292 t.Errorf("%s.%s depth %d; want %d", s.Name(), test.name, len(f.Index), len(test.index))
1294 for i, x := range f.Index {
1295 if x != test.index[i] {
1296 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
1301 t.Errorf("%s.%s found", s.Name(), f.Name)
1303 } else if len(test.index) > 0 {
1304 t.Errorf("%s.%s not found", s.Name(), test.name)
1307 if test.value != 0 {
1308 v := ValueOf(test.s).FieldByName(test.name)
1310 if x, ok := v.Interface().(int); ok {
1311 if x != test.value {
1312 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
1315 t.Errorf("%s.%s value not an int", s.Name(), test.name)
1318 t.Errorf("%s.%s value not found", s.Name(), test.name)
1324 func TestImportPath(t *testing.T) {
1325 if path := TypeOf(vector.Vector{}).PkgPath(); path != "libgo_container.vector" {
1326 t.Errorf("TypeOf(vector.Vector{}).PkgPath() = %q, want \"libgo_container.vector\"", path)
1330 func TestVariadicType(t *testing.T) {
1331 // Test example from Type documentation.
1332 var f func(x int, y ...float64)
1334 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
1336 if sl.Kind() == Slice {
1337 if sl.Elem() == TypeOf(0.0) {
1345 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
1346 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
1347 for i := 0; i < typ.NumIn(); i++ {
1348 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
1362 func (*inner) m() {}
1363 func (*outer) m() {}
1365 func TestNestedMethods(t *testing.T) {
1366 typ := TypeOf((*outer)(nil))
1367 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
1368 t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
1369 for i := 0; i < typ.NumMethod(); i++ {
1371 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
1376 type InnerInt struct {
1380 type OuterInt struct {
1385 func (i *InnerInt) M() int {
1389 func TestEmbeddedMethods(t *testing.T) {
1390 typ := TypeOf((*OuterInt)(nil))
1391 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
1392 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
1393 for i := 0; i < typ.NumMethod(); i++ {
1395 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
1400 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
1401 t.Errorf("i.M() = %d, want 3", v)
1404 o := &OuterInt{1, InnerInt{2}}
1405 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
1406 t.Errorf("i.M() = %d, want 2", v)
1410 if v := f(o); v != 2 {
1411 t.Errorf("f(o) = %d, want 2", v)
1415 func TestPtrTo(t *testing.T) {
1419 for i = 0; i < 100; i++ {
1422 for i = 0; i < 100; i++ {
1425 if typ != TypeOf(i) {
1426 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
1430 func TestAddr(t *testing.T) {
1442 t.Errorf("Addr.Elem.Set failed to set value")
1445 // Again but take address of the ValueOf value.
1446 // Exercises generation of PtrTypes not present in the binary.
1448 v = ValueOf(&q).Elem()
1457 t.Errorf("Addr.Elem.Set failed to set value")
1460 // Starting without pointer we should get changed value
1463 v = ValueOf(&qq).Elem()
1469 if p.X != 3 { // should be unchanged from last time
1470 t.Errorf("somehow value Set changed original p")
1472 p = v0.Interface().(struct {
1476 t.Errorf("Addr.Elem.Set valued to set value in top value")
1480 /* gccgo does do allocations here.
1482 func noAlloc(t *testing.T, n int, f func(int)) {
1483 // once to prime everything
1485 runtime.MemStats.Mallocs = 0
1487 for j := 0; j < n; j++ {
1490 // A few allocs may happen in the testing package when GOMAXPROCS > 1, so don't
1491 // require zero mallocs.
1492 if runtime.MemStats.Mallocs > 5 {
1493 t.Fatalf("%d mallocs after %d iterations", runtime.MemStats.Mallocs, n)
1497 func TestAllocations(t *testing.T) {
1498 noAlloc(t, 100, func(j int) {
1503 if int(v.Int()) != 42+j {
1511 func TestSmallNegativeInt(t *testing.T) {
1515 t.Errorf("int16(-1).Int() returned %v", v.Int())
1519 func TestSlice(t *testing.T) {
1520 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
1521 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
1522 if len(v) != 2 || v[0] != 4 || v[1] != 5 {
1523 t.Errorf("xs.Slice(3, 5) = %v", v)
1526 xa := [7]int{10, 20, 30, 40, 50, 60, 70}
1527 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
1528 if len(v) != 3 || v[0] != 30 || v[1] != 40 || v[2] != 50 {
1529 t.Errorf("xa.Slice(2, 5) = %v", v)
1533 func TestVariadic(t *testing.T) {
1538 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
1539 if b.String() != "hello, 42 world" {
1540 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
1544 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
1545 if b.String() != "hello, 42 world" {
1546 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
1550 var tagGetTests = []struct {
1555 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
1556 {`protobuf:"PB(1,2)"`, `foo`, ``},
1557 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
1558 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
1559 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
1562 func TestTagGet(t *testing.T) {
1563 for _, tt := range tagGetTests {
1564 if v := tt.Tag.Get(tt.Key); v != tt.Value {
1565 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
1570 type Private struct {
1575 func (p *Private) m() {
1578 type Public struct {
1583 func (p *Public) M() {
1586 func TestUnexported(t *testing.T) {
1589 isValid(v.Elem().Field(0))
1590 isValid(v.Elem().Field(1))
1591 isValid(v.Elem().FieldByName("X"))
1592 isValid(v.Elem().FieldByName("Y"))
1593 isValid(v.Type().Method(0).Func)
1594 isNonNil(v.Elem().Field(0).Interface())
1595 isNonNil(v.Elem().Field(1).Interface())
1596 isNonNil(v.Elem().FieldByName("X").Interface())
1597 isNonNil(v.Elem().FieldByName("Y").Interface())
1598 isNonNil(v.Type().Method(0).Func.Interface())
1602 isValid(v.Elem().Field(0))
1603 isValid(v.Elem().Field(1))
1604 isValid(v.Elem().FieldByName("x"))
1605 isValid(v.Elem().FieldByName("y"))
1606 isValid(v.Type().Method(0).Func)
1607 shouldPanic(func() { v.Elem().Field(0).Interface() })
1608 shouldPanic(func() { v.Elem().Field(1).Interface() })
1609 shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
1610 shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
1611 shouldPanic(func() { v.Type().Method(0).Func.Interface() })
1614 func shouldPanic(f func()) {
1616 if recover() == nil {
1617 panic("did not panic")
1623 func isNonNil(x interface{}) {
1625 panic("nil interface")
1629 func isValid(v Value) {