diff --git a/network.go b/network.go index 108d78a..5442ca2 100644 --- a/network.go +++ b/network.go @@ -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 } diff --git a/network_test.go b/network_test.go index 9c153f0..0b222be 100644 --- a/network_test.go +++ b/network_test.go @@ -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) }