Skip to content

Commit

Permalink
Added unit tests for IsHexValid function
Browse files Browse the repository at this point in the history
  • Loading branch information
begmaroman committed Jan 29, 2024
1 parent 97f99b8 commit 1e69fef
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
6 changes: 3 additions & 3 deletions types/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ type ArgHash common.Hash

// UnmarshalText unmarshals from text
func (arg *ArgHash) UnmarshalText(input []byte) error {
if !HexIsValid(string(input)) {
if !IsHexValid(string(input)) {
return fmt.Errorf("invalid hash, it needs to be a hexadecimal value")
}

Expand Down Expand Up @@ -123,8 +123,8 @@ func decodeToHex(b []byte) ([]byte, error) {
return hex.DecodeString(str)
}

// HexIsValid checks if the provided string is a valid hexadecimal value
func HexIsValid(s string) bool {
// IsHexValid checks if the provided string is a valid hexadecimal value
func IsHexValid(s string) bool {
str := strings.TrimPrefix(s, "0x")
for _, b := range []byte(str) {
if !(b >= '0' && b <= '9' || b >= 'a' && b <= 'f' || b >= 'A' && b <= 'F') {
Expand Down
41 changes: 41 additions & 0 deletions types/types_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package types

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestIsHexValid(t *testing.T) {
tests := []struct {
name string
s string
want bool
}{
{
name: "valid hex without 0x prefix",
s: "76616c69642068657820776974686f757420307820707265666978",
want: true,
},
{
name: "valid hex with 0x prefix",
s: "0x76616c696420686578207769746820307820707265666978",
want: true,
},
{
name: "invalid hex without 0x prefix",
s: "76616c696invalid07769746820307820707265666978",
want: false,
},
{
name: "invalid hex with 0x prefix",
s: "0x76616c696invalid07769746820307820707265666978",
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
require.Equal(t, tt.want, IsHexValid(tt.s))
})
}
}

0 comments on commit 1e69fef

Please sign in to comment.