github.com/turingchain2020/turingchain@v1.1.21/types/reflect_test.go (about) 1 // Copyright Turing Corp. 2018 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. 4 5 package types 6 7 import ( 8 "reflect" 9 "testing" 10 11 "github.com/stretchr/testify/assert" 12 ) 13 14 type T struct { 15 a int 16 b *int 17 } 18 19 func (t *T) Query_Add(in *ReqNil) (Message, error) { 20 result := t.a + *t.b 21 return &Int64{Data: int64(result)}, nil 22 } 23 24 var qdata = NewQueryData("Query_") 25 26 func TestValue(t *testing.T) { 27 b := 20 28 data := &T{10, &b} 29 qdata.Register("T", data) 30 qdata.SetThis("T", reflect.ValueOf(data)) 31 32 reply, err := qdata.Call("T", "Add", &ReqNil{}) 33 assert.Nil(t, err) 34 assert.Equal(t, reply.(*Int64).Data, int64(30)) 35 36 *data.b = 30 37 reply, err = qdata.Call("T", "Add", &ReqNil{}) 38 assert.Nil(t, err) 39 assert.Equal(t, reply.(*Int64).Data, int64(40)) 40 41 data.a = 30 42 reply, err = qdata.Call("T", "Add", &ReqNil{}) 43 assert.Nil(t, err) 44 assert.Equal(t, reply.(*Int64).Data, int64(60)) 45 46 data2 := &T{10, &b} 47 qdata.SetThis("T", reflect.ValueOf(data2)) 48 reply, err = qdata.Call("T", "Add", &ReqNil{}) 49 assert.Nil(t, err) 50 assert.Equal(t, reply.(*Int64).Data, int64(40)) 51 } 52 53 func BenchmarkCallOrigin(b *testing.B) { 54 bb := 20 55 data := &T{10, &bb} 56 result := int64(0) 57 for i := 0; i < b.N; i++ { 58 reply, _ := data.Query_Add(nil) 59 result += reply.(*Int64).Data 60 } 61 assert.Equal(b, result, int64(b.N*30)) 62 } 63 64 func init() { 65 bb := 20 66 data := &T{10, &bb} 67 qdata.Register("TT", data) 68 qdata.SetThis("TT", reflect.ValueOf(data)) 69 } 70 71 func BenchmarkCallQueryData(b *testing.B) { 72 result := int64(0) 73 for i := 0; i < b.N; i++ { 74 reply, _ := qdata.Call("TT", "Add", &ReqNil{}) 75 result += reply.(*Int64).Data 76 } 77 assert.Equal(b, result, int64(b.N*30)) 78 } 79 80 func TestIsOK(t *testing.T) { 81 data := make([]reflect.Value, 2) 82 var err interface{} 83 data[0] = reflect.ValueOf(&ReqNil{}) 84 data[1] = reflect.ValueOf(err) 85 assert.Equal(t, reflect.Invalid, data[1].Kind()) 86 assert.Equal(t, true, IsNil(data[1])) 87 assert.Equal(t, true, IsOK(data, 2)) 88 }