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))
880 newmap := MakeMap(mv.Type())
881 for k, v := range m {
882 // Check that returned Keys match keys in range.
883 // These aren't required to be in the same order.
885 for _, kv := range keys {
886 if kv.String() == k {
892 t.Errorf("Missing key %q", k)
895 // Check that value lookup is correct.
896 vv := mv.MapIndex(ValueOf(k))
897 if vi := vv.Int(); vi != int64(v) {
898 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
901 // Copy into new map.
902 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
904 vv := mv.MapIndex(ValueOf("not-present"))
906 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
909 newm := newmap.Interface().(map[string]int)
910 if len(newm) != len(m) {
911 t.Errorf("length after copy: newm=%d, m=%d", newm, m)
914 for k, v := range newm {
917 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
921 newmap.SetMapIndex(ValueOf("a"), Value{})
924 t.Errorf("newm[\"a\"] = %d after delete", v)
927 mv = ValueOf(&m).Elem()
928 mv.Set(Zero(mv.Type()))
930 t.Errorf("mv.Set(nil) failed")
934 func TestChan(t *testing.T) {
935 for loop := 0; loop < 2; loop++ {
939 // check both ways to allocate channels
942 c = make(chan int, 1)
945 cv = MakeChan(TypeOf(c), 1)
946 c = cv.Interface().(chan int)
951 if i := <-c; i != 2 {
952 t.Errorf("reflect Send 2, native recv %d", i)
957 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
958 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
962 val, ok := cv.TryRecv()
963 if val.IsValid() || ok {
964 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
969 val, ok = cv.TryRecv()
971 t.Errorf("TryRecv on ready chan got nil")
972 } else if i := val.Int(); i != 4 || !ok {
973 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
978 ok = cv.TrySend(ValueOf(5))
981 t.Errorf("TrySend on full chan succeeded: value %d", i)
985 ok = cv.TrySend(ValueOf(6))
987 t.Errorf("TrySend on empty chan failed")
990 t.Errorf("TrySend 6, recv %d", i)
997 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
998 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1000 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1001 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1005 // check creation of unbuffered channel
1007 cv := MakeChan(TypeOf(c), 0)
1008 c = cv.Interface().(chan int)
1009 if cv.TrySend(ValueOf(7)) {
1010 t.Errorf("TrySend on sync chan succeeded")
1012 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1013 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1017 cv = MakeChan(TypeOf(c), 10)
1018 c = cv.Interface().(chan int)
1019 for i := 0; i < 3; i++ {
1022 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1023 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1028 // Difficult test for function call because of
1029 // implicit padding between arguments.
1030 func dummy(b byte, c int, d byte) (i byte, j int, k byte) {
1034 func TestFunc(t *testing.T) {
1035 ret := ValueOf(dummy).Call([]Value{ValueOf(byte(10)), ValueOf(20), ValueOf(byte(30))})
1037 t.Fatalf("Call returned %d values, want 3", len(ret))
1040 i := byte(ret[0].Uint())
1041 j := int(ret[1].Int())
1042 k := byte(ret[2].Uint())
1043 if i != 10 || j != 20 || k != 30 {
1044 t.Errorf("Call returned %d, %d, %d; want 10, 20, 30", i, j, k)
1052 // This will be index 0.
1053 func (p Point) AnotherMethod(scale int) int {
1057 // This will be index 1.
1058 func (p Point) Dist(scale int) int {
1059 // println("Point.Dist", p.x, p.y, scale)
1060 return p.x*p.x*scale + p.y*p.y*scale
1063 func TestMethod(t *testing.T) {
1064 // Non-curried method of type.
1066 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1068 t.Errorf("Type Method returned %d; want 250", i)
1071 m, ok := TypeOf(p).MethodByName("Dist")
1073 t.Fatalf("method by name failed")
1075 m.Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1077 t.Errorf("Type MethodByName returned %d; want 250", i)
1080 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(10)})[0].Int()
1082 t.Errorf("Pointer Type Method returned %d; want 250", i)
1085 m, ok = TypeOf(&p).MethodByName("Dist")
1087 t.Fatalf("ptr method by name failed")
1089 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(10)})[0].Int()
1091 t.Errorf("Pointer Type MethodByName returned %d; want 250", i)
1094 // Curried method of value.
1095 i = ValueOf(p).Method(1).Call([]Value{ValueOf(10)})[0].Int()
1097 t.Errorf("Value Method returned %d; want 250", i)
1099 i = ValueOf(p).MethodByName("Dist").Call([]Value{ValueOf(10)})[0].Int()
1101 t.Errorf("Value MethodByName returned %d; want 250", i)
1104 // Curried method of pointer.
1105 i = ValueOf(&p).Method(1).Call([]Value{ValueOf(10)})[0].Int()
1107 t.Errorf("Pointer Value Method returned %d; want 250", i)
1109 i = ValueOf(&p).MethodByName("Dist").Call([]Value{ValueOf(10)})[0].Int()
1111 t.Errorf("Pointer Value MethodByName returned %d; want 250", i)
1114 // Curried method of interface value.
1115 // Have to wrap interface value in a struct to get at it.
1116 // Passing it to ValueOf directly would
1117 // access the underlying Point, not the interface.
1123 pv := ValueOf(s).Field(0)
1124 i = pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
1126 t.Errorf("Interface Method returned %d; want 250", i)
1128 i = pv.MethodByName("Dist").Call([]Value{ValueOf(10)})[0].Int()
1130 t.Errorf("Interface MethodByName returned %d; want 250", i)
1134 func TestInterfaceSet(t *testing.T) {
1143 sv := ValueOf(&s).Elem()
1144 sv.Field(0).Set(ValueOf(p))
1145 if q := s.I.(*Point); q != p {
1146 t.Errorf("i: have %p want %p", q, p)
1151 if q := s.P.(*Point); q != p {
1152 t.Errorf("i: have %p want %p", q, p)
1155 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
1157 t.Errorf("Interface Method returned %d; want 250", i)
1166 func TestAnonymousFields(t *testing.T) {
1167 var field StructField
1171 if field, ok = type1.FieldByName("int"); !ok {
1172 t.Error("no field 'int'")
1174 if field.Index[0] != 1 {
1175 t.Error("field index should be 1; is", field.Index)
1229 var fieldTests = []FTest{
1230 {struct{}{}, "", nil, 0},
1231 {struct{}{}, "Foo", nil, 0},
1232 {S0{A: 'a'}, "A", []int{0}, 'a'},
1233 {S0{}, "D", nil, 0},
1234 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
1235 {S1{B: 'b'}, "B", []int{0}, 'b'},
1236 {S1{}, "S0", []int{1}, 0},
1237 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
1238 {S2{A: 'a'}, "A", []int{0}, 'a'},
1239 {S2{}, "S1", []int{1}, 0},
1240 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
1241 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
1242 {S2{}, "D", nil, 0},
1243 {S3{}, "S1", nil, 0},
1244 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
1245 {S3{}, "B", nil, 0},
1246 {S3{D: 'd'}, "D", []int{2}, 0},
1247 {S3{E: 'e'}, "E", []int{3}, 'e'},
1248 {S4{A: 'a'}, "A", []int{1}, 'a'},
1249 {S4{}, "B", nil, 0},
1252 func TestFieldByIndex(t *testing.T) {
1253 for _, test := range fieldTests {
1255 f := s.FieldByIndex(test.index)
1257 if test.index != nil {
1258 if f.Name != test.name {
1259 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
1262 t.Errorf("%s.%s found", s.Name(), f.Name)
1264 } else if len(test.index) > 0 {
1265 t.Errorf("%s.%s not found", s.Name(), test.name)
1268 if test.value != 0 {
1269 v := ValueOf(test.s).FieldByIndex(test.index)
1271 if x, ok := v.Interface().(int); ok {
1272 if x != test.value {
1273 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
1276 t.Errorf("%s%v value not an int", s.Name(), test.index)
1279 t.Errorf("%s%v value not found", s.Name(), test.index)
1285 func TestFieldByName(t *testing.T) {
1286 for _, test := range fieldTests {
1288 f, found := s.FieldByName(test.name)
1290 if test.index != nil {
1291 // Verify field depth and index.
1292 if len(f.Index) != len(test.index) {
1293 t.Errorf("%s.%s depth %d; want %d", s.Name(), test.name, len(f.Index), len(test.index))
1295 for i, x := range f.Index {
1296 if x != test.index[i] {
1297 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
1302 t.Errorf("%s.%s found", s.Name(), f.Name)
1304 } else if len(test.index) > 0 {
1305 t.Errorf("%s.%s not found", s.Name(), test.name)
1308 if test.value != 0 {
1309 v := ValueOf(test.s).FieldByName(test.name)
1311 if x, ok := v.Interface().(int); ok {
1312 if x != test.value {
1313 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
1316 t.Errorf("%s.%s value not an int", s.Name(), test.name)
1319 t.Errorf("%s.%s value not found", s.Name(), test.name)
1325 func TestImportPath(t *testing.T) {
1326 if path := TypeOf(&base64.Encoding{}).Elem().PkgPath(); path != "libgo_encoding.base64" {
1327 t.Errorf(`TypeOf(&base64.Encoding{}).Elem().PkgPath() = %q, want "libgo_encoding.base64"`, path)
1331 func TestVariadicType(t *testing.T) {
1332 // Test example from Type documentation.
1333 var f func(x int, y ...float64)
1335 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
1337 if sl.Kind() == Slice {
1338 if sl.Elem() == TypeOf(0.0) {
1346 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
1347 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
1348 for i := 0; i < typ.NumIn(); i++ {
1349 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
1363 func (*inner) m() {}
1364 func (*outer) m() {}
1366 func TestNestedMethods(t *testing.T) {
1367 typ := TypeOf((*outer)(nil))
1368 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
1369 t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
1370 for i := 0; i < typ.NumMethod(); i++ {
1372 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
1377 type InnerInt struct {
1381 type OuterInt struct {
1386 func (i *InnerInt) M() int {
1390 func TestEmbeddedMethods(t *testing.T) {
1391 typ := TypeOf((*OuterInt)(nil))
1392 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
1393 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
1394 for i := 0; i < typ.NumMethod(); i++ {
1396 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
1401 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
1402 t.Errorf("i.M() = %d, want 3", v)
1405 o := &OuterInt{1, InnerInt{2}}
1406 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
1407 t.Errorf("i.M() = %d, want 2", v)
1411 if v := f(o); v != 2 {
1412 t.Errorf("f(o) = %d, want 2", v)
1416 func TestPtrTo(t *testing.T) {
1420 for i = 0; i < 100; i++ {
1423 for i = 0; i < 100; i++ {
1426 if typ != TypeOf(i) {
1427 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
1431 func TestAddr(t *testing.T) {
1443 t.Errorf("Addr.Elem.Set failed to set value")
1446 // Again but take address of the ValueOf value.
1447 // Exercises generation of PtrTypes not present in the binary.
1449 v = ValueOf(&q).Elem()
1458 t.Errorf("Addr.Elem.Set failed to set value")
1461 // Starting without pointer we should get changed value
1464 v = ValueOf(&qq).Elem()
1470 if p.X != 3 { // should be unchanged from last time
1471 t.Errorf("somehow value Set changed original p")
1473 p = v0.Interface().(struct {
1477 t.Errorf("Addr.Elem.Set valued to set value in top value")
1481 /* gccgo does do allocations here.
1483 func noAlloc(t *testing.T, n int, f func(int)) {
1484 // once to prime everything
1486 runtime.MemStats.Mallocs = 0
1488 for j := 0; j < n; j++ {
1491 // A few allocs may happen in the testing package when GOMAXPROCS > 1, so don't
1492 // require zero mallocs.
1493 if runtime.MemStats.Mallocs > 5 {
1494 t.Fatalf("%d mallocs after %d iterations", runtime.MemStats.Mallocs, n)
1498 func TestAllocations(t *testing.T) {
1499 noAlloc(t, 100, func(j int) {
1504 if int(v.Int()) != 42+j {
1512 func TestSmallNegativeInt(t *testing.T) {
1516 t.Errorf("int16(-1).Int() returned %v", v.Int())
1520 func TestSlice(t *testing.T) {
1521 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
1522 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
1523 if len(v) != 2 || v[0] != 4 || v[1] != 5 {
1524 t.Errorf("xs.Slice(3, 5) = %v", v)
1527 xa := [7]int{10, 20, 30, 40, 50, 60, 70}
1528 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
1529 if len(v) != 3 || v[0] != 30 || v[1] != 40 || v[2] != 50 {
1530 t.Errorf("xa.Slice(2, 5) = %v", v)
1534 func TestVariadic(t *testing.T) {
1539 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
1540 if b.String() != "hello, 42 world" {
1541 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
1545 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
1546 if b.String() != "hello, 42 world" {
1547 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
1551 var tagGetTests = []struct {
1556 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
1557 {`protobuf:"PB(1,2)"`, `foo`, ``},
1558 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
1559 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
1560 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
1563 func TestTagGet(t *testing.T) {
1564 for _, tt := range tagGetTests {
1565 if v := tt.Tag.Get(tt.Key); v != tt.Value {
1566 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
1571 func TestBytes(t *testing.T) {
1574 y := ValueOf(x).Bytes()
1575 if !bytes.Equal(x, y) {
1576 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
1579 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
1583 func TestSetBytes(t *testing.T) {
1586 y := []byte{1, 2, 3, 4}
1587 ValueOf(&x).Elem().SetBytes(y)
1588 if !bytes.Equal(x, y) {
1589 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
1592 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
1596 type Private struct {
1601 func (p *Private) m() {
1604 type Public struct {
1609 func (p *Public) M() {
1612 func TestUnexported(t *testing.T) {
1615 isValid(v.Elem().Field(0))
1616 isValid(v.Elem().Field(1))
1617 isValid(v.Elem().FieldByName("X"))
1618 isValid(v.Elem().FieldByName("Y"))
1619 isValid(v.Type().Method(0).Func)
1620 isNonNil(v.Elem().Field(0).Interface())
1621 isNonNil(v.Elem().Field(1).Interface())
1622 isNonNil(v.Elem().FieldByName("X").Interface())
1623 isNonNil(v.Elem().FieldByName("Y").Interface())
1624 isNonNil(v.Type().Method(0).Func.Interface())
1628 isValid(v.Elem().Field(0))
1629 isValid(v.Elem().Field(1))
1630 isValid(v.Elem().FieldByName("x"))
1631 isValid(v.Elem().FieldByName("y"))
1632 isValid(v.Type().Method(0).Func)
1633 shouldPanic(func() { v.Elem().Field(0).Interface() })
1634 shouldPanic(func() { v.Elem().Field(1).Interface() })
1635 shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
1636 shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
1637 shouldPanic(func() { v.Type().Method(0).Func.Interface() })
1640 func shouldPanic(f func()) {
1642 if recover() == nil {
1643 panic("did not panic")
1649 func isNonNil(x interface{}) {
1651 panic("nil interface")
1655 func isValid(v Value) {