github.com/Finschia/finschia-sdk@v0.48.1/codec/types/any_internal_test.go (about) 1 package types 2 3 import ( 4 "testing" 5 6 "github.com/gogo/protobuf/proto" 7 "github.com/stretchr/testify/require" 8 ) 9 10 type Dog struct { 11 Name string `protobuf:"bytes,1,opt,name=size,proto3" json:"size,omitempty"` 12 } 13 14 func (d Dog) Greet() string { return d.Name } 15 16 // We implement a minimal proto.Message interface 17 func (d *Dog) Reset() { d.Name = "" } 18 func (d *Dog) String() string { return d.Name } 19 func (d *Dog) ProtoMessage() {} 20 func (d *Dog) XXX_MessageName() string { return "tests/dog" } 21 22 type Animal interface { 23 Greet() string 24 } 25 26 var ( 27 _ Animal = (*Dog)(nil) 28 _ proto.Message = (*Dog)(nil) 29 ) 30 31 func TestAnyPackUnpack(t *testing.T) { 32 registry := NewInterfaceRegistry() 33 registry.RegisterInterface("Animal", (*Animal)(nil)) 34 registry.RegisterImplementations( 35 (*Animal)(nil), 36 &Dog{}, 37 ) 38 39 spot := &Dog{Name: "Spot"} 40 var animal Animal 41 42 // with cache 43 any, err := NewAnyWithValue(spot) 44 require.NoError(t, err) 45 require.Equal(t, spot, any.GetCachedValue()) 46 err = registry.UnpackAny(any, &animal) 47 require.NoError(t, err) 48 require.Equal(t, spot, animal) 49 50 // without cache 51 any.cachedValue = nil 52 err = registry.UnpackAny(any, &animal) 53 require.NoError(t, err) 54 require.Equal(t, spot, animal) 55 } 56 57 func TestString(t *testing.T) { 58 require := require.New(t) 59 spot := &Dog{Name: "Spot"} 60 any, err := NewAnyWithValue(spot) 61 require.NoError(err) 62 63 require.Equal("&Any{TypeUrl:/tests/dog,Value:[10 4 83 112 111 116],XXX_unrecognized:[]}", any.String()) 64 require.Equal(`&Any{TypeUrl: "/tests/dog", 65 Value: []byte{0xa, 0x4, 0x53, 0x70, 0x6f, 0x74} 66 }`, any.GoString()) 67 }