From 97ddc70c4df1a2e62093ee9a199af5624bc35a7a Mon Sep 17 00:00:00 2001 From: Ibrahim Jarif Date: Wed, 20 Feb 2019 02:28:26 +0530 Subject: [PATCH] ValidateAddress should return true if IPv6 is valid (#3027) - Add tests for ValidateAddress function Fixes https://github.com/dgraph-io/dgraph/issues/3023 Signed-off-by: Ibrahim Jarif --- x/x.go | 2 +- x/x_test.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/x/x.go b/x/x.go index a0f1d48d517..6101f875797 100644 --- a/x/x.go +++ b/x/x.go @@ -279,7 +279,7 @@ func ValidateAddress(addr string) bool { if p, err := strconv.Atoi(port); err != nil || p <= 0 || p >= 65536 { return false } - if err := net.ParseIP(host); err == nil { + if ip := net.ParseIP(host); ip != nil { return true } // try to parse as hostname as per hostname RFC diff --git a/x/x_test.go b/x/x_test.go index 53f358d1484..2e12b4e84d4 100644 --- a/x/x_test.go +++ b/x/x_test.go @@ -52,3 +52,45 @@ func TestDivideAndRule(t *testing.T) { test(1755, 4, 439) } + +func TestValidateAddress(t *testing.T) { + t.Run("IPv4", func(t *testing.T) { + testData := []struct { + name string + address string + isValid bool + }{ + {"Valid without port", "190.0.0.1", false}, + {"Valid with port", "192.5.32.1:333", true}, + {"Invalid without port", "12.0.0", false}, + // the following test returns true because 12.0.0 is considered as valid + // hostname + {"Invalid with port", "12.0.0:3333", true}, + } + for _, subtest := range testData { + st := subtest + t.Run(st.name, func(t *testing.T) { + require.Equal(t, st.isValid, ValidateAddress(st.address)) + }) + } + + }) + t.Run("IPv6", func(t *testing.T) { + testData := []struct { + name string + address string + isValid bool + }{ + {"Valid without port", "[2001:db8::1]", false}, + {"Valid with port", "[2001:db8::1]:8888", true}, + {"Invalid without port", "[2001:db8]", false}, + {"Invalid with port", "[2001:db8]:2222", false}, + } + for _, subtest := range testData { + st := subtest + t.Run(st.name, func(t *testing.T) { + require.Equal(t, st.isValid, ValidateAddress(st.address)) + }) + } + }) +}