github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/utilities/common/bytes_test.go (about) 1 package common 2 3 import ( 4 "bytes" 5 "testing" 6 7 checker "gopkg.in/check.v1" 8 ) 9 10 type BytesSuite struct{} 11 12 var _ = checker.Suite(&BytesSuite{}) 13 14 func (s *BytesSuite) TestCopyBytes(c *checker.C) { 15 data1 := []byte{1, 2, 3, 4} 16 exp1 := []byte{1, 2, 3, 4} 17 res1 := CopyBytes(data1) 18 c.Assert(res1, checker.DeepEquals, exp1) 19 } 20 21 func (s *BytesSuite) TestLeftPadBytes(c *checker.C) { 22 val1 := []byte{1, 2, 3, 4} 23 exp1 := []byte{0, 0, 0, 0, 1, 2, 3, 4} 24 25 res1 := LeftPadBytes(val1, 8) 26 res2 := LeftPadBytes(val1, 2) 27 28 c.Assert(res1, checker.DeepEquals, exp1) 29 c.Assert(res2, checker.DeepEquals, val1) 30 } 31 32 func (s *BytesSuite) TestRightPadBytes(c *checker.C) { 33 val := []byte{1, 2, 3, 4} 34 exp := []byte{1, 2, 3, 4, 0, 0, 0, 0} 35 36 resstd := RightPadBytes(val, 8) 37 resshrt := RightPadBytes(val, 2) 38 39 c.Assert(resstd, checker.DeepEquals, exp) 40 c.Assert(resshrt, checker.DeepEquals, val) 41 } 42 43 func TestFromHex(t *testing.T) { 44 input := "0x01" 45 expected := []byte{1} 46 result := FromHex(input) 47 if !bytes.Equal(expected, result) { 48 t.Errorf("Expected %x got %x", expected, result) 49 } 50 } 51 52 func TestIsHex(t *testing.T) { 53 tests := []struct { 54 input string 55 ok bool 56 }{ 57 {"", true}, 58 {"0", false}, 59 {"00", true}, 60 {"a9e67e", true}, 61 {"A9E67E", true}, 62 {"0xa9e67e", false}, 63 {"a9e67e001", false}, 64 {"0xHELLO_MY_NAME_IS_STEVEN_@#$^&*", false}, 65 } 66 for _, test := range tests { 67 if ok := isHex(test.input); ok != test.ok { 68 t.Errorf("isHex(%q) = %v, want %v", test.input, ok, test.ok) 69 } 70 } 71 } 72 73 func TestFromHexOddLength(t *testing.T) { 74 input := "0x1" 75 expected := []byte{1} 76 result := FromHex(input) 77 if !bytes.Equal(expected, result) { 78 t.Errorf("Expected %x got %x", expected, result) 79 } 80 } 81 82 func TestNoPrefixShortHexOddLength(t *testing.T) { 83 input := "1" 84 expected := []byte{1} 85 result := FromHex(input) 86 if !bytes.Equal(expected, result) { 87 t.Errorf("Expected %x got %x", expected, result) 88 } 89 }