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.
24 func TestBool(t
*testing
.T
) {
27 t
.Fatal("ValueOf(true).Bool() = false")
44 func isDigit(c
uint8) bool { return '0' <= c
&& c
<= '9' }
46 func assert(t
*testing
.T
, s
, want
string) {
48 t
.Errorf("have %#q want %#q", s
, want
)
52 func typestring(i
interface{}) string { return TypeOf(i
).String() }
54 var typeTests
= []pair
{
55 {struct{ x
int }{}, "int"},
56 {struct{ x
int8 }{}, "int8"},
57 {struct{ x
int16 }{}, "int16"},
58 {struct{ x
int32 }{}, "int32"},
59 {struct{ x
int64 }{}, "int64"},
60 {struct{ x
uint }{}, "uint"},
61 {struct{ x
uint8 }{}, "uint8"},
62 {struct{ x
uint16 }{}, "uint16"},
63 {struct{ x
uint32 }{}, "uint32"},
64 {struct{ x
uint64 }{}, "uint64"},
65 {struct{ x
float32 }{}, "float32"},
66 {struct{ x
float64 }{}, "float64"},
67 {struct{ x
int8 }{}, "int8"},
68 {struct{ x (**int8) }{}, "**int8"},
69 {struct{ x (**integer
) }{}, "**reflect_test.integer"},
70 {struct{ x ([32]int32) }{}, "[32]int32"},
71 {struct{ x ([]int8) }{}, "[]int8"},
72 {struct{ x (map[string]int32) }{}, "map[string]int32"},
73 {struct{ x (chan<- string) }{}, "chan<- string"},
80 "struct { c chan *int32; d float32 }",
82 {struct{ x (func(a
int8, b
int32)) }{}, "func(int8, int32)"},
85 c
func(chan *integer
, *int8)
88 "struct { c func(chan *reflect_test.integer, *int8) }",
96 "struct { a int8; b int32 }",
105 "struct { a int8; b int8; c int32 }",
115 "struct { a int8; b int8; c int8; d int32 }",
126 "struct { a int8; b int8; c int8; d int8; e int32 }",
138 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
142 a
int8 `reflect:"hi there"`
145 `struct { a int8 "reflect:\"hi there\"" }`,
149 a
int8 `reflect:"hi \x00there\t\n\"\\"`
152 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
159 "struct { f func(...int) }",
163 a(func(func(int) int) func(func(int)) int)
167 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
171 var valueTests
= []pair
{
182 {new(float32), "256.25"},
183 {new(float64), "512.125"},
184 {new(complex64
), "532.125+10i"},
185 {new(complex128
), "564.25+1i"},
186 {new(string), "stringy cheese"},
188 {new(*int8), "*int8(0)"},
189 {new(**int8), "**int8(0)"},
190 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
191 {new(**integer
), "**reflect_test.integer(0)"},
192 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
193 {new(chan<- string), "chan<- string"},
194 {new(func(a
int8, b
int32)), "func(int8, int32)(0)"},
199 "struct { c chan *int32; d float32 }{chan *int32, 0}",
201 {new(struct{ c
func(chan *integer
, *int8) }),
202 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
208 "struct { a int8; b int32 }{0, 0}",
215 "struct { a int8; b int8; c int32 }{0, 0, 0}",
219 func testType(t
*testing
.T
, i
int, typ Type
, want
string) {
222 t
.Errorf("#%d: have %#q, want %#q", i
, s
, want
)
226 func TestTypes(t
*testing
.T
) {
227 for i
, tt
:= range typeTests
{
228 testType(t
, i
, ValueOf(tt
.i
).Field(0).Type(), tt
.s
)
232 func TestSet(t
*testing
.T
) {
233 for i
, tt
:= range valueTests
{
262 v
.SetComplex(532.125 + 10i
)
264 v
.SetComplex(564.25 + 1i
)
266 v
.SetString("stringy cheese")
270 s
:= valueToString(v
)
272 t
.Errorf("#%d: have %#q, want %#q", i
, s
, tt
.s
)
277 func TestSetValue(t
*testing
.T
) {
278 for i
, tt
:= range valueTests
{
279 v
:= ValueOf(tt
.i
).Elem()
282 v
.Set(ValueOf(int(132)))
284 v
.Set(ValueOf(int8(8)))
286 v
.Set(ValueOf(int16(16)))
288 v
.Set(ValueOf(int32(32)))
290 v
.Set(ValueOf(int64(64)))
292 v
.Set(ValueOf(uint(132)))
294 v
.Set(ValueOf(uint8(8)))
296 v
.Set(ValueOf(uint16(16)))
298 v
.Set(ValueOf(uint32(32)))
300 v
.Set(ValueOf(uint64(64)))
302 v
.Set(ValueOf(float32(256.25)))
304 v
.Set(ValueOf(512.125))
306 v
.Set(ValueOf(complex64(532.125 + 10i
)))
308 v
.Set(ValueOf(complex128(564.25 + 1i
)))
310 v
.Set(ValueOf("stringy cheese"))
314 s
:= valueToString(v
)
316 t
.Errorf("#%d: have %#q, want %#q", i
, s
, tt
.s
)
323 var valueToStringTests
= []pair
{
328 {T
{123, 456.75, "hello", &_i
}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
329 {new(chan *T
), "*chan *reflect_test.T(&chan *reflect_test.T)"},
330 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
331 {&[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})"},
332 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
333 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
336 func TestValueToString(t
*testing
.T
) {
337 for i
, test
:= range valueToStringTests
{
338 s
:= valueToString(ValueOf(test
.i
))
340 t
.Errorf("#%d: have %#q, want %#q", i
, s
, test
.s
)
345 func TestArrayElemSet(t
*testing
.T
) {
346 v
:= ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
347 v
.Index(4).SetInt(123)
348 s
:= valueToString(v
)
349 const want
= "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
351 t
.Errorf("[10]int: have %#q want %#q", s
, want
)
354 v
= ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
355 v
.Index(4).SetInt(123)
357 const want1
= "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
359 t
.Errorf("[]int: have %#q want %#q", s
, want1
)
363 func TestPtrPointTo(t
*testing
.T
) {
367 vi
:= ValueOf(&i
).Elem()
368 vip
.Elem().Set(vi
.Addr())
370 t
.Errorf("got %d, want 1234", *ip
)
374 vp
:= ValueOf(&ip
).Elem()
375 vp
.Set(Zero(vp
.Type()))
377 t
.Errorf("got non-nil (%p), want nil", ip
)
381 func TestPtrSetNil(t
*testing
.T
) {
385 vip
.Elem().Set(Zero(vip
.Elem().Type()))
387 t
.Errorf("got non-nil (%d), want nil", *ip
)
391 func TestMapSetNil(t
*testing
.T
) {
392 m
:= make(map[string]int)
394 vm
.Elem().Set(Zero(vm
.Elem().Type()))
396 t
.Errorf("got non-nil (%p), want nil", m
)
400 func TestAll(t
*testing
.T
) {
401 testType(t
, 1, TypeOf((int8)(0)), "int8")
402 testType(t
, 2, TypeOf((*int8)(nil)).Elem(), "int8")
404 typ
:= TypeOf((*struct {
408 testType(t
, 3, typ
, "*struct { c chan *int32; d float32 }")
410 testType(t
, 4, etyp
, "struct { c chan *int32; d float32 }")
413 testType(t
, 5, f
.Type
, "chan *int32")
415 f
, present
:= styp
.FieldByName("d")
417 t
.Errorf("FieldByName says present field is absent")
419 testType(t
, 6, f
.Type
, "float32")
421 f
, present
= styp
.FieldByName("absent")
423 t
.Errorf("FieldByName says absent field is present")
426 typ
= TypeOf([32]int32{})
427 testType(t
, 7, typ
, "[32]int32")
428 testType(t
, 8, typ
.Elem(), "int32")
430 typ
= TypeOf((map[string]*int32)(nil))
431 testType(t
, 9, typ
, "map[string]*int32")
433 testType(t
, 10, mtyp
.Key(), "string")
434 testType(t
, 11, mtyp
.Elem(), "*int32")
436 typ
= TypeOf((chan<- string)(nil))
437 testType(t
, 12, typ
, "chan<- string")
438 testType(t
, 13, typ
.Elem(), "string")
440 // make sure tag strings are not part of element type
441 typ
= TypeOf(struct {
442 d
[]uint32 `reflect:"TAG"`
444 testType(t
, 14, typ
, "[]uint32")
447 func TestInterfaceGet(t
*testing
.T
) {
452 v1
:= ValueOf(&inter
)
453 v2
:= v1
.Elem().Field(0)
454 assert(t
, v2
.Type().String(), "interface {}")
457 assert(t
, v3
.Type().String(), "float64")
460 func TestInterfaceValue(t
*testing
.T
) {
465 v1
:= ValueOf(&inter
)
466 v2
:= v1
.Elem().Field(0)
467 assert(t
, v2
.Type().String(), "interface {}")
469 assert(t
, v3
.Type().String(), "float64")
472 if _
, ok
:= i3
.(float64); !ok
{
473 t
.Error("v2.Interface() did not return float64, got ", TypeOf(i3
))
477 func TestFunctionValue(t
*testing
.T
) {
478 var x
interface{} = func() {}
480 if fmt
.Sprint(v
.Interface()) != fmt
.Sprint(x
) {
481 t
.Fatalf("TestFunction returned wrong pointer")
483 assert(t
, v
.Type().String(), "func()")
486 var appendTests
= []struct {
489 {make([]int, 2, 4), []int{22}},
490 {make([]int, 2, 4), []int{22, 33, 44}},
493 func sameInts(x
, y
[]int) bool {
494 if len(x
) != len(y
) {
497 for i
, xx
:= range x
{
505 func TestAppend(t
*testing
.T
) {
506 for i
, test
:= range appendTests
{
507 origLen
, extraLen
:= len(test
.orig
), len(test
.extra
)
508 want
:= append(test
.orig
, test
.extra
...)
509 // Convert extra from []int to []Value.
510 e0
:= make([]Value
, len(test
.extra
))
511 for j
, e
:= range test
.extra
{
514 // Convert extra from []int to *SliceValue.
515 e1
:= ValueOf(test
.extra
)
517 a0
:= ValueOf(test
.orig
)
518 have0
:= Append(a0
, e0
...).Interface().([]int)
519 if !sameInts(have0
, want
) {
520 t
.Errorf("Append #%d: have %v, want %v (%p %p)", i
, have0
, want
, test
.orig
, have0
)
522 // Check that the orig and extra slices were not modified.
523 if len(test
.orig
) != origLen
{
524 t
.Errorf("Append #%d origLen: have %v, want %v", i
, len(test
.orig
), origLen
)
526 if len(test
.extra
) != extraLen
{
527 t
.Errorf("Append #%d extraLen: have %v, want %v", i
, len(test
.extra
), extraLen
)
530 a1
:= ValueOf(test
.orig
)
531 have1
:= AppendSlice(a1
, e1
).Interface().([]int)
532 if !sameInts(have1
, want
) {
533 t
.Errorf("AppendSlice #%d: have %v, want %v", i
, have1
, want
)
535 // Check that the orig and extra slices were not modified.
536 if len(test
.orig
) != origLen
{
537 t
.Errorf("AppendSlice #%d origLen: have %v, want %v", i
, len(test
.orig
), origLen
)
539 if len(test
.extra
) != extraLen
{
540 t
.Errorf("AppendSlice #%d extraLen: have %v, want %v", i
, len(test
.extra
), extraLen
)
545 func TestCopy(t
*testing
.T
) {
546 a
:= []int{1, 2, 3, 4, 10, 9, 8, 7}
547 b
:= []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
548 c
:= []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
549 for i
:= 0; i
< len(b
); i
++ {
551 t
.Fatalf("b != c before test")
556 aa
:= ValueOf(&a1
).Elem()
557 ab
:= ValueOf(&b1
).Elem()
558 for tocopy
:= 1; tocopy
<= 7; tocopy
++ {
562 for i
:= 0; i
< tocopy
; i
++ {
564 t
.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
565 tocopy
, i
, a
[i
], i
, b
[i
])
568 for i
:= tocopy
; i
< len(b
); i
++ {
571 t
.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
572 tocopy
, i
, a
[i
], i
, b
[i
], i
, c
[i
])
574 t
.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
575 tocopy
, i
, b
[i
], i
, c
[i
])
578 t
.Logf("tocopy=%d elem %d is okay\n", tocopy
, i
)
584 func TestCopyArray(t
*testing
.T
) {
585 a
:= [8]int{1, 2, 3, 4, 10, 9, 8, 7}
586 b
:= [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
588 aa
:= ValueOf(&a
).Elem()
589 ab
:= ValueOf(&b
).Elem()
591 for i
:= 0; i
< len(a
); i
++ {
593 t
.Errorf("(i) a[%d]=%d, b[%d]=%d", i
, a
[i
], i
, b
[i
])
596 for i
:= len(a
); i
< len(b
); i
++ {
598 t
.Errorf("(ii) b[%d]=%d, c[%d]=%d", i
, b
[i
], i
, c
[i
])
600 t
.Logf("elem %d is okay\n", i
)
605 func TestBigUnnamedStruct(t
*testing
.T
) {
606 b
:= struct{ a
, b
, c
, d
int64 }{1, 2, 3, 4}
608 b1
:= v
.Interface().(struct {
611 if b1
.a
!= b
.a || b1
.b
!= b
.b || b1
.c
!= b
.c || b1
.d
!= b
.d
{
612 t
.Errorf("ValueOf(%v).Interface().(*Big) = %v", b
, b1
)
620 func TestBigStruct(t
*testing
.T
) {
621 b
:= big
{1, 2, 3, 4, 5}
623 b1
:= v
.Interface().(big
)
624 if b1
.a
!= b
.a || b1
.b
!= b
.b || b1
.c
!= b
.c || b1
.d
!= b
.d || b1
.e
!= b
.e
{
625 t
.Errorf("ValueOf(%v).Interface().(big) = %v", b
, b1
)
636 type DeepEqualTest
struct {
641 // Simple functions for DeepEqual tests.
645 fn3
= func() { fn1() } // Not nil.
648 var deepEqualTests
= []DeepEqualTest
{
652 {int32(1), int32(1), true},
654 {float32(0.5), float32(0.5), true},
655 {"hello", "hello", true},
656 {make([]int, 10), make([]int, 10), true},
657 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
658 {Basic
{1, 0.5}, Basic
{1, 0.5}, true},
659 {error(nil), error(nil), true},
660 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
665 {int32(1), int32(2), false},
667 {float32(0.5), float32(0.6), false},
668 {"hello", "hey", false},
669 {make([]int, 10), make([]int, 11), false},
670 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
671 {Basic
{1, 0.5}, Basic
{1, 0.6}, false},
672 {Basic
{1, 0}, Basic
{2, 0}, false},
673 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
674 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
675 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
676 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
682 // Nil vs empty: not the same.
683 {[]int{}, []int(nil), false},
684 {[]int{}, []int{}, true},
685 {[]int(nil), []int(nil), true},
686 {map[int]int{}, map[int]int(nil), false},
687 {map[int]int{}, map[int]int{}, true},
688 {map[int]int(nil), map[int]int(nil), true},
692 {int32(1), int64(1), false},
693 {0.5, "hello", false},
694 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
695 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
696 {Basic
{1, 0.5}, NotBasic
{1, 0.5}, false},
697 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
700 func TestDeepEqual(t
*testing
.T
) {
701 for _
, test
:= range deepEqualTests
{
702 if r
:= DeepEqual(test
.a
, test
.b
); r
!= test
.eq
{
703 t
.Errorf("DeepEqual(%v, %v) = %v, want %v", test
.a
, test
.b
, r
, test
.eq
)
708 func TestTypeOf(t
*testing
.T
) {
709 // Special case for nil
710 if typ
:= TypeOf(nil); typ
!= nil {
711 t
.Errorf("expected nil type for nil value; got %v", typ
)
713 for _
, test
:= range deepEqualTests
{
718 typ
:= TypeOf(test
.a
)
720 t
.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test
.a
, typ
, test
.a
, v
.Type())
725 type Recursive
struct {
730 func TestDeepEqualRecursiveStruct(t
*testing
.T
) {
731 a
, b
:= new(Recursive
), new(Recursive
)
732 *a
= Recursive
{12, a
}
733 *b
= Recursive
{12, b
}
734 if !DeepEqual(a
, b
) {
735 t
.Error("DeepEqual(recursive same) = false, want true")
739 type _Complex
struct {
743 d
map[float64]float64
746 func TestDeepEqualComplexStruct(t
*testing
.T
) {
747 m
:= make(map[float64]float64)
748 stra
, strb
:= "hello", "hello"
749 a
, b
:= new(_Complex
), new(_Complex
)
750 *a
= _Complex
{5, [3]*_Complex
{a
, b
, a
}, &stra
, m
}
751 *b
= _Complex
{5, [3]*_Complex
{b
, a
, a
}, &strb
, m
}
752 if !DeepEqual(a
, b
) {
753 t
.Error("DeepEqual(complex same) = false, want true")
757 func TestDeepEqualComplexStructInequality(t
*testing
.T
) {
758 m
:= make(map[float64]float64)
759 stra
, strb
:= "hello", "helloo" // Difference is here
760 a
, b
:= new(_Complex
), new(_Complex
)
761 *a
= _Complex
{5, [3]*_Complex
{a
, b
, a
}, &stra
, m
}
762 *b
= _Complex
{5, [3]*_Complex
{b
, a
, a
}, &strb
, m
}
764 t
.Error("DeepEqual(complex different) = true, want false")
772 func TestDeepEqualUnexportedMap(t
*testing
.T
) {
773 // Check that DeepEqual can look at unexported fields.
774 x1
:= UnexpT
{map[int]int{1: 2}}
775 x2
:= UnexpT
{map[int]int{1: 2}}
776 if !DeepEqual(&x1
, &x2
) {
777 t
.Error("DeepEqual(x1, x2) = false, want true")
780 y1
:= UnexpT
{map[int]int{2: 3}}
781 if DeepEqual(&x1
, &y1
) {
782 t
.Error("DeepEqual(x1, y1) = true, want false")
786 func check2ndField(x
interface{}, offs
uintptr, t
*testing
.T
) {
788 f
:= s
.Type().Field(1)
789 if f
.Offset
!= offs
{
790 t
.Error("mismatched offsets in structure alignment:", f
.Offset
, offs
)
794 // Check that structure alignment & offsets viewed through reflect agree with those
795 // from the compiler itself.
796 func TestAlignment(t
*testing
.T
) {
797 type T1inner
struct {
804 type T2inner
struct {
812 x
:= T1
{T1inner
{2}, 17}
813 check2ndField(x
, uintptr(unsafe
.Pointer(&x
.f
))-uintptr(unsafe
.Pointer(&x
)), t
)
815 x1
:= T2
{T2inner
{2, 3}, 17}
816 check2ndField(x1
, uintptr(unsafe
.Pointer(&x1
.f
))-uintptr(unsafe
.Pointer(&x1
)), t
)
819 func Nil(a
interface{}, t
*testing
.T
) {
820 n
:= ValueOf(a
).Field(0)
822 t
.Errorf("%v should be nil", a
)
826 func NotNil(a
interface{}, t
*testing
.T
) {
827 n
:= ValueOf(a
).Field(0)
829 t
.Errorf("value of type %v should not be nil", ValueOf(a
).Type().String())
833 func TestIsNil(t
*testing
.T
) {
834 // These implement IsNil.
835 // Wrap in extra struct to hide interface type.
836 doNil
:= []interface{}{
838 struct{ x
interface{} }{},
839 struct{ x
map[string]int }{},
840 struct{ x
func() bool }{},
841 struct{ x
chan int }{},
842 struct{ x
[]string }{},
844 for _
, ts
:= range doNil
{
845 ty
:= TypeOf(ts
).Field(0).Type
847 v
.IsNil() // panics if not okay to call
850 // Check the implementations
862 si
.x
= make([]int, 10)
869 ci
.x
= make(chan int)
876 mi
.x
= make(map[int]int)
894 func TestInterfaceExtraction(t
*testing
.T
) {
900 v
:= Indirect(ValueOf(&s
)).Field(0).Interface()
901 if v
!= s
.W
.(interface{}) {
902 t
.Error("Interface() on interface: ", v
, s
.W
)
906 func TestNilPtrValueSub(t
*testing
.T
) {
908 if pv
:= ValueOf(pi
); pv
.Elem().IsValid() {
909 t
.Error("ValueOf((*int)(nil)).Elem().IsValid()")
913 func TestMap(t
*testing
.T
) {
914 m
:= map[string]int{"a": 1, "b": 2}
916 if n
:= mv
.Len(); n
!= len(m
) {
917 t
.Errorf("Len = %d, want %d", n
, len(m
))
920 newmap
:= MakeMap(mv
.Type())
921 for k
, v
:= range m
{
922 // Check that returned Keys match keys in range.
923 // These aren't required to be in the same order.
925 for _
, kv
:= range keys
{
926 if kv
.String() == k
{
932 t
.Errorf("Missing key %q", k
)
935 // Check that value lookup is correct.
936 vv
:= mv
.MapIndex(ValueOf(k
))
937 if vi
:= vv
.Int(); vi
!= int64(v
) {
938 t
.Errorf("Key %q: have value %d, want %d", k
, vi
, v
)
941 // Copy into new map.
942 newmap
.SetMapIndex(ValueOf(k
), ValueOf(v
))
944 vv
:= mv
.MapIndex(ValueOf("not-present"))
946 t
.Errorf("Invalid key: got non-nil value %s", valueToString(vv
))
949 newm
:= newmap
.Interface().(map[string]int)
950 if len(newm
) != len(m
) {
951 t
.Errorf("length after copy: newm=%d, m=%d", len(newm
), len(m
))
954 for k
, v
:= range newm
{
957 t
.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k
, v
, k
, mv
, ok
)
961 newmap
.SetMapIndex(ValueOf("a"), Value
{})
964 t
.Errorf("newm[\"a\"] = %d after delete", v
)
967 mv
= ValueOf(&m
).Elem()
968 mv
.Set(Zero(mv
.Type()))
970 t
.Errorf("mv.Set(nil) failed")
974 func TestChan(t
*testing
.T
) {
975 for loop
:= 0; loop
< 2; loop
++ {
979 // check both ways to allocate channels
982 c
= make(chan int, 1)
985 cv
= MakeChan(TypeOf(c
), 1)
986 c
= cv
.Interface().(chan int)
991 if i
:= <-c
; i
!= 2 {
992 t
.Errorf("reflect Send 2, native recv %d", i
)
997 if i
, ok
:= cv
.Recv(); i
.Int() != 3 ||
!ok
{
998 t
.Errorf("native send 3, reflect Recv %d, %t", i
.Int(), ok
)
1002 val
, ok
:= cv
.TryRecv()
1003 if val
.IsValid() || ok
{
1004 t
.Errorf("TryRecv on empty chan: %s, %t", valueToString(val
), ok
)
1009 val
, ok
= cv
.TryRecv()
1011 t
.Errorf("TryRecv on ready chan got nil")
1012 } else if i
:= val
.Int(); i
!= 4 ||
!ok
{
1013 t
.Errorf("native send 4, TryRecv %d, %t", i
, ok
)
1018 ok
= cv
.TrySend(ValueOf(5))
1021 t
.Errorf("TrySend on full chan succeeded: value %d", i
)
1025 ok
= cv
.TrySend(ValueOf(6))
1027 t
.Errorf("TrySend on empty chan failed")
1029 if i
= <-c
; i
!= 6 {
1030 t
.Errorf("TrySend 6, recv %d", i
)
1037 if i
, ok
:= cv
.Recv(); i
.Int() != 123 ||
!ok
{
1038 t
.Errorf("send 123 then close; Recv %d, %t", i
.Int(), ok
)
1040 if i
, ok
:= cv
.Recv(); i
.Int() != 0 || ok
{
1041 t
.Errorf("after close Recv %d, %t", i
.Int(), ok
)
1045 // check creation of unbuffered channel
1047 cv
:= MakeChan(TypeOf(c
), 0)
1048 c
= cv
.Interface().(chan int)
1049 if cv
.TrySend(ValueOf(7)) {
1050 t
.Errorf("TrySend on sync chan succeeded")
1052 if v
, ok
:= cv
.TryRecv(); v
.IsValid() || ok
{
1053 t
.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v
.IsValid(), ok
)
1057 cv
= MakeChan(TypeOf(c
), 10)
1058 c
= cv
.Interface().(chan int)
1059 for i
:= 0; i
< 3; i
++ {
1062 if l
, m
:= cv
.Len(), cv
.Cap(); l
!= len(c
) || m
!= cap(c
) {
1063 t
.Errorf("Len/Cap = %d/%d want %d/%d", l
, m
, len(c
), cap(c
))
1067 // caseInfo describes a single case in a select test.
1068 type caseInfo
struct {
1077 var allselect
= flag
.Bool("allselect", false, "exhaustive select test")
1079 func TestSelect(t
*testing
.T
) {
1080 selectWatch
.once
.Do(func() { go selectWatcher() })
1084 newop
:= func(n
int, cap int) (ch
, val Value
) {
1087 c
:= make(chan int, cap)
1091 c
:= make(chan string, cap)
1093 val
= ValueOf(fmt
.Sprint(n
))
1098 for n
:= 0; x
.Next(); n
++ {
1099 if testing
.Short() && n
>= 1000 {
1102 if n
>= 100000 && !*allselect
{
1105 if n%100000
== 0 && testing
.Verbose() {
1106 println("TestSelect", n
)
1108 var cases
[]SelectCase
1113 ch
, val
:= newop(len(cases
), 1)
1114 cases
= append(cases
, SelectCase
{
1119 info
= append(info
, caseInfo
{desc
: "ready send", canSelect
: true})
1124 ch
, val
:= newop(len(cases
), 1)
1126 cases
= append(cases
, SelectCase
{
1130 info
= append(info
, caseInfo
{desc
: "ready recv", canSelect
: true, recv
: val
})
1135 ch
, val
:= newop(len(cases
), 0)
1136 cases
= append(cases
, SelectCase
{
1143 f
:= func() { ch
.Recv() }
1144 info
= append(info
, caseInfo
{desc
: "blocking send", helper
: f
})
1146 info
= append(info
, caseInfo
{desc
: "blocking send"})
1152 ch
, val
:= newop(len(cases
), 0)
1153 cases
= append(cases
, SelectCase
{
1159 f
:= func() { ch
.Send(val
) }
1160 info
= append(info
, caseInfo
{desc
: "blocking recv", recv
: val
, helper
: f
})
1162 info
= append(info
, caseInfo
{desc
: "blocking recv"})
1168 // Maybe include value to send.
1173 cases
= append(cases
, SelectCase
{
1177 info
= append(info
, caseInfo
{desc
: "zero Chan send"})
1180 // Zero Chan receive.
1182 cases
= append(cases
, SelectCase
{
1185 info
= append(info
, caseInfo
{desc
: "zero Chan recv"})
1190 cases
= append(cases
, SelectCase
{
1192 Chan
: ValueOf((chan int)(nil)),
1195 info
= append(info
, caseInfo
{desc
: "nil Chan send"})
1200 cases
= append(cases
, SelectCase
{
1202 Chan
: ValueOf((chan int)(nil)),
1204 info
= append(info
, caseInfo
{desc
: "nil Chan recv"})
1207 // closed Chan send.
1209 ch
:= make(chan int)
1211 cases
= append(cases
, SelectCase
{
1216 info
= append(info
, caseInfo
{desc
: "closed Chan send", canSelect
: true, panic: true})
1219 // closed Chan recv.
1221 ch
, val
:= newop(len(cases
), 0)
1223 val
= Zero(val
.Type())
1224 cases
= append(cases
, SelectCase
{
1228 info
= append(info
, caseInfo
{desc
: "closed Chan recv", canSelect
: true, closed: true, recv
: val
})
1231 var helper
func() // goroutine to help the select complete
1233 // Add default? Must be last case here, but will permute.
1234 // Add the default if the select would otherwise
1235 // block forever, and maybe add it anyway.
1241 for i
, c
:= range info
{
1249 } else if c
.helper
!= nil {
1251 helpers
= append(helpers
, i
)
1254 if !canProceed || x
.Maybe() {
1255 cases
= append(cases
, SelectCase
{
1258 info
= append(info
, caseInfo
{desc
: "default", canSelect
: canBlock
})
1260 } else if canBlock
{
1261 // Select needs to communicate with another goroutine.
1262 cas
:= &info
[helpers
[x
.Choose(len(helpers
))]]
1264 cas
.canSelect
= true
1268 // Permute cases and case info.
1269 // Doing too much here makes the exhaustive loop
1270 // too exhausting, so just do two swaps.
1271 for loop
:= 0; loop
< 2; loop
++ {
1272 i
:= x
.Choose(len(cases
))
1273 j
:= x
.Choose(len(cases
))
1274 cases
[i
], cases
[j
] = cases
[j
], cases
[i
]
1275 info
[i
], info
[j
] = info
[j
], info
[i
]
1279 // We wait before kicking off a goroutine to satisfy a blocked select.
1280 // The pause needs to be big enough to let the select block before
1281 // we run the helper, but if we lose that race once in a while it's okay: the
1282 // select will just proceed immediately. Not a big deal.
1283 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1284 pause
:= 10 * time
.Microsecond
1285 if testing
.Short() {
1286 pause
= 100 * time
.Microsecond
1288 time
.AfterFunc(pause
, helper
)
1292 i
, recv
, recvOK
, panicErr
:= runSelect(cases
, info
)
1293 if panicErr
!= nil && !canPanic
{
1294 t
.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info
), panicErr
)
1296 if panicErr
== nil && canPanic
&& numCanSelect
== 1 {
1297 t
.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info
), i
)
1299 if panicErr
!= nil {
1307 recvStr
= fmt
.Sprintf(", received %v, %v", recv
.Interface(), recvOK
)
1309 t
.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info
), i
, recvStr
)
1313 t
.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info
), i
)
1317 if cases
[i
].Dir
== SelectRecv
{
1318 if !recv
.IsValid() {
1319 t
.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info
), i
, recv
, recvOK
, cas
.recv
.Interface(), !cas
.closed)
1321 if !cas
.recv
.IsValid() {
1322 t
.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info
), i
)
1324 if recv
.Interface() != cas
.recv
.Interface() || recvOK
!= !cas
.closed {
1325 if recv
.Interface() == cas
.recv
.Interface() && recvOK
== !cas
.closed {
1326 t
.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info
), i
, recv
.Interface(), recvOK
, recv
.Interface())
1328 t
.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info
), i
, recv
.Interface(), recvOK
, cas
.recv
.Interface(), !cas
.closed)
1331 if recv
.IsValid() || recvOK
{
1332 t
.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info
), i
, recv
, recvOK
, Value
{}, false)
1338 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1339 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1340 // an error describing the select and panics the entire test binary.
1341 var selectWatch
struct {
1348 func selectWatcher() {
1350 time
.Sleep(1 * time
.Second
)
1352 if selectWatch
.info
!= nil && time
.Since(selectWatch
.now
) > 1*time
.Second
{
1353 fmt
.Fprintf(os
.Stderr
, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch
.info
))
1354 panic("select stuck")
1356 selectWatch
.Unlock()
1360 // runSelect runs a single select test.
1361 // It returns the values returned by Select but also returns
1362 // a panic value if the Select panics.
1363 func runSelect(cases
[]SelectCase
, info
[]caseInfo
) (chosen
int, recv Value
, recvOK
bool, panicErr
interface{}) {
1365 panicErr
= recover()
1368 selectWatch
.info
= nil
1369 selectWatch
.Unlock()
1373 selectWatch
.now
= time
.Now()
1374 selectWatch
.info
= info
1375 selectWatch
.Unlock()
1377 chosen
, recv
, recvOK
= Select(cases
)
1381 // fmtSelect formats the information about a single select test.
1382 func fmtSelect(info
[]caseInfo
) string {
1383 var buf bytes
.Buffer
1384 fmt
.Fprintf(&buf
, "\nselect {\n")
1385 for i
, cas
:= range info
{
1386 fmt
.Fprintf(&buf
, "%d: %s", i
, cas
.desc
)
1387 if cas
.recv
.IsValid() {
1388 fmt
.Fprintf(&buf
, " val=%#v", cas
.recv
.Interface())
1391 fmt
.Fprintf(&buf
, " canselect")
1394 fmt
.Fprintf(&buf
, " panic")
1396 fmt
.Fprintf(&buf
, "\n")
1398 fmt
.Fprintf(&buf
, "}")
1404 // Difficult test for function call because of
1405 // implicit padding between arguments.
1406 func dummy(b
byte, c
int, d
byte, e two
, f
byte, g
float32, h
byte) (i
byte, j
int, k
byte, l two
, m
byte, n
float32, o
byte) {
1407 return b
, c
, d
, e
, f
, g
, h
1410 func TestFunc(t
*testing
.T
) {
1411 ret
:= ValueOf(dummy
).Call([]Value
{
1415 ValueOf(two
{40, 50}),
1417 ValueOf(float32(70)),
1421 t
.Fatalf("Call returned %d values, want 7", len(ret
))
1424 i
:= byte(ret
[0].Uint())
1425 j
:= int(ret
[1].Int())
1426 k
:= byte(ret
[2].Uint())
1427 l
:= ret
[3].Interface().(two
)
1428 m
:= byte(ret
[4].Uint())
1429 n
:= float32(ret
[5].Float())
1430 o
:= byte(ret
[6].Uint())
1432 if i
!= 10 || j
!= 20 || k
!= 30 || l
!= (two
{40, 50}) || m
!= 60 || n
!= 70 || o
!= 80 {
1433 t
.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i
, j
, k
, l
, m
, n
, o
)
1437 func TestMakeFunc(t
*testing
.T
) {
1438 switch runtime
.GOARCH
{
1439 case "amd64", "386":
1441 t
.Skip("MakeFunc not implemented for " + runtime
.GOARCH
)
1445 fv
:= MakeFunc(TypeOf(f
), func(in
[]Value
) []Value
{ return in
})
1446 ValueOf(&f
).Elem().Set(fv
)
1448 // Call g with small arguments so that there is
1449 // something predictable (and different from the
1450 // correct results) in those positions on the stack.
1452 g(1, 2, 3, two
{4, 5}, 6, 7, 8)
1454 // Call constructed function f.
1455 i
, j
, k
, l
, m
, n
, o
:= f(10, 20, 30, two
{40, 50}, 60, 70, 80)
1456 if i
!= 10 || j
!= 20 || k
!= 30 || l
!= (two
{40, 50}) || m
!= 60 || n
!= 70 || o
!= 80 {
1457 t
.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i
, j
, k
, l
, m
, n
, o
)
1461 func TestMakeFuncInterface(t
*testing
.T
) {
1462 switch runtime
.GOARCH
{
1463 case "amd64", "386":
1465 t
.Skip("MakeFunc not implemented for " + runtime
.GOARCH
)
1468 fn
:= func(i
int) int { return i
}
1469 incr
:= func(in
[]Value
) []Value
{
1470 return []Value
{ValueOf(int(in
[0].Int() + 1))}
1472 fv
:= MakeFunc(TypeOf(fn
), incr
)
1473 ValueOf(&fn
).Elem().Set(fv
)
1474 if r
:= fn(2); r
!= 3 {
1475 t
.Errorf("Call returned %d, want 3", r
)
1477 if r
:= fv
.Call([]Value
{ValueOf(14)})[0].Int(); r
!= 15 {
1478 t
.Errorf("Call returned %d, want 15", r
)
1480 if r
:= fv
.Interface().(func(int) int)(26); r
!= 27 {
1481 t
.Errorf("Call returned %d, want 27", r
)
1489 // This will be index 0.
1490 func (p Point
) AnotherMethod(scale
int) int {
1494 // This will be index 1.
1495 func (p Point
) Dist(scale
int) int {
1496 //println("Point.Dist", p.x, p.y, scale)
1497 return p
.x
*p
.x
*scale
+ p
.y
*p
.y
*scale
1500 func TestMethod(t
*testing
.T
) {
1501 // Non-curried method of type.
1503 i
:= TypeOf(p
).Method(1).Func
.Call([]Value
{ValueOf(p
), ValueOf(10)})[0].Int()
1505 t
.Errorf("Type Method returned %d; want 250", i
)
1508 m
, ok
:= TypeOf(p
).MethodByName("Dist")
1510 t
.Fatalf("method by name failed")
1512 i
= m
.Func
.Call([]Value
{ValueOf(p
), ValueOf(11)})[0].Int()
1514 t
.Errorf("Type MethodByName returned %d; want 275", i
)
1517 i
= TypeOf(&p
).Method(1).Func
.Call([]Value
{ValueOf(&p
), ValueOf(12)})[0].Int()
1519 t
.Errorf("Pointer Type Method returned %d; want 300", i
)
1522 m
, ok
= TypeOf(&p
).MethodByName("Dist")
1524 t
.Fatalf("ptr method by name failed")
1526 i
= m
.Func
.Call([]Value
{ValueOf(&p
), ValueOf(13)})[0].Int()
1528 t
.Errorf("Pointer Type MethodByName returned %d; want 325", i
)
1531 // Curried method of value.
1532 tfunc
:= TypeOf((func(int) int)(nil))
1533 v
:= ValueOf(p
).Method(1)
1534 if tt
:= v
.Type(); tt
!= tfunc
{
1535 t
.Errorf("Value Method Type is %s; want %s", tt
, tfunc
)
1537 i
= v
.Call([]Value
{ValueOf(14)})[0].Int()
1539 t
.Errorf("Value Method returned %d; want 350", i
)
1541 v
= ValueOf(p
).MethodByName("Dist")
1542 if tt
:= v
.Type(); tt
!= tfunc
{
1543 t
.Errorf("Value MethodByName Type is %s; want %s", tt
, tfunc
)
1545 i
= v
.Call([]Value
{ValueOf(15)})[0].Int()
1547 t
.Errorf("Value MethodByName returned %d; want 375", i
)
1550 // Curried method of pointer.
1551 v
= ValueOf(&p
).Method(1)
1552 if tt
:= v
.Type(); tt
!= tfunc
{
1553 t
.Errorf("Pointer Value Method Type is %s; want %s", tt
, tfunc
)
1555 i
= v
.Call([]Value
{ValueOf(16)})[0].Int()
1557 t
.Errorf("Pointer Value Method returned %d; want 400", i
)
1559 v
= ValueOf(&p
).MethodByName("Dist")
1560 if tt
:= v
.Type(); tt
!= tfunc
{
1561 t
.Errorf("Pointer Value MethodByName Type is %s; want %s", tt
, tfunc
)
1563 i
= v
.Call([]Value
{ValueOf(17)})[0].Int()
1565 t
.Errorf("Pointer Value MethodByName returned %d; want 425", i
)
1568 // Curried method of interface value.
1569 // Have to wrap interface value in a struct to get at it.
1570 // Passing it to ValueOf directly would
1571 // access the underlying Point, not the interface.
1575 pv
:= ValueOf(&x
).Elem()
1577 if tt
:= v
.Type(); tt
!= tfunc
{
1578 t
.Errorf("Interface Method Type is %s; want %s", tt
, tfunc
)
1580 i
= v
.Call([]Value
{ValueOf(18)})[0].Int()
1582 t
.Errorf("Interface Method returned %d; want 450", i
)
1584 v
= pv
.MethodByName("Dist")
1585 if tt
:= v
.Type(); tt
!= tfunc
{
1586 t
.Errorf("Interface MethodByName Type is %s; want %s", tt
, tfunc
)
1588 i
= v
.Call([]Value
{ValueOf(19)})[0].Int()
1590 t
.Errorf("Interface MethodByName returned %d; want 475", i
)
1594 /* Not yet implemented for gccgo
1596 func TestMethodValue(t *testing.T) {
1600 // Curried method of value.
1601 tfunc := TypeOf((func(int) int)(nil))
1602 v := ValueOf(p).Method(1)
1603 if tt := v.Type(); tt != tfunc {
1604 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1606 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
1608 t.Errorf("Value Method returned %d; want 250", i)
1610 v = ValueOf(p).MethodByName("Dist")
1611 if tt := v.Type(); tt != tfunc {
1612 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1614 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
1616 t.Errorf("Value MethodByName returned %d; want 275", i)
1619 // Curried method of pointer.
1620 v = ValueOf(&p).Method(1)
1621 if tt := v.Type(); tt != tfunc {
1622 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1624 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
1626 t.Errorf("Pointer Value Method returned %d; want 300", i)
1628 v = ValueOf(&p).MethodByName("Dist")
1629 if tt := v.Type(); tt != tfunc {
1630 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1632 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
1634 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
1637 // Curried method of pointer to pointer.
1639 v = ValueOf(&pp).Elem().Method(1)
1640 if tt := v.Type(); tt != tfunc {
1641 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
1643 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
1645 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
1647 v = ValueOf(&pp).Elem().MethodByName("Dist")
1648 if tt := v.Type(); tt != tfunc {
1649 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1651 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
1653 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
1656 // Curried method of interface value.
1657 // Have to wrap interface value in a struct to get at it.
1658 // Passing it to ValueOf directly would
1659 // access the underlying Point, not the interface.
1665 pv := ValueOf(s).Field(0)
1667 if tt := v.Type(); tt != tfunc {
1668 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1670 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
1672 t.Errorf("Interface Method returned %d; want 400", i)
1674 v = pv.MethodByName("Dist")
1675 if tt := v.Type(); tt != tfunc {
1676 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1678 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
1680 t.Errorf("Interface MethodByName returned %d; want 425", i)
1686 // Reflect version of $GOROOT/test/method5.go
1688 // Concrete types implementing M method.
1689 // Smaller than a word, word-sized, larger than a word.
1690 // Value and pointer receivers.
1692 type Tinter
interface {
1693 M(int, byte) (byte, int)
1698 func (v Tsmallv
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
1702 func (p
*Tsmallp
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
1706 func (v Twordv
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
1710 func (p
*Twordp
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
1712 type Tbigv
[2]uintptr
1714 func (v Tbigv
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(v
[0]) + int(v
[1]) }
1716 type Tbigp
[2]uintptr
1718 func (p
*Tbigp
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(p
[0]) + int(p
[1]) }
1720 // Again, with an unexported method.
1724 func (v tsmallv
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
1728 func (p
*tsmallp
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
1732 func (v twordv
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
1736 func (p
*twordp
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
1738 type tbigv
[2]uintptr
1740 func (v tbigv
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(v
[0]) + int(v
[1]) }
1742 type tbigp
[2]uintptr
1744 func (p
*tbigp
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(p
[0]) + int(p
[1]) }
1746 type tinter
interface {
1747 m(int, byte) (byte, int)
1750 // Embedding via pointer.
1767 func (t4 Tm4
) M(x
int, b
byte) (byte, int) { return b
, x
+ 40 }
1769 func TestMethod5(t
*testing
.T
) {
1770 /* Not yet used for gccgo
1771 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
1773 if b != 99 || x != 1000+inc {
1774 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
1779 CheckV
:= func(name
string, i Value
, inc
int) {
1780 bx
:= i
.Method(0).Call([]Value
{ValueOf(1000), ValueOf(byte(99))})
1781 b
:= bx
[0].Interface()
1782 x
:= bx
[1].Interface()
1783 if b
!= byte(99) || x
!= 1000+inc
{
1784 t
.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name
, b
, x
, 1000+inc
)
1787 /* Not yet implemented for gccgo
1788 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
1792 var TinterType
= TypeOf(new(Tinter
)).Elem()
1793 var tinterType
= TypeOf(new(tinter
)).Elem()
1795 CheckI
:= func(name
string, i
interface{}, inc
int) {
1797 CheckV(name
, v
, inc
)
1798 CheckV("(i="+name
+")", v
.Convert(TinterType
), inc
)
1803 CheckI("&sv", &sv
, 1)
1806 CheckI("&sp", &sp
, 2)
1810 CheckI("&wv", &wv
, 3)
1813 CheckI("&wp", &wp
, 4)
1815 bv
:= Tbigv([2]uintptr{5, 6})
1816 CheckI("bv", bv
, 11)
1817 CheckI("&bv", &bv
, 11)
1819 bp
:= Tbigp([2]uintptr{7, 8})
1820 CheckI("&bp", &bp
, 15)
1826 CheckI("t4", t4
, 40)
1827 CheckI("&t4", &t4
, 40)
1828 CheckI("t3", t3
, 40)
1829 CheckI("&t3", &t3
, 40)
1830 CheckI("t2", t2
, 40)
1831 CheckI("&t2", &t2
, 40)
1832 CheckI("t1", t1
, 40)
1833 CheckI("&t1", &t1
, 40)
1835 methodShouldPanic
:= func(name
string, i
interface{}) {
1838 shouldPanic(func() { m
.Call([]Value
{ValueOf(1000), ValueOf(byte(99))}) })
1839 shouldPanic(func() { m
.Interface() })
1841 v
= v
.Convert(tinterType
)
1843 shouldPanic(func() { m
.Call([]Value
{ValueOf(1000), ValueOf(byte(99))}) })
1844 shouldPanic(func() { m
.Interface() })
1848 methodShouldPanic("_sv", _sv
)
1849 methodShouldPanic("&_sv", &_sv
)
1852 methodShouldPanic("&_sp", &_sp
)
1855 methodShouldPanic("_wv", _wv
)
1856 methodShouldPanic("&_wv", &_wv
)
1859 methodShouldPanic("&_wp", &_wp
)
1861 _bv
:= tbigv([2]uintptr{5, 6})
1862 methodShouldPanic("_bv", _bv
)
1863 methodShouldPanic("&_bv", &_bv
)
1865 _bp
:= tbigp([2]uintptr{7, 8})
1866 methodShouldPanic("&_bp", &_bp
)
1869 vnil
:= ValueOf(&tnil
).Elem()
1870 shouldPanic(func() { vnil
.Method(0) })
1873 func TestInterfaceSet(t
*testing
.T
) {
1882 sv
:= ValueOf(&s
).Elem()
1883 sv
.Field(0).Set(ValueOf(p
))
1884 if q
:= s
.I
.(*Point
); q
!= p
{
1885 t
.Errorf("i: have %p want %p", q
, p
)
1890 if q
:= s
.P
.(*Point
); q
!= p
{
1891 t
.Errorf("i: have %p want %p", q
, p
)
1894 i
:= pv
.Method(0).Call([]Value
{ValueOf(10)})[0].Int()
1896 t
.Errorf("Interface Method returned %d; want 250", i
)
1905 func TestAnonymousFields(t
*testing
.T
) {
1906 var field StructField
1910 if field
, ok
= type1
.FieldByName("int"); !ok
{
1911 t
.Fatal("no field 'int'")
1913 if field
.Index
[0] != 1 {
1914 t
.Error("field index should be 1; is", field
.Index
)
1968 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
1990 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2009 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2023 var fieldTests
= []FTest
{
2024 {struct{}{}, "", nil, 0},
2025 {struct{}{}, "Foo", nil, 0},
2026 {S0
{A
: 'a'}, "A", []int{0}, 'a'},
2027 {S0
{}, "D", nil, 0},
2028 {S1
{S0
: S0
{A
: 'a'}}, "A", []int{1, 0}, 'a'},
2029 {S1
{B
: 'b'}, "B", []int{0}, 'b'},
2030 {S1
{}, "S0", []int{1}, 0},
2031 {S1
{S0
: S0
{C
: 'c'}}, "C", []int{1, 2}, 'c'},
2032 {S2
{A
: 'a'}, "A", []int{0}, 'a'},
2033 {S2
{}, "S1", []int{1}, 0},
2034 {S2
{S1
: &S1
{B
: 'b'}}, "B", []int{1, 0}, 'b'},
2035 {S2
{S1
: &S1
{S0
: S0
{C
: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2036 {S2
{}, "D", nil, 0},
2037 {S3
{}, "S1", nil, 0},
2038 {S3
{S2
: S2
{A
: 'a'}}, "A", []int{1, 0}, 'a'},
2039 {S3
{}, "B", nil, 0},
2040 {S3
{D
: 'd'}, "D", []int{2}, 0},
2041 {S3
{E
: 'e'}, "E", []int{3}, 'e'},
2042 {S4
{A
: 'a'}, "A", []int{1}, 'a'},
2043 {S4
{}, "B", nil, 0},
2044 {S5
{}, "X", nil, 0},
2045 {S5
{}, "Y", []int{2, 0, 1}, 0},
2046 {S10
{}, "X", nil, 0},
2047 {S10
{}, "Y", []int{2, 0, 0, 1}, 0},
2048 {S14
{}, "X", nil, 0},
2051 func TestFieldByIndex(t
*testing
.T
) {
2052 for _
, test
:= range fieldTests
{
2054 f
:= s
.FieldByIndex(test
.index
)
2056 if test
.index
!= nil {
2057 if f
.Name
!= test
.name
{
2058 t
.Errorf("%s.%s found; want %s", s
.Name(), f
.Name
, test
.name
)
2061 t
.Errorf("%s.%s found", s
.Name(), f
.Name
)
2063 } else if len(test
.index
) > 0 {
2064 t
.Errorf("%s.%s not found", s
.Name(), test
.name
)
2067 if test
.value
!= 0 {
2068 v
:= ValueOf(test
.s
).FieldByIndex(test
.index
)
2070 if x
, ok
:= v
.Interface().(int); ok
{
2071 if x
!= test
.value
{
2072 t
.Errorf("%s%v is %d; want %d", s
.Name(), test
.index
, x
, test
.value
)
2075 t
.Errorf("%s%v value not an int", s
.Name(), test
.index
)
2078 t
.Errorf("%s%v value not found", s
.Name(), test
.index
)
2084 func TestFieldByName(t
*testing
.T
) {
2085 for _
, test
:= range fieldTests
{
2087 f
, found
:= s
.FieldByName(test
.name
)
2089 if test
.index
!= nil {
2090 // Verify field depth and index.
2091 if len(f
.Index
) != len(test
.index
) {
2092 t
.Errorf("%s.%s depth %d; want %d: %v vs %v", s
.Name(), test
.name
, len(f
.Index
), len(test
.index
), f
.Index
, test
.index
)
2094 for i
, x
:= range f
.Index
{
2095 if x
!= test
.index
[i
] {
2096 t
.Errorf("%s.%s.Index[%d] is %d; want %d", s
.Name(), test
.name
, i
, x
, test
.index
[i
])
2101 t
.Errorf("%s.%s found", s
.Name(), f
.Name
)
2103 } else if len(test
.index
) > 0 {
2104 t
.Errorf("%s.%s not found", s
.Name(), test
.name
)
2107 if test
.value
!= 0 {
2108 v
:= ValueOf(test
.s
).FieldByName(test
.name
)
2110 if x
, ok
:= v
.Interface().(int); ok
{
2111 if x
!= test
.value
{
2112 t
.Errorf("%s.%s is %d; want %d", s
.Name(), test
.name
, x
, test
.value
)
2115 t
.Errorf("%s.%s value not an int", s
.Name(), test
.name
)
2118 t
.Errorf("%s.%s value not found", s
.Name(), test
.name
)
2124 func TestImportPath(t
*testing
.T
) {
2129 {TypeOf(&base64
.Encoding
{}).Elem(), "encoding/base64"},
2130 {TypeOf(int(0)), ""},
2131 {TypeOf(int8(0)), ""},
2132 {TypeOf(int16(0)), ""},
2133 {TypeOf(int32(0)), ""},
2134 {TypeOf(int64(0)), ""},
2135 {TypeOf(uint(0)), ""},
2136 {TypeOf(uint8(0)), ""},
2137 {TypeOf(uint16(0)), ""},
2138 {TypeOf(uint32(0)), ""},
2139 {TypeOf(uint64(0)), ""},
2140 {TypeOf(uintptr(0)), ""},
2141 {TypeOf(float32(0)), ""},
2142 {TypeOf(float64(0)), ""},
2143 {TypeOf(complex64(0)), ""},
2144 {TypeOf(complex128(0)), ""},
2145 {TypeOf(byte(0)), ""},
2146 {TypeOf(rune(0)), ""},
2147 {TypeOf([]byte(nil)), ""},
2148 {TypeOf([]rune(nil)), ""},
2149 {TypeOf(string("")), ""},
2150 {TypeOf((*interface{})(nil)).Elem(), ""},
2151 {TypeOf((*byte)(nil)), ""},
2152 {TypeOf((*rune
)(nil)), ""},
2153 {TypeOf((*int64)(nil)), ""},
2154 {TypeOf(map[string]int{}), ""},
2155 {TypeOf((*error
)(nil)).Elem(), ""},
2157 for _
, test
:= range tests
{
2158 if path
:= test
.t
.PkgPath(); path
!= test
.path
{
2159 t
.Errorf("%v.PkgPath() = %q, want %q", test
.t
, path
, test
.path
)
2164 func TestVariadicType(t
*testing
.T
) {
2165 // Test example from Type documentation.
2166 var f
func(x
int, y
...float64)
2168 if typ
.NumIn() == 2 && typ
.In(0) == TypeOf(int(0)) {
2170 if sl
.Kind() == Slice
{
2171 if sl
.Elem() == TypeOf(0.0) {
2179 t
.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
2180 s
:= fmt
.Sprintf("have NumIn() = %d", typ
.NumIn())
2181 for i
:= 0; i
< typ
.NumIn(); i
++ {
2182 s
+= fmt
.Sprintf(", In(%d) = %s", i
, typ
.In(i
))
2196 func (*inner
) m() {}
2197 func (*outer
) m() {}
2199 func TestNestedMethods(t
*testing
.T
) {
2200 t
.Skip("fails on gccgo due to function wrappers")
2201 typ
:= TypeOf((*outer
)(nil))
2202 if typ
.NumMethod() != 1 || typ
.Method(0).Func
.Pointer() != ValueOf((*outer
).m
).Pointer() {
2203 t
.Errorf("Wrong method table for outer: (m=%p)", (*outer
).m
)
2204 for i
:= 0; i
< typ
.NumMethod(); i
++ {
2206 t
.Errorf("\t%d: %s %#x\n", i
, m
.Name
, m
.Func
.Pointer())
2211 type InnerInt
struct {
2215 type OuterInt
struct {
2220 func (i
*InnerInt
) M() int {
2224 func TestEmbeddedMethods(t
*testing
.T
) {
2225 /* This part of the test fails on gccgo due to function wrappers.
2226 typ := TypeOf((*OuterInt)(nil))
2227 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
2228 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
2229 for i := 0; i < typ.NumMethod(); i++ {
2231 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2237 if v
:= ValueOf(i
).Method(0).Call(nil)[0].Int(); v
!= 3 {
2238 t
.Errorf("i.M() = %d, want 3", v
)
2241 o
:= &OuterInt
{1, InnerInt
{2}}
2242 if v
:= ValueOf(o
).Method(0).Call(nil)[0].Int(); v
!= 2 {
2243 t
.Errorf("i.M() = %d, want 2", v
)
2247 if v
:= f(o
); v
!= 2 {
2248 t
.Errorf("f(o) = %d, want 2", v
)
2252 func TestPtrTo(t
*testing
.T
) {
2256 for i
= 0; i
< 100; i
++ {
2259 for i
= 0; i
< 100; i
++ {
2262 if typ
!= TypeOf(i
) {
2263 t
.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ
, TypeOf(i
))
2267 func TestPtrToGC(t
*testing
.T
) {
2269 tt
:= TypeOf(T(nil))
2273 for i
:= 0; i
< n
; i
++ {
2278 v
.Elem().Set(ValueOf(p
).Convert(pt
))
2279 x
= append(x
, v
.Interface())
2283 for i
, xi
:= range x
{
2284 k
:= ValueOf(xi
).Elem().Elem().Elem().Interface().(uintptr)
2285 if k
!= uintptr(i
) {
2286 t
.Errorf("lost x[%d] = %d, want %d", i
, k
, i
)
2291 func TestAddr(t
*testing
.T
) {
2303 t
.Errorf("Addr.Elem.Set failed to set value")
2306 // Again but take address of the ValueOf value.
2307 // Exercises generation of PtrTypes not present in the binary.
2309 v
= ValueOf(&q
).Elem()
2318 t
.Errorf("Addr.Elem.Set failed to set value")
2321 // Starting without pointer we should get changed value
2324 v
= ValueOf(&qq
).Elem()
2330 if p
.X
!= 3 { // should be unchanged from last time
2331 t
.Errorf("somehow value Set changed original p")
2333 p
= v0
.Interface().(struct {
2337 t
.Errorf("Addr.Elem.Set valued to set value in top value")
2340 // Verify that taking the address of a type gives us a pointer
2341 // which we can convert back using the usual interface
2346 ps
:= ValueOf(&s
).Elem().Field(0).Addr().Interface()
2347 *(ps
.(**bool)) = new(bool)
2349 t
.Errorf("Addr.Interface direct assignment failed")
2353 /* gccgo does do allocations here.
2355 func noAlloc(t *testing.T, n int, f func(int)) {
2356 if testing.Short() {
2357 t.Skip("skipping malloc count in short mode")
2359 if runtime.GOMAXPROCS(0) > 1 {
2360 t.Skip("skipping; GOMAXPROCS>1")
2363 allocs := testing.AllocsPerRun(n, func() {
2368 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
2372 func TestAllocations(t *testing.T) {
2373 noAlloc(t, 100, func(j int) {
2378 if int(v.Int()) != 42+j {
2386 func TestSmallNegativeInt(t
*testing
.T
) {
2390 t
.Errorf("int16(-1).Int() returned %v", v
.Int())
2394 func TestIndex(t
*testing
.T
) {
2395 xs
:= []byte{1, 2, 3, 4, 5, 6, 7, 8}
2396 v
:= ValueOf(xs
).Index(3).Interface().(byte)
2398 t
.Errorf("xs.Index(3) = %v; expected %v", v
, xs
[3])
2400 xa
:= [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
2401 v
= ValueOf(xa
).Index(2).Interface().(byte)
2403 t
.Errorf("xa.Index(2) = %v; expected %v", v
, xa
[2])
2406 v
= ValueOf(s
).Index(3).Interface().(byte)
2408 t
.Errorf("s.Index(3) = %v; expected %v", v
, s
[3])
2412 func TestSlice(t
*testing
.T
) {
2413 xs
:= []int{1, 2, 3, 4, 5, 6, 7, 8}
2414 v
:= ValueOf(xs
).Slice(3, 5).Interface().([]int)
2416 t
.Errorf("len(xs.Slice(3, 5)) = %d", len(v
))
2419 t
.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v
))
2421 if !DeepEqual(v
[0:5], xs
[3:]) {
2422 t
.Errorf("xs.Slice(3, 5)[0:5] = %v", v
[0:5])
2424 xa
:= [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2425 v
= ValueOf(&xa
).Elem().Slice(2, 5).Interface().([]int)
2427 t
.Errorf("len(xa.Slice(2, 5)) = %d", len(v
))
2430 t
.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v
))
2432 if !DeepEqual(v
[0:6], xa
[2:]) {
2433 t
.Errorf("xs.Slice(2, 5)[0:6] = %v", v
[0:6])
2436 vs
:= ValueOf(s
).Slice(3, 5).Interface().(string)
2438 t
.Errorf("s.Slice(3, 5) = %q; expected %q", vs
, s
[3:5])
2442 func TestSlice3(t
*testing
.T
) {
2443 xs
:= []int{1, 2, 3, 4, 5, 6, 7, 8}
2444 v
:= ValueOf(xs
).Slice3(3, 5, 7).Interface().([]int)
2446 t
.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v
))
2449 t
.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v
))
2451 if !DeepEqual(v
[0:4], xs
[3:7:7]) {
2452 t
.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v
[0:4])
2454 rv
:= ValueOf(&xs
).Elem()
2455 shouldPanic(func() { rv
.Slice3(1, 2, 1) })
2456 shouldPanic(func() { rv
.Slice3(1, 1, 11) })
2457 shouldPanic(func() { rv
.Slice3(2, 2, 1) })
2459 xa
:= [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2460 v
= ValueOf(&xa
).Elem().Slice3(2, 5, 6).Interface().([]int)
2462 t
.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v
))
2465 t
.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v
))
2467 if !DeepEqual(v
[0:4], xa
[2:6:6]) {
2468 t
.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v
[0:4])
2470 rv
= ValueOf(&xa
).Elem()
2471 shouldPanic(func() { rv
.Slice3(1, 2, 1) })
2472 shouldPanic(func() { rv
.Slice3(1, 1, 11) })
2473 shouldPanic(func() { rv
.Slice3(2, 2, 1) })
2476 rv
= ValueOf(&s
).Elem()
2477 shouldPanic(func() { rv
.Slice3(1, 2, 3) })
2480 func TestSetLenCap(t
*testing
.T
) {
2481 xs
:= []int{1, 2, 3, 4, 5, 6, 7, 8}
2482 xa
:= [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2484 vs
:= ValueOf(&xs
).Elem()
2485 shouldPanic(func() { vs
.SetLen(10) })
2486 shouldPanic(func() { vs
.SetCap(10) })
2487 shouldPanic(func() { vs
.SetLen(-1) })
2488 shouldPanic(func() { vs
.SetCap(-1) })
2489 shouldPanic(func() { vs
.SetCap(6) }) // smaller than len
2491 if len(xs
) != 5 ||
cap(xs
) != 8 {
2492 t
.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs
), cap(xs
))
2495 if len(xs
) != 5 ||
cap(xs
) != 6 {
2496 t
.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs
), cap(xs
))
2499 if len(xs
) != 5 ||
cap(xs
) != 5 {
2500 t
.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs
), cap(xs
))
2502 shouldPanic(func() { vs
.SetCap(4) }) // smaller than len
2503 shouldPanic(func() { vs
.SetLen(6) }) // bigger than cap
2505 va
:= ValueOf(&xa
).Elem()
2506 shouldPanic(func() { va
.SetLen(8) })
2507 shouldPanic(func() { va
.SetCap(8) })
2510 func TestVariadic(t
*testing
.T
) {
2515 V(fmt
.Fprintf
).Call([]Value
{V(&b
), V("%s, %d world"), V("hello"), V(42)})
2516 if b
.String() != "hello, 42 world" {
2517 t
.Errorf("after Fprintf Call: %q != %q", b
.String(), "hello 42 world")
2521 V(fmt
.Fprintf
).CallSlice([]Value
{V(&b
), V("%s, %d world"), V([]interface{}{"hello", 42})})
2522 if b
.String() != "hello, 42 world" {
2523 t
.Errorf("after Fprintf CallSlice: %q != %q", b
.String(), "hello 42 world")
2527 func TestFuncArg(t
*testing
.T
) {
2528 f1
:= func(i
int, f
func(int) int) int { return f(i
) }
2529 f2
:= func(i
int) int { return i
+ 1 }
2530 r
:= ValueOf(f1
).Call([]Value
{ValueOf(100), ValueOf(f2
)})
2531 if r
[0].Int() != 101 {
2532 t
.Errorf("function returned %d, want 101", r
[0].Int())
2536 var tagGetTests
= []struct {
2541 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
2542 {`protobuf:"PB(1,2)"`, `foo`, ``},
2543 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
2544 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
2545 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
2548 func TestTagGet(t
*testing
.T
) {
2549 for _
, tt
:= range tagGetTests
{
2550 if v
:= tt
.Tag
.Get(tt
.Key
); v
!= tt
.Value
{
2551 t
.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt
.Tag
, tt
.Key
, v
, tt
.Value
)
2556 func TestBytes(t
*testing
.T
) {
2559 y
:= ValueOf(x
).Bytes()
2560 if !bytes
.Equal(x
, y
) {
2561 t
.Fatalf("ValueOf(%v).Bytes() = %v", x
, y
)
2564 t
.Errorf("ValueOf(%p).Bytes() = %p", &x
[0], &y
[0])
2568 func TestSetBytes(t
*testing
.T
) {
2571 y
:= []byte{1, 2, 3, 4}
2572 ValueOf(&x
).Elem().SetBytes(y
)
2573 if !bytes
.Equal(x
, y
) {
2574 t
.Fatalf("ValueOf(%v).Bytes() = %v", x
, y
)
2577 t
.Errorf("ValueOf(%p).Bytes() = %p", &x
[0], &y
[0])
2581 type Private
struct {
2586 func (p
*Private
) m() {
2589 type Public
struct {
2594 func (p
*Public
) M() {
2597 func TestUnexported(t
*testing
.T
) {
2600 isValid(v
.Elem().Field(0))
2601 isValid(v
.Elem().Field(1))
2602 isValid(v
.Elem().FieldByName("X"))
2603 isValid(v
.Elem().FieldByName("Y"))
2604 isValid(v
.Type().Method(0).Func
)
2605 isNonNil(v
.Elem().Field(0).Interface())
2606 isNonNil(v
.Elem().Field(1).Interface())
2607 isNonNil(v
.Elem().FieldByName("X").Interface())
2608 isNonNil(v
.Elem().FieldByName("Y").Interface())
2609 isNonNil(v
.Type().Method(0).Func
.Interface())
2613 isValid(v
.Elem().Field(0))
2614 isValid(v
.Elem().Field(1))
2615 isValid(v
.Elem().FieldByName("x"))
2616 isValid(v
.Elem().FieldByName("y"))
2617 isValid(v
.Type().Method(0).Func
)
2618 shouldPanic(func() { v
.Elem().Field(0).Interface() })
2619 shouldPanic(func() { v
.Elem().Field(1).Interface() })
2620 shouldPanic(func() { v
.Elem().FieldByName("x").Interface() })
2621 shouldPanic(func() { v
.Elem().FieldByName("y").Interface() })
2622 shouldPanic(func() { v
.Type().Method(0).Func
.Interface() })
2625 func shouldPanic(f
func()) {
2627 if recover() == nil {
2628 panic("did not panic")
2634 func isNonNil(x
interface{}) {
2636 panic("nil interface")
2640 func isValid(v Value
) {
2646 func TestAlias(t
*testing
.T
) {
2647 x
:= string("hello")
2648 v
:= ValueOf(&x
).Elem()
2649 oldvalue
:= v
.Interface()
2650 v
.SetString("world")
2651 newvalue
:= v
.Interface()
2653 if oldvalue
!= "hello" || newvalue
!= "world" {
2654 t
.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue
, newvalue
)
2660 func EmptyInterfaceV(x
interface{}) Value
{
2661 return ValueOf(&x
).Elem()
2664 func ReaderV(x io
.Reader
) Value
{
2665 return ValueOf(&x
).Elem()
2668 func ReadWriterV(x io
.ReadWriter
) Value
{
2669 return ValueOf(&x
).Elem()
2673 type MyString
string
2675 type MyRunes
[]int32
2679 var convertTests
= []struct {
2685 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
2691 var numbers = []string{
2692 "int8", "uint8", "int16", "uint16",
2693 "int32", "uint32", "int64", "uint64",
2694 "int", "uint", "uintptr",
2695 "float32", "float64",
2699 // all pairs but in an unusual order,
2700 // to emit all the int8, uint8 cases
2701 // before n grows too big.
2703 for i, f := range numbers {
2704 for _, g := range numbers[i:] {
2705 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
2708 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
2715 {V(int8(1)), V(int8(1))},
2716 {V(int8(2)), V(uint8(2))},
2717 {V(uint8(3)), V(int8(3))},
2718 {V(int8(4)), V(int16(4))},
2719 {V(int16(5)), V(int8(5))},
2720 {V(int8(6)), V(uint16(6))},
2721 {V(uint16(7)), V(int8(7))},
2722 {V(int8(8)), V(int32(8))},
2723 {V(int32(9)), V(int8(9))},
2724 {V(int8(10)), V(uint32(10))},
2725 {V(uint32(11)), V(int8(11))},
2726 {V(int8(12)), V(int64(12))},
2727 {V(int64(13)), V(int8(13))},
2728 {V(int8(14)), V(uint64(14))},
2729 {V(uint64(15)), V(int8(15))},
2730 {V(int8(16)), V(int(16))},
2731 {V(int(17)), V(int8(17))},
2732 {V(int8(18)), V(uint(18))},
2733 {V(uint(19)), V(int8(19))},
2734 {V(int8(20)), V(uintptr(20))},
2735 {V(uintptr(21)), V(int8(21))},
2736 {V(int8(22)), V(float32(22))},
2737 {V(float32(23)), V(int8(23))},
2738 {V(int8(24)), V(float64(24))},
2739 {V(float64(25)), V(int8(25))},
2740 {V(uint8(26)), V(uint8(26))},
2741 {V(uint8(27)), V(int16(27))},
2742 {V(int16(28)), V(uint8(28))},
2743 {V(uint8(29)), V(uint16(29))},
2744 {V(uint16(30)), V(uint8(30))},
2745 {V(uint8(31)), V(int32(31))},
2746 {V(int32(32)), V(uint8(32))},
2747 {V(uint8(33)), V(uint32(33))},
2748 {V(uint32(34)), V(uint8(34))},
2749 {V(uint8(35)), V(int64(35))},
2750 {V(int64(36)), V(uint8(36))},
2751 {V(uint8(37)), V(uint64(37))},
2752 {V(uint64(38)), V(uint8(38))},
2753 {V(uint8(39)), V(int(39))},
2754 {V(int(40)), V(uint8(40))},
2755 {V(uint8(41)), V(uint(41))},
2756 {V(uint(42)), V(uint8(42))},
2757 {V(uint8(43)), V(uintptr(43))},
2758 {V(uintptr(44)), V(uint8(44))},
2759 {V(uint8(45)), V(float32(45))},
2760 {V(float32(46)), V(uint8(46))},
2761 {V(uint8(47)), V(float64(47))},
2762 {V(float64(48)), V(uint8(48))},
2763 {V(int16(49)), V(int16(49))},
2764 {V(int16(50)), V(uint16(50))},
2765 {V(uint16(51)), V(int16(51))},
2766 {V(int16(52)), V(int32(52))},
2767 {V(int32(53)), V(int16(53))},
2768 {V(int16(54)), V(uint32(54))},
2769 {V(uint32(55)), V(int16(55))},
2770 {V(int16(56)), V(int64(56))},
2771 {V(int64(57)), V(int16(57))},
2772 {V(int16(58)), V(uint64(58))},
2773 {V(uint64(59)), V(int16(59))},
2774 {V(int16(60)), V(int(60))},
2775 {V(int(61)), V(int16(61))},
2776 {V(int16(62)), V(uint(62))},
2777 {V(uint(63)), V(int16(63))},
2778 {V(int16(64)), V(uintptr(64))},
2779 {V(uintptr(65)), V(int16(65))},
2780 {V(int16(66)), V(float32(66))},
2781 {V(float32(67)), V(int16(67))},
2782 {V(int16(68)), V(float64(68))},
2783 {V(float64(69)), V(int16(69))},
2784 {V(uint16(70)), V(uint16(70))},
2785 {V(uint16(71)), V(int32(71))},
2786 {V(int32(72)), V(uint16(72))},
2787 {V(uint16(73)), V(uint32(73))},
2788 {V(uint32(74)), V(uint16(74))},
2789 {V(uint16(75)), V(int64(75))},
2790 {V(int64(76)), V(uint16(76))},
2791 {V(uint16(77)), V(uint64(77))},
2792 {V(uint64(78)), V(uint16(78))},
2793 {V(uint16(79)), V(int(79))},
2794 {V(int(80)), V(uint16(80))},
2795 {V(uint16(81)), V(uint(81))},
2796 {V(uint(82)), V(uint16(82))},
2797 {V(uint16(83)), V(uintptr(83))},
2798 {V(uintptr(84)), V(uint16(84))},
2799 {V(uint16(85)), V(float32(85))},
2800 {V(float32(86)), V(uint16(86))},
2801 {V(uint16(87)), V(float64(87))},
2802 {V(float64(88)), V(uint16(88))},
2803 {V(int32(89)), V(int32(89))},
2804 {V(int32(90)), V(uint32(90))},
2805 {V(uint32(91)), V(int32(91))},
2806 {V(int32(92)), V(int64(92))},
2807 {V(int64(93)), V(int32(93))},
2808 {V(int32(94)), V(uint64(94))},
2809 {V(uint64(95)), V(int32(95))},
2810 {V(int32(96)), V(int(96))},
2811 {V(int(97)), V(int32(97))},
2812 {V(int32(98)), V(uint(98))},
2813 {V(uint(99)), V(int32(99))},
2814 {V(int32(100)), V(uintptr(100))},
2815 {V(uintptr(101)), V(int32(101))},
2816 {V(int32(102)), V(float32(102))},
2817 {V(float32(103)), V(int32(103))},
2818 {V(int32(104)), V(float64(104))},
2819 {V(float64(105)), V(int32(105))},
2820 {V(uint32(106)), V(uint32(106))},
2821 {V(uint32(107)), V(int64(107))},
2822 {V(int64(108)), V(uint32(108))},
2823 {V(uint32(109)), V(uint64(109))},
2824 {V(uint64(110)), V(uint32(110))},
2825 {V(uint32(111)), V(int(111))},
2826 {V(int(112)), V(uint32(112))},
2827 {V(uint32(113)), V(uint(113))},
2828 {V(uint(114)), V(uint32(114))},
2829 {V(uint32(115)), V(uintptr(115))},
2830 {V(uintptr(116)), V(uint32(116))},
2831 {V(uint32(117)), V(float32(117))},
2832 {V(float32(118)), V(uint32(118))},
2833 {V(uint32(119)), V(float64(119))},
2834 {V(float64(120)), V(uint32(120))},
2835 {V(int64(121)), V(int64(121))},
2836 {V(int64(122)), V(uint64(122))},
2837 {V(uint64(123)), V(int64(123))},
2838 {V(int64(124)), V(int(124))},
2839 {V(int(125)), V(int64(125))},
2840 {V(int64(126)), V(uint(126))},
2841 {V(uint(127)), V(int64(127))},
2842 {V(int64(128)), V(uintptr(128))},
2843 {V(uintptr(129)), V(int64(129))},
2844 {V(int64(130)), V(float32(130))},
2845 {V(float32(131)), V(int64(131))},
2846 {V(int64(132)), V(float64(132))},
2847 {V(float64(133)), V(int64(133))},
2848 {V(uint64(134)), V(uint64(134))},
2849 {V(uint64(135)), V(int(135))},
2850 {V(int(136)), V(uint64(136))},
2851 {V(uint64(137)), V(uint(137))},
2852 {V(uint(138)), V(uint64(138))},
2853 {V(uint64(139)), V(uintptr(139))},
2854 {V(uintptr(140)), V(uint64(140))},
2855 {V(uint64(141)), V(float32(141))},
2856 {V(float32(142)), V(uint64(142))},
2857 {V(uint64(143)), V(float64(143))},
2858 {V(float64(144)), V(uint64(144))},
2859 {V(int(145)), V(int(145))},
2860 {V(int(146)), V(uint(146))},
2861 {V(uint(147)), V(int(147))},
2862 {V(int(148)), V(uintptr(148))},
2863 {V(uintptr(149)), V(int(149))},
2864 {V(int(150)), V(float32(150))},
2865 {V(float32(151)), V(int(151))},
2866 {V(int(152)), V(float64(152))},
2867 {V(float64(153)), V(int(153))},
2868 {V(uint(154)), V(uint(154))},
2869 {V(uint(155)), V(uintptr(155))},
2870 {V(uintptr(156)), V(uint(156))},
2871 {V(uint(157)), V(float32(157))},
2872 {V(float32(158)), V(uint(158))},
2873 {V(uint(159)), V(float64(159))},
2874 {V(float64(160)), V(uint(160))},
2875 {V(uintptr(161)), V(uintptr(161))},
2876 {V(uintptr(162)), V(float32(162))},
2877 {V(float32(163)), V(uintptr(163))},
2878 {V(uintptr(164)), V(float64(164))},
2879 {V(float64(165)), V(uintptr(165))},
2880 {V(float32(166)), V(float32(166))},
2881 {V(float32(167)), V(float64(167))},
2882 {V(float64(168)), V(float32(168))},
2883 {V(float64(169)), V(float64(169))},
2886 {V(float64(1.5)), V(int(1))},
2889 {V(complex64(1i
)), V(complex64(1i
))},
2890 {V(complex64(2i
)), V(complex128(2i
))},
2891 {V(complex128(3i
)), V(complex64(3i
))},
2892 {V(complex128(4i
)), V(complex128(4i
))},
2895 {V(string("hello")), V(string("hello"))},
2896 {V(string("bytes1")), V([]byte("bytes1"))},
2897 {V([]byte("bytes2")), V(string("bytes2"))},
2898 {V([]byte("bytes3")), V([]byte("bytes3"))},
2899 {V(string("runes♝")), V([]rune("runes♝"))},
2900 {V([]rune("runes♕")), V(string("runes♕"))},
2901 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
2902 {V(int('a')), V(string("a"))},
2903 {V(int8('a')), V(string("a"))},
2904 {V(int16('a')), V(string("a"))},
2905 {V(int32('a')), V(string("a"))},
2906 {V(int64('a')), V(string("a"))},
2907 {V(uint('a')), V(string("a"))},
2908 {V(uint8('a')), V(string("a"))},
2909 {V(uint16('a')), V(string("a"))},
2910 {V(uint32('a')), V(string("a"))},
2911 {V(uint64('a')), V(string("a"))},
2912 {V(uintptr('a')), V(string("a"))},
2913 {V(int(-1)), V(string("\uFFFD"))},
2914 {V(int8(-2)), V(string("\uFFFD"))},
2915 {V(int16(-3)), V(string("\uFFFD"))},
2916 {V(int32(-4)), V(string("\uFFFD"))},
2917 {V(int64(-5)), V(string("\uFFFD"))},
2918 {V(uint(0x110001)), V(string("\uFFFD"))},
2919 {V(uint32(0x110002)), V(string("\uFFFD"))},
2920 {V(uint64(0x110003)), V(string("\uFFFD"))},
2921 {V(uintptr(0x110004)), V(string("\uFFFD"))},
2924 {V(MyString("hello")), V(string("hello"))},
2925 {V(string("hello")), V(MyString("hello"))},
2926 {V(string("hello")), V(string("hello"))},
2927 {V(MyString("hello")), V(MyString("hello"))},
2928 {V(MyString("bytes1")), V([]byte("bytes1"))},
2929 {V([]byte("bytes2")), V(MyString("bytes2"))},
2930 {V([]byte("bytes3")), V([]byte("bytes3"))},
2931 {V(MyString("runes♝")), V([]rune("runes♝"))},
2932 {V([]rune("runes♕")), V(MyString("runes♕"))},
2933 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
2934 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
2935 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
2936 {V(int('a')), V(MyString("a"))},
2937 {V(int8('a')), V(MyString("a"))},
2938 {V(int16('a')), V(MyString("a"))},
2939 {V(int32('a')), V(MyString("a"))},
2940 {V(int64('a')), V(MyString("a"))},
2941 {V(uint('a')), V(MyString("a"))},
2942 {V(uint8('a')), V(MyString("a"))},
2943 {V(uint16('a')), V(MyString("a"))},
2944 {V(uint32('a')), V(MyString("a"))},
2945 {V(uint64('a')), V(MyString("a"))},
2946 {V(uintptr('a')), V(MyString("a"))},
2947 {V(int(-1)), V(MyString("\uFFFD"))},
2948 {V(int8(-2)), V(MyString("\uFFFD"))},
2949 {V(int16(-3)), V(MyString("\uFFFD"))},
2950 {V(int32(-4)), V(MyString("\uFFFD"))},
2951 {V(int64(-5)), V(MyString("\uFFFD"))},
2952 {V(uint(0x110001)), V(MyString("\uFFFD"))},
2953 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
2954 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
2955 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
2958 {V(string("bytes1")), V(MyBytes("bytes1"))},
2959 {V(MyBytes("bytes2")), V(string("bytes2"))},
2960 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
2961 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
2962 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
2965 {V(string("runes♝")), V(MyRunes("runes♝"))},
2966 {V(MyRunes("runes♕")), V(string("runes♕"))},
2967 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
2968 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
2969 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
2971 // named types and equal underlying types
2972 {V(new(int)), V(new(integer
))},
2973 {V(new(integer
)), V(new(int))},
2974 {V(Empty
{}), V(struct{}{})},
2975 {V(new(Empty
)), V(new(struct{}))},
2976 {V(struct{}{}), V(Empty
{})},
2977 {V(new(struct{})), V(new(Empty
))},
2978 {V(Empty
{}), V(Empty
{})},
2979 {V(MyBytes
{}), V([]byte{})},
2980 {V([]byte{}), V(MyBytes
{})},
2981 {V((func())(nil)), V(MyFunc(nil))},
2982 {V((MyFunc
)(nil)), V((func())(nil))},
2984 // can convert *byte and *MyByte
2985 {V((*byte)(nil)), V((*MyByte
)(nil))},
2986 {V((*MyByte
)(nil)), V((*byte)(nil))},
2988 // cannot convert mismatched array sizes
2989 {V([2]byte{}), V([2]byte{})},
2990 {V([3]byte{}), V([3]byte{})},
2992 // cannot convert other instances
2993 {V((**byte)(nil)), V((**byte)(nil))},
2994 {V((**MyByte
)(nil)), V((**MyByte
)(nil))},
2995 {V((chan byte)(nil)), V((chan byte)(nil))},
2996 {V((chan MyByte
)(nil)), V((chan MyByte
)(nil))},
2997 {V(([]byte)(nil)), V(([]byte)(nil))},
2998 {V(([]MyByte
)(nil)), V(([]MyByte
)(nil))},
2999 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3000 {V((map[int]MyByte
)(nil)), V((map[int]MyByte
)(nil))},
3001 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
3002 {V((map[MyByte
]int)(nil)), V((map[MyByte
]int)(nil))},
3003 {V([2]byte{}), V([2]byte{})},
3004 {V([2]MyByte
{}), V([2]MyByte
{})},
3007 {V((***int)(nil)), V((***int)(nil))},
3008 {V((***byte)(nil)), V((***byte)(nil))},
3009 {V((***int32)(nil)), V((***int32)(nil))},
3010 {V((***int64)(nil)), V((***int64)(nil))},
3011 {V((chan int)(nil)), V((<-chan int)(nil))},
3012 {V((chan int)(nil)), V((chan<- int)(nil))},
3013 {V((chan string)(nil)), V((<-chan string)(nil))},
3014 {V((chan string)(nil)), V((chan<- string)(nil))},
3015 {V((chan byte)(nil)), V((chan byte)(nil))},
3016 {V((chan MyByte
)(nil)), V((chan MyByte
)(nil))},
3017 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
3018 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3019 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
3020 {V([]uint(nil)), V([]uint(nil))},
3021 {V([]int(nil)), V([]int(nil))},
3022 {V(new(interface{})), V(new(interface{}))},
3023 {V(new(io
.Reader
)), V(new(io
.Reader
))},
3024 {V(new(io
.Writer
)), V(new(io
.Writer
))},
3027 {V(int(1)), EmptyInterfaceV(int(1))},
3028 {V(string("hello")), EmptyInterfaceV(string("hello"))},
3029 {V(new(bytes
.Buffer
)), ReaderV(new(bytes
.Buffer
))},
3030 {ReadWriterV(new(bytes
.Buffer
)), ReaderV(new(bytes
.Buffer
))},
3031 {V(new(bytes
.Buffer
)), ReadWriterV(new(bytes
.Buffer
))},
3034 func TestConvert(t
*testing
.T
) {
3035 canConvert
:= map[[2]Type
]bool{}
3036 all
:= map[Type
]bool{}
3038 for _
, tt
:= range convertTests
{
3040 if !t1
.ConvertibleTo(t1
) {
3041 t
.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1
, t1
)
3046 if !t1
.ConvertibleTo(t2
) {
3047 t
.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1
, t2
)
3053 canConvert
[[2]Type
{t1
, t2
}] = true
3055 // vout1 represents the in value converted to the in type.
3057 vout1
:= v1
.Convert(t1
)
3058 out1
:= vout1
.Interface()
3059 if vout1
.Type() != tt
.in
.Type() ||
!DeepEqual(out1
, tt
.in
.Interface()) {
3060 t
.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt
.in
.Interface(), t1
, out1
, tt
.in
.Interface())
3063 // vout2 represents the in value converted to the out type.
3064 vout2
:= v1
.Convert(t2
)
3065 out2
:= vout2
.Interface()
3066 if vout2
.Type() != tt
.out
.Type() ||
!DeepEqual(out2
, tt
.out
.Interface()) {
3067 t
.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt
.in
.Interface(), t2
, out2
, tt
.out
.Interface())
3070 // vout3 represents a new value of the out type, set to vout2. This makes
3071 // sure the converted value vout2 is really usable as a regular value.
3072 vout3
:= New(t2
).Elem()
3074 out3
:= vout3
.Interface()
3075 if vout3
.Type() != tt
.out
.Type() ||
!DeepEqual(out3
, tt
.out
.Interface()) {
3076 t
.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt
.in
.Interface(), t2
, out3
, tt
.out
.Interface())
3080 t
.Errorf("table entry %v is RO, should not be", v1
)
3083 t
.Errorf("self-conversion output %v is RO, should not be", vout1
)
3086 t
.Errorf("conversion output %v is RO, should not be", vout2
)
3089 t
.Errorf("set(conversion output) %v is RO, should not be", vout3
)
3091 if !IsRO(MakeRO(v1
).Convert(t1
)) {
3092 t
.Errorf("RO self-conversion output %v is not RO, should be", v1
)
3094 if !IsRO(MakeRO(v1
).Convert(t2
)) {
3095 t
.Errorf("RO conversion output %v is not RO, should be", v1
)
3099 // Assume that of all the types we saw during the tests,
3100 // if there wasn't an explicit entry for a conversion between
3101 // a pair of types, then it's not to be allowed. This checks for
3102 // things like 'int64' converting to '*int'.
3103 for t1
:= range all
{
3104 for t2
:= range all
{
3105 expectOK
:= t1
== t2 || canConvert
[[2]Type
{t1
, t2
}] || t2
.Kind() == Interface
&& t2
.NumMethod() == 0
3106 if ok
:= t1
.ConvertibleTo(t2
); ok
!= expectOK
{
3107 t
.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1
, t2
, ok
, expectOK
)
3113 func TestOverflow(t
*testing
.T
) {
3114 if ovf
:= V(float64(0)).OverflowFloat(1e300
); ovf
{
3115 t
.Errorf("%v wrongly overflows float64", 1e300
)
3118 maxFloat32
:= float64((1<<24 - 1) << (127 - 23))
3119 if ovf
:= V(float32(0)).OverflowFloat(maxFloat32
); ovf
{
3120 t
.Errorf("%v wrongly overflows float32", maxFloat32
)
3122 ovfFloat32
:= float64((1<<24-1)<<(127-23) + 1<<(127-52))
3123 if ovf
:= V(float32(0)).OverflowFloat(ovfFloat32
); !ovf
{
3124 t
.Errorf("%v should overflow float32", ovfFloat32
)
3126 if ovf
:= V(float32(0)).OverflowFloat(-ovfFloat32
); !ovf
{
3127 t
.Errorf("%v should overflow float32", -ovfFloat32
)
3130 maxInt32
:= int64(0x7fffffff)
3131 if ovf
:= V(int32(0)).OverflowInt(maxInt32
); ovf
{
3132 t
.Errorf("%v wrongly overflows int32", maxInt32
)
3134 if ovf
:= V(int32(0)).OverflowInt(-1 << 31); ovf
{
3135 t
.Errorf("%v wrongly overflows int32", -int64(1)<<31)
3137 ovfInt32
:= int64(1 << 31)
3138 if ovf
:= V(int32(0)).OverflowInt(ovfInt32
); !ovf
{
3139 t
.Errorf("%v should overflow int32", ovfInt32
)
3142 maxUint32
:= uint64(0xffffffff)
3143 if ovf
:= V(uint32(0)).OverflowUint(maxUint32
); ovf
{
3144 t
.Errorf("%v wrongly overflows uint32", maxUint32
)
3146 ovfUint32
:= uint64(1 << 32)
3147 if ovf
:= V(uint32(0)).OverflowUint(ovfUint32
); !ovf
{
3148 t
.Errorf("%v should overflow uint32", ovfUint32
)
3152 func checkSameType(t
*testing
.T
, x
, y
interface{}) {
3153 if TypeOf(x
) != TypeOf(y
) {
3154 t
.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x
), TypeOf(y
))
3158 func TestArrayOf(t
*testing
.T
) {
3159 // check construction and use of type not in binary
3161 at
:= ArrayOf(10, TypeOf(T(1)))
3163 for i
:= 0; i
< v
.Len(); i
++ {
3164 v
.Index(i
).Set(ValueOf(T(i
)))
3166 s
:= fmt
.Sprint(v
.Interface())
3167 want
:= "[0 1 2 3 4 5 6 7 8 9]"
3169 t
.Errorf("constructed array = %s, want %s", s
, want
)
3172 // check that type already in binary is found
3173 checkSameType(t
, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T
{})
3176 func TestSliceOf(t
*testing
.T
) {
3177 // check construction and use of type not in binary
3179 st
:= SliceOf(TypeOf(T(1)))
3180 v
:= MakeSlice(st
, 10, 10)
3182 for i
:= 0; i
< v
.Len(); i
++ {
3183 v
.Index(i
).Set(ValueOf(T(i
)))
3186 s
:= fmt
.Sprint(v
.Interface())
3187 want
:= "[0 1 2 3 4 5 6 7 8 9]"
3189 t
.Errorf("constructed slice = %s, want %s", s
, want
)
3192 // check that type already in binary is found
3194 checkSameType(t
, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1
{})
3197 func TestSliceOverflow(t
*testing
.T
) {
3198 // check that MakeSlice panics when size of slice overflows uint
3201 l
:= (1<<(unsafe
.Sizeof((*byte)(nil))*8)-1)/s
+ 1
3203 t
.Fatal("slice size does not overflow")
3206 st
:= SliceOf(TypeOf(x
))
3210 t
.Fatal("slice overflow does not panic")
3213 MakeSlice(st
, int(l
), int(l
))
3216 func TestSliceOfGC(t
*testing
.T
) {
3218 tt
:= TypeOf(T(nil))
3222 for i
:= 0; i
< n
; i
++ {
3223 v
:= MakeSlice(st
, n
, n
)
3224 for j
:= 0; j
< v
.Len(); j
++ {
3226 *p
= uintptr(i
*n
+ j
)
3227 v
.Index(j
).Set(ValueOf(p
).Convert(tt
))
3229 x
= append(x
, v
.Interface())
3233 for i
, xi
:= range x
{
3235 for j
:= 0; j
< v
.Len(); j
++ {
3236 k
:= v
.Index(j
).Elem().Interface()
3237 if k
!= uintptr(i
*n
+j
) {
3238 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
3244 func TestChanOf(t
*testing
.T
) {
3245 // check construction and use of type not in binary
3247 ct
:= ChanOf(BothDir
, TypeOf(T("")))
3248 v
:= MakeChan(ct
, 2)
3250 v
.Send(ValueOf(T("hello")))
3252 v
.Send(ValueOf(T("world")))
3259 if s1
!= "hello" || s2
!= "world" {
3260 t
.Errorf("constructed chan: have %q, %q, want %q, %q", s1
, s2
, "hello", "world")
3263 // check that type already in binary is found
3265 checkSameType(t
, Zero(ChanOf(BothDir
, TypeOf(T1(1)))).Interface(), (chan T1
)(nil))
3268 func TestChanOfGC(t
*testing
.T
) {
3269 done
:= make(chan bool, 1)
3273 case <-time
.After(5 * time
.Second
):
3274 panic("deadlock in TestChanOfGC")
3283 tt
:= TypeOf(T(nil))
3284 ct
:= ChanOf(BothDir
, tt
)
3286 // NOTE: The garbage collector handles allocated channels specially,
3287 // so we have to save pointers to channels in x; the pointer code will
3288 // use the gc info in the newly constructed chan type.
3291 for i
:= 0; i
< n
; i
++ {
3292 v
:= MakeChan(ct
, n
)
3293 for j
:= 0; j
< n
; j
++ {
3295 *p
= uintptr(i
*n
+ j
)
3296 v
.Send(ValueOf(p
).Convert(tt
))
3300 x
= append(x
, pv
.Interface())
3304 for i
, xi
:= range x
{
3305 v
:= ValueOf(xi
).Elem()
3306 for j
:= 0; j
< n
; j
++ {
3308 k
:= pv
.Elem().Interface()
3309 if k
!= uintptr(i
*n
+j
) {
3310 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
3316 func TestMapOf(t
*testing
.T
) {
3317 // check construction and use of type not in binary
3321 v
:= MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
3323 v
.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
3326 s
:= fmt
.Sprint(v
.Interface())
3329 t
.Errorf("constructed map = %s, want %s", s
, want
)
3332 // check that type already in binary is found
3333 checkSameType(t
, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V
]K(nil))
3335 // check that invalid key type panics
3336 shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
3339 func TestMapOfGCKeys(t
*testing
.T
) {
3341 tt
:= TypeOf(T(nil))
3342 mt
:= MapOf(tt
, TypeOf(false))
3344 // NOTE: The garbage collector handles allocated maps specially,
3345 // so we have to save pointers to maps in x; the pointer code will
3346 // use the gc info in the newly constructed map type.
3349 for i
:= 0; i
< n
; i
++ {
3351 for j
:= 0; j
< n
; j
++ {
3353 *p
= uintptr(i
*n
+ j
)
3354 v
.SetMapIndex(ValueOf(p
).Convert(tt
), ValueOf(true))
3358 x
= append(x
, pv
.Interface())
3362 for i
, xi
:= range x
{
3363 v
:= ValueOf(xi
).Elem()
3365 for _
, kv
:= range v
.MapKeys() {
3366 out
= append(out
, int(kv
.Elem().Interface().(uintptr)))
3369 for j
, k
:= range out
{
3371 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
3377 func TestMapOfGCValues(t
*testing
.T
) {
3379 tt
:= TypeOf(T(nil))
3380 mt
:= MapOf(TypeOf(1), tt
)
3382 // NOTE: The garbage collector handles allocated maps specially,
3383 // so we have to save pointers to maps in x; the pointer code will
3384 // use the gc info in the newly constructed map type.
3387 for i
:= 0; i
< n
; i
++ {
3389 for j
:= 0; j
< n
; j
++ {
3391 *p
= uintptr(i
*n
+ j
)
3392 v
.SetMapIndex(ValueOf(j
), ValueOf(p
).Convert(tt
))
3396 x
= append(x
, pv
.Interface())
3400 for i
, xi
:= range x
{
3401 v
:= ValueOf(xi
).Elem()
3402 for j
:= 0; j
< n
; j
++ {
3403 k
:= v
.MapIndex(ValueOf(j
)).Elem().Interface().(uintptr)
3404 if k
!= uintptr(i
*n
+j
) {
3405 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
3417 func BenchmarkFieldByName1(b
*testing
.B
) {
3419 for i
:= 0; i
< b
.N
; i
++ {
3424 func BenchmarkFieldByName2(b
*testing
.B
) {
3426 for i
:= 0; i
< b
.N
; i
++ {
3501 func TestEmbed(t
*testing
.T
) {
3503 f
, ok
:= typ
.FieldByName("X")
3505 t
.Fatalf(`FieldByName("X") should fail, returned %v`, f
.Index
)
3509 func BenchmarkFieldByName3(b
*testing
.B
) {
3511 for i
:= 0; i
< b
.N
; i
++ {
3521 func BenchmarkInterfaceBig(b
*testing
.B
) {
3523 for i
:= 0; i
< b
.N
; i
++ {
3529 func TestAllocsInterfaceBig(t
*testing
.T
) {
3530 if testing
.Short() {
3531 t
.Skip("skipping malloc count in short mode")
3534 if allocs
:= testing
.AllocsPerRun(100, func() { v
.Interface() }); allocs
> 0 {
3535 t
.Error("allocs:", allocs
)
3539 func BenchmarkInterfaceSmall(b
*testing
.B
) {
3540 v
:= ValueOf(int64(0))
3541 for i
:= 0; i
< b
.N
; i
++ {
3546 func TestAllocsInterfaceSmall(t
*testing
.T
) {
3547 if testing
.Short() {
3548 t
.Skip("skipping malloc count in short mode")
3550 v
:= ValueOf(int64(0))
3551 if allocs
:= testing
.AllocsPerRun(100, func() { v
.Interface() }); allocs
> 0 {
3552 t
.Error("allocs:", allocs
)
3556 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
3557 // The basic usage is:
3560 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
3563 // Each iteration of the loop returns a different set of results, until all
3564 // possible result sets have been explored. It is okay for different code paths
3565 // to make different method call sequences on x, but there must be no
3566 // other source of non-determinism in the call sequences.
3568 // When faced with a new decision, x chooses randomly. Future explorations
3569 // of that path will choose successive values for the result. Thus, stopping
3570 // the loop after a fixed number of iterations gives somewhat stochastic
3576 // v := make([]bool, x.Choose(4))
3577 // for i := range v {
3583 // prints (in some order):
3592 // [false false false]
3595 // [false false false false]
3597 // [true true true true]
3599 type exhaustive
struct {
3605 type choice
struct {
3611 func (x
*exhaustive
) Next() bool {
3613 x
.r
= rand
.New(rand
.NewSource(time
.Now().UnixNano()))
3620 for i
:= len(x
.last
) - 1; i
>= 0; i
-- {
3624 x
.last
= x
.last
[:i
+1]
3631 func (x
*exhaustive
) Choose(max
int) int {
3632 if x
.pos
>= len(x
.last
) {
3633 x
.last
= append(x
.last
, choice
{x
.r
.Intn(max
), 0, max
})
3638 panic("inconsistent use of exhaustive tester")
3640 return (c
.n
+ c
.off
) % max
3643 func (x
*exhaustive
) Maybe() bool {
3644 return x
.Choose(2) == 1