Skip to content

Commit

Permalink
fix: getHostByName
Browse files Browse the repository at this point in the history
- changed getHostByName
- added unit-test
  • Loading branch information
lib0xidium committed Oct 10, 2024
1 parent fc7fc0d commit 65d69fd
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 10 deletions.
16 changes: 11 additions & 5 deletions network.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
package sprig

import (
"math/rand"
"net"
)

func getHostByName(name string) string {
addrs, _ := net.LookupHost(name)
//TODO: add error handing when release v3 comes out
return addrs[rand.Intn(len(addrs))]
const NUM_TRIES = 3

func getHostByName(name string) ([]string, error) {
err := error(nil)
addrs := []string(nil)
for tries := 0; tries < NUM_TRIES; tries++ {
if addrs, err = net.LookupHost(name); err == nil {
return addrs, nil
}
}
return addrs, err
}
33 changes: 28 additions & 5 deletions network_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,40 @@ package sprig

import (
"net"
"strings"
"testing"

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

func TestGetHostByName(t *testing.T) {
tpl := `{{"www.google.com" | getHostByName}}`
// GIVEN a valid hostname
tpl := `{{"google.com" | getHostByName}}`

resolvedIP, _ := runRaw(tpl, nil)
// WHEN getHostByName is executed
resolvedIP, err := runRaw(tpl, nil)

ip := net.ParseIP(resolvedIP)
assert.NotNil(t, ip)
assert.NotEmpty(t, ip)
// THEN the resolved IP should not be empty and no error should be returned
assert.NotEmpty(t, resolvedIP)
assert.NoError(t, err)

// result has type string, but it should be a slice of strings
// convert it to a slice of strings
resolvedIPs := strings.Split(resolvedIP[1:len(resolvedIP)-1], " ")

// Check if the resolved IP is a valid IP address
parsedIP := net.ParseIP(resolvedIPs[0])
assert.NotNil(t, parsedIP)
}

func TestGetHostByNameNXDomain(t *testing.T) {
// GIVEN an invalid hostname
tpl := `{{"invalid.invalid" | getHostByName}}`

// WHEN getHostByName is executed
resolvedIP, err := runRaw(tpl, nil)

// THEN the resolved IP should be empty and an error should be returned
assert.Empty(t, resolvedIP)
assert.Error(t, err)
}

0 comments on commit 65d69fd

Please sign in to comment.