github.com/klaytn/klaytn@v1.12.1/node/cn/protocol_test.go (about)

     1  // Copyright 2019 The klaytn Authors
     2  // This file is part of the klaytn library.
     3  //
     4  // The klaytn library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The klaytn library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the klaytn library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package cn
    18  
    19  import (
    20  	"bytes"
    21  	"testing"
    22  
    23  	"github.com/klaytn/klaytn/common"
    24  	"github.com/klaytn/klaytn/rlp"
    25  	"github.com/stretchr/testify/assert"
    26  )
    27  
    28  func TestHashOrNumber_Success(t *testing.T) {
    29  	// Hash is used for hashOrNumber.
    30  	{
    31  		data := &hashOrNumber{Hash: common.HexToHash("111")}
    32  		b := new(bytes.Buffer)
    33  		assert.NoError(t, rlp.Encode(b, data))
    34  
    35  		decodedHashData := &hashOrNumber{}
    36  		assert.NoError(t, rlp.DecodeBytes(b.Bytes(), decodedHashData))
    37  		assert.EqualValues(t, data, decodedHashData)
    38  	}
    39  	// Number is used for hashOrNumber.
    40  	{
    41  		data := &hashOrNumber{Number: uint64(111)}
    42  		b := new(bytes.Buffer)
    43  		assert.NoError(t, rlp.Encode(b, data))
    44  
    45  		decodedHashData := &hashOrNumber{}
    46  		assert.NoError(t, rlp.DecodeBytes(b.Bytes(), decodedHashData))
    47  		assert.EqualValues(t, data, decodedHashData)
    48  	}
    49  }
    50  
    51  func TestHashOrNumber_Fail(t *testing.T) {
    52  	// If both hash and number is provided, it should throw an error.
    53  	{
    54  		data := &hashOrNumber{Hash: common.HexToHash("111"), Number: uint64(111)}
    55  		b := new(bytes.Buffer)
    56  		assert.Error(t, rlp.Encode(b, data))
    57  	}
    58  	// If trying to decode invalid type into hashOrNumber, it should throw an error.
    59  	{
    60  		data := &basePeer{id: "TestBasePeer"}
    61  		b := new(bytes.Buffer)
    62  		assert.NoError(t, rlp.Encode(b, data))
    63  
    64  		decodedHashData := &hashOrNumber{}
    65  		assert.Error(t, rlp.DecodeBytes(b.Bytes(), decodedHashData))
    66  	}
    67  }