github.com/iotexproject/iotex-core@v1.14.1-rc1/pkg/util/byteutil/byteutil_test.go (about)

     1  // Copyright (c) 2022 IoTeX Foundation
     2  // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
     3  // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
     4  // This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
     5  
     6  package byteutil
     7  
     8  import (
     9  	"testing"
    10  
    11  	"github.com/pkg/errors"
    12  
    13  	"github.com/stretchr/testify/require"
    14  )
    15  
    16  func TestUint32(t *testing.T) {
    17  	input := uint32(31415926)
    18  	t.Run("convert uint32 to bytes", func(t *testing.T) {
    19  		expectedValue := []uint8([]byte{0x76, 0x5e, 0xdf, 0x1})
    20  		result := Uint32ToBytes(input)
    21  		require.Equal(t, expectedValue, result)
    22  	})
    23  
    24  	t.Run("converts a uint32 to 4 bytes in big-endian", func(t *testing.T) {
    25  		expectedValue := []uint8([]byte{0x1, 0xdf, 0x5e, 0x76})
    26  		result := Uint32ToBytesBigEndian(input)
    27  		require.Equal(t, expectedValue, result)
    28  	})
    29  }
    30  
    31  func TestUint64(t *testing.T) {
    32  	input := uint64(1844674407370955161)
    33  	byteInput := []byte{0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x19}
    34  	t.Run("convert uint64 to bytes", func(t *testing.T) {
    35  		result := Uint64ToBytes(input)
    36  		require.Equal(t, byteInput, result)
    37  	})
    38  
    39  	t.Run("convert bytes to unit64", func(t *testing.T) {
    40  		result := BytesToUint64(byteInput)
    41  		require.Equal(t, input, result)
    42  	})
    43  
    44  	t.Run("converts a uint64 to 8 bytes in big-endian", func(t *testing.T) {
    45  		expectedValue := []uint8([]byte{0x19, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99})
    46  		result := Uint64ToBytesBigEndian(input)
    47  		require.Equal(t, expectedValue, result)
    48  	})
    49  
    50  	t.Run("converts 8 bytes to uint64 in big-endian", func(t *testing.T) {
    51  		expectedValue := uint64(11068046444225730841)
    52  		result := BytesToUint64BigEndian(byteInput)
    53  		require.Equal(t, expectedValue, result)
    54  	})
    55  }
    56  
    57  func TestMust(t *testing.T) {
    58  	t.Run("return identical output when given nil error", func(t *testing.T) {
    59  		b := []byte{0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x19}
    60  		result := Must(b, nil)
    61  		require.Equal(t, b, result)
    62  	})
    63  	t.Run("panics when an error was given", func(t *testing.T) {
    64  		expectedErr := errors.New("an error was given")
    65  		require.Panics(t, func() {
    66  			Must([]byte{0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x19}, expectedErr)
    67  		}, expectedErr)
    68  	})
    69  }