github.com/cosmos/cosmos-sdk@v0.50.10/codec/collections_test.go (about) 1 package codec_test 2 3 import ( 4 "testing" 5 6 gogotypes "github.com/cosmos/gogoproto/types" 7 "github.com/google/go-cmp/cmp" 8 "github.com/stretchr/testify/require" 9 "google.golang.org/protobuf/testing/protocmp" 10 "google.golang.org/protobuf/types/known/wrapperspb" 11 12 "cosmossdk.io/collections/colltest" 13 14 "github.com/cosmos/cosmos-sdk/codec" 15 codectypes "github.com/cosmos/cosmos-sdk/codec/types" 16 "github.com/cosmos/cosmos-sdk/testutil/testdata" 17 ) 18 19 func TestCollectionsCorrectness(t *testing.T) { 20 t.Run("CollValue", func(t *testing.T) { 21 cdc := codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) 22 colltest.TestValueCodec(t, codec.CollValue[gogotypes.UInt64Value](cdc), gogotypes.UInt64Value{ 23 Value: 500, 24 }) 25 }) 26 27 t.Run("CollValueV2", func(t *testing.T) { 28 // NOTE: we cannot use colltest.TestValueCodec because protov2 has different 29 // compare semantics than protov1. We need to use protocmp.Transform() alongside 30 // cmp to ensure equality. 31 encoder := codec.CollValueV2[wrapperspb.UInt64Value]() 32 value := &wrapperspb.UInt64Value{Value: 500} 33 encodedValue, err := encoder.Encode(value) 34 require.NoError(t, err) 35 decodedValue, err := encoder.Decode(encodedValue) 36 require.NoError(t, err) 37 require.True(t, cmp.Equal(value, decodedValue, protocmp.Transform()), "encoding and decoding produces different values") 38 39 encodedJSONValue, err := encoder.EncodeJSON(value) 40 require.NoError(t, err) 41 decodedJSONValue, err := encoder.DecodeJSON(encodedJSONValue) 42 require.NoError(t, err) 43 require.True(t, cmp.Equal(value, decodedJSONValue, protocmp.Transform()), "encoding and decoding produces different values") 44 require.NotEmpty(t, encoder.ValueType()) 45 46 _ = encoder.Stringify(value) 47 }) 48 49 t.Run("BoolValue", func(t *testing.T) { 50 colltest.TestValueCodec(t, codec.BoolValue, true) 51 colltest.TestValueCodec(t, codec.BoolValue, false) 52 53 // asserts produced bytes are equal 54 valueAssert := func(b bool) { 55 wantBytes, err := (&gogotypes.BoolValue{Value: b}).Marshal() 56 require.NoError(t, err) 57 gotBytes, err := codec.BoolValue.Encode(b) 58 require.NoError(t, err) 59 require.Equal(t, wantBytes, gotBytes) 60 } 61 62 valueAssert(true) 63 valueAssert(false) 64 }) 65 66 t.Run("CollInterfaceValue", func(t *testing.T) { 67 cdc := codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) 68 cdc.InterfaceRegistry().RegisterInterface("animal", (*testdata.Animal)(nil), &testdata.Dog{}, &testdata.Cat{}) 69 valueCodec := codec.CollInterfaceValue[testdata.Animal](cdc) 70 71 colltest.TestValueCodec[testdata.Animal](t, valueCodec, &testdata.Dog{Name: "Doggo"}) 72 colltest.TestValueCodec[testdata.Animal](t, valueCodec, &testdata.Cat{Moniker: "Kitty"}) 73 74 // assert if used with a non interface type it yields a panic. 75 require.Panics(t, func() { 76 codec.CollInterfaceValue[*testdata.Dog](cdc) 77 }) 78 }) 79 }