github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/network/codec/roundTripHeader_test.go (about)

     1  package codec_test
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/assert"
     7  
     8  	"github.com/onflow/flow-go/model/messages"
     9  	"github.com/onflow/flow-go/network"
    10  	"github.com/onflow/flow-go/utils/unittest"
    11  )
    12  
    13  // roundTripHeaderViaCodec tests encoding and then decoding (AKA round-
    14  // trip) an example message to see if the decoded message matches the
    15  // original encoded message. Why? Both JSON and CBOR require helper
    16  // functions (i.e. MarshalJSON() & MarshalCBOR()) which properly export
    17  // time in the proper format and zone, otherwise running nodes will fail
    18  // due to signature validation failures due to using the incorrectly
    19  // serialized time. When CBOR was first added without the assicated
    20  // helper function then all the unit tests passed but the nodes failed
    21  // as described above. Therefore these functions were added to help the
    22  // next developer who wants to add a new serialization format :-)
    23  func roundTripHeaderViaCodec(t *testing.T, codec network.Codec) {
    24  	block := unittest.BlockFixture()
    25  	message := messages.NewBlockProposal(&block)
    26  	encoded, err := codec.Encode(message)
    27  	assert.NoError(t, err)
    28  	decodedInterface, err := codec.Decode(encoded)
    29  	assert.NoError(t, err)
    30  	decoded := decodedInterface.(*messages.BlockProposal)
    31  	decodedBlock := decoded.Block.ToInternal()
    32  	// compare LastViewTC separately, because it is a pointer field
    33  	if decodedBlock.Header.LastViewTC == nil {
    34  		assert.Equal(t, block.Header.LastViewTC, decodedBlock.Header.LastViewTC)
    35  	} else {
    36  		assert.Equal(t, *block.Header.LastViewTC, *decodedBlock.Header.LastViewTC)
    37  	}
    38  	// compare the rest of the header
    39  	// manually set LastViewTC fields to be equal to pass the Header pointer comparison
    40  	decodedBlock.Header.LastViewTC = block.Header.LastViewTC
    41  	assert.Equal(t, *block.Header, *decodedBlock.Header)
    42  }
    43  
    44  func TestRoundTripHeaderViaCBOR(t *testing.T) {
    45  	codec := unittest.NetworkCodec()
    46  	roundTripHeaderViaCodec(t, codec)
    47  }