github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/p2p/serializer_test.go (about)

     1  // Copyright 2021 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package p2p
    15  
    16  import (
    17  	"reflect"
    18  	"testing"
    19  
    20  	"github.com/stretchr/testify/require"
    21  	"github.com/vmihailenco/msgpack/v5"
    22  )
    23  
    24  type jsonSerializableMessage struct {
    25  	A int
    26  	B float64
    27  	C string
    28  }
    29  
    30  type msgpackSerializableMessage struct {
    31  	A int
    32  	B float64
    33  	C string
    34  	D []int
    35  }
    36  
    37  func (m *msgpackSerializableMessage) Marshal() ([]byte, error) {
    38  	return msgpack.Marshal(m)
    39  }
    40  
    41  func (m *msgpackSerializableMessage) Unmarshal(data []byte) error {
    42  	return msgpack.Unmarshal(data, m)
    43  }
    44  
    45  func TestJsonSerializable(t *testing.T) {
    46  	msg := &jsonSerializableMessage{
    47  		A: 1,
    48  		B: 2,
    49  		C: "test",
    50  	}
    51  
    52  	data, err := marshalMessage(msg)
    53  	require.NoError(t, err)
    54  
    55  	msg1 := &jsonSerializableMessage{}
    56  	err = unmarshalMessage(data, msg1)
    57  	require.NoError(t, err)
    58  
    59  	require.True(t, reflect.DeepEqual(msg, msg1))
    60  }
    61  
    62  func TestMsgpackSerializable(t *testing.T) {
    63  	msg := &msgpackSerializableMessage{
    64  		A: 1,
    65  		B: 2,
    66  		C: "test",
    67  		D: []int{1, 2, 3, 4, 5, 6},
    68  	}
    69  	data, err := marshalMessage(msg)
    70  	require.NoError(t, err)
    71  
    72  	data1, err := msgpack.Marshal(msg)
    73  	require.NoError(t, err)
    74  	require.Equal(t, data1, data)
    75  
    76  	msg1 := &msgpackSerializableMessage{}
    77  	err = unmarshalMessage(data, msg1)
    78  	require.NoError(t, err)
    79  	require.True(t, reflect.DeepEqual(msg, msg1))
    80  }