Browse code

Add more helpful error message for -add-host Fixes: #10655

As noted in the issue, bad format was being returned even if the format
was appropriate, but the IP was invalid. This adds a better error
message for when the IP address fails validation.

Docker-DCO-1.1-Signed-off-by: Phil Estes <estesp@linux.vnet.ibm.com> (github: estesp)

Phil Estes authored on 2015/02/09 23:59:05
Showing 2 changed files
... ...
@@ -207,10 +207,10 @@ func ValidateExtraHost(val string) (string, error) {
207 207
 	// allow for IPv6 addresses in extra hosts by only splitting on first ":"
208 208
 	arr := strings.SplitN(val, ":", 2)
209 209
 	if len(arr) != 2 || len(arr[0]) == 0 {
210
-		return "", fmt.Errorf("bad format for add-host: %s", val)
210
+		return "", fmt.Errorf("bad format for add-host: %q", val)
211 211
 	}
212 212
 	if _, err := ValidateIPAddress(arr[1]); err != nil {
213
-		return "", fmt.Errorf("bad format for add-host: %s", val)
213
+		return "", fmt.Errorf("invalid IP address in add-host: %q", arr[1])
214 214
 	}
215 215
 	return val, nil
216 216
 }
... ...
@@ -1,6 +1,7 @@
1 1
 package opts
2 2
 
3 3
 import (
4
+	"strings"
4 5
 	"testing"
5 6
 )
6 7
 
... ...
@@ -113,11 +114,11 @@ func TestValidateExtraHosts(t *testing.T) {
113 113
 		`ipv6local:::1`,
114 114
 	}
115 115
 
116
-	invalid := []string{
117
-		`myhost:192.notanipaddress.1`,
118
-		`thathost-nosemicolon10.0.0.1`,
119
-		`anipv6host:::::1`,
120
-		`ipv6local:::0::`,
116
+	invalid := map[string]string{
117
+		`myhost:192.notanipaddress.1`:  `invalid IP`,
118
+		`thathost-nosemicolon10.0.0.1`: `bad format`,
119
+		`anipv6host:::::1`:             `invalid IP`,
120
+		`ipv6local:::0::`:              `invalid IP`,
121 121
 	}
122 122
 
123 123
 	for _, extrahost := range valid {
... ...
@@ -126,9 +127,13 @@ func TestValidateExtraHosts(t *testing.T) {
126 126
 		}
127 127
 	}
128 128
 
129
-	for _, extrahost := range invalid {
130
-		if _, err := ValidateExtraHost(extrahost); err == nil {
131
-			t.Fatalf("ValidateExtraHost(`" + extrahost + "`) should have failed validation")
129
+	for extraHost, expectedError := range invalid {
130
+		if _, err := ValidateExtraHost(extraHost); err == nil {
131
+			t.Fatalf("ValidateExtraHost(`%q`) should have failed validation", extraHost)
132
+		} else {
133
+			if !strings.Contains(err.Error(), expectedError) {
134
+				t.Fatalf("ValidateExtraHost(`%q`) error should contain %q", extraHost, expectedError)
135
+			}
132 136
 		}
133 137
 	}
134 138
 }