Skip to content

Commit

Permalink
chore: utils tests (#661)
Browse files Browse the repository at this point in the history
* chore: add tests for utils

* chore:delete unused code

* fix: ipv6 validation issue
  • Loading branch information
chaitanyaprem authored Aug 22, 2023
1 parent 54c0221 commit bc06867
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 40 deletions.
2 changes: 2 additions & 0 deletions waku/v2/utils/hex.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"strings"
)

// DecodeHexString decodes input string into a hex string.
// Note that if the string is prefixed by 0x , it is trimmed
func DecodeHexString(input string) ([]byte, error) {
input = strings.TrimPrefix(input, "0x")
return hex.DecodeString(input)
Expand Down
27 changes: 27 additions & 0 deletions waku/v2/utils/hex_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package utils

import (
"testing"

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

func TestHexDecoding(t *testing.T) {
const s = "0x48656c6c6f20476f7068657221"
decodedString, err := DecodeHexString(s)
require.NoError(t, err)
require.Equal(t, decodedString, []byte("Hello Gopher!"))

const s1 = "48656c6c6f20476f7068657221"
_, err = DecodeHexString(s1)
require.NoError(t, err)
require.Equal(t, decodedString, []byte("Hello Gopher!"))

const s2 = "jk"
_, err = DecodeHexString(s2)
require.Error(t, err)

const s3 = "48656c6c6f20476f706865722"
_, err = DecodeHexString(s3)
require.Error(t, err)
}
6 changes: 4 additions & 2 deletions waku/v2/utils/ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import (
"strings"
)

// IsIPv4 validates if string is a valid IPV4 address
func IsIPv4(str string) bool {
ip := net.ParseIP(str)
return ip != nil && !strings.Contains(str, ":")
ip := net.ParseIP(str).To4()
return ip != nil
}

// IsIPv6 validates if string is a valid IPV6 address
func IsIPv6(str string) bool {
ip := net.ParseIP(str)
return ip != nil && strings.Contains(str, ":")
Expand Down
20 changes: 20 additions & 0 deletions waku/v2/utils/ip_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package utils

import (
"testing"

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

func TestIPValidation(t *testing.T) {
require.Equal(t, IsIPv4("127.0.0.1"), true)
require.Equal(t, IsIPv4("abcd"), false)
require.Equal(t, IsIPv4("::1"), false)
require.Equal(t, IsIPv4("1000.40.210.253"), false)

require.Equal(t, IsIPv6("::1"), true)
require.Equal(t, IsIPv6("fe80::6c4a:6aff:fecf:8097"), true)
require.Equal(t, IsIPv6("2001:0db8:85a3:0000:0000:8a2e:0370:7334:3445"), false)
require.Equal(t, IsIPv6("127.0.0.1"), false)

}
38 changes: 0 additions & 38 deletions waku/v2/utils/ntp.go

This file was deleted.

0 comments on commit bc06867

Please sign in to comment.