github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/network/codec/cbor/codec_test.go (about) 1 package cbor_test 2 3 import ( 4 "testing" 5 6 "github.com/stretchr/testify/assert" 7 "github.com/stretchr/testify/require" 8 9 "github.com/onflow/flow-go/network/codec" 10 "github.com/onflow/flow-go/network/codec/cbor" 11 "github.com/onflow/flow-go/utils/unittest" 12 ) 13 14 func TestCodec_Decode(t *testing.T) { 15 c := cbor.NewCodec() 16 t.Run("decodes message successfully", func(t *testing.T) { 17 18 data := unittest.ProposalFixture() 19 encoded, err := c.Encode(data) 20 require.NoError(t, err) 21 22 decoded, err := c.Decode(encoded) 23 require.NoError(t, err) 24 require.Equal(t, data, decoded) 25 }) 26 27 t.Run("returns error when data is empty", func(t *testing.T) { 28 decoded, err := c.Decode(nil) 29 assert.Nil(t, decoded) 30 assert.True(t, codec.IsErrInvalidEncoding(err)) 31 32 decoded, err = c.Decode([]byte{}) 33 assert.Nil(t, decoded) 34 assert.True(t, codec.IsErrInvalidEncoding(err)) 35 }) 36 37 t.Run("returns error when message code is invalid", func(t *testing.T) { 38 decoded, err := c.Decode([]byte{codec.CodeMin.Uint8()}) 39 assert.Nil(t, decoded) 40 assert.True(t, codec.IsErrUnknownMsgCode(err)) 41 42 decoded, err = c.Decode([]byte{codec.CodeMax.Uint8()}) 43 assert.Nil(t, decoded) 44 assert.True(t, codec.IsErrUnknownMsgCode(err)) 45 46 decoded, err = c.Decode([]byte{codec.CodeMin.Uint8() - 1}) 47 assert.Nil(t, decoded) 48 assert.True(t, codec.IsErrUnknownMsgCode(err)) 49 50 decoded, err = c.Decode([]byte{codec.CodeMax.Uint8() + 1}) 51 assert.Nil(t, decoded) 52 assert.True(t, codec.IsErrUnknownMsgCode(err)) 53 }) 54 55 t.Run("returns error when unmarshalling fails - empty", func(t *testing.T) { 56 decoded, err := c.Decode([]byte{codec.CodeBlockProposal.Uint8()}) 57 assert.Nil(t, decoded) 58 assert.True(t, codec.IsErrMsgUnmarshal(err)) 59 }) 60 61 t.Run("returns error when unmarshalling fails - wrong type", func(t *testing.T) { 62 data := unittest.ProposalFixture() 63 encoded, err := c.Encode(data) 64 require.NoError(t, err) 65 66 encoded[0] = codec.CodeCollectionGuarantee.Uint8() 67 68 decoded, err := c.Decode(encoded) 69 assert.Nil(t, decoded) 70 assert.True(t, codec.IsErrMsgUnmarshal(err)) 71 }) 72 73 t.Run("returns error when unmarshalling fails - corrupt", func(t *testing.T) { 74 data := unittest.ProposalFixture() 75 encoded, err := c.Encode(data) 76 require.NoError(t, err) 77 78 encoded[2] = 0x20 // corrupt payload 79 80 decoded, err := c.Decode(encoded) 81 assert.Nil(t, decoded) 82 assert.True(t, codec.IsErrMsgUnmarshal(err)) 83 }) 84 }