Skip to content

Commit 30bf08c

Browse files
committed
Add _test for the net.IP flag type
1 parent c2a4060 commit 30bf08c

File tree

2 files changed

+67
-1
lines changed

2 files changed

+67
-1
lines changed

ip.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@ package pflag
33
import (
44
"fmt"
55
"net"
6+
"strings"
67
)
78

9+
var _ = strings.TrimSpace
10+
811
// -- net.IP value
912
type ipValue net.IP
1013

@@ -15,7 +18,7 @@ func newIPValue(val net.IP, p *net.IP) *ipValue {
1518

1619
func (i *ipValue) String() string { return net.IP(*i).String() }
1720
func (i *ipValue) Set(s string) error {
18-
ip := net.ParseIP(s)
21+
ip := net.ParseIP(strings.TrimSpace(s))
1922
if ip == nil {
2023
return fmt.Errorf("failed to parse IP: %q", s)
2124
}

ip_test.go

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package pflag
2+
3+
import (
4+
"fmt"
5+
"net"
6+
"os"
7+
"testing"
8+
)
9+
10+
func setUpIP(ip *net.IP) *FlagSet {
11+
f := NewFlagSet("test", ContinueOnError)
12+
f.IPVar(ip, "address", net.ParseIP("0.0.0.0"), "IP Address")
13+
return f
14+
}
15+
16+
func TestIP(t *testing.T) {
17+
testCases := []struct {
18+
input string
19+
success bool
20+
expected string
21+
}{
22+
{"0.0.0.0", true, "0.0.0.0"},
23+
{" 0.0.0.0 ", true, "0.0.0.0"},
24+
{"1.2.3.4", true, "1.2.3.4"},
25+
{"127.0.0.1", true, "127.0.0.1"},
26+
{"255.255.255.255", true, "255.255.255.255"},
27+
{"", false, ""},
28+
{"0", false, ""},
29+
{"localhost", false, ""},
30+
{"0.0.0", false, ""},
31+
{"0.0.0.", false, ""},
32+
{"0.0.0.0.", false, ""},
33+
{"0.0.0.256", false, ""},
34+
{"0 . 0 . 0 . 0", false, ""},
35+
}
36+
37+
devnull, _ := os.Open(os.DevNull)
38+
os.Stderr = devnull
39+
for i := range testCases {
40+
var addr net.IP
41+
f := setUpIP(&addr)
42+
43+
tc := &testCases[i]
44+
45+
arg := fmt.Sprintf("--address=%s", tc.input)
46+
err := f.Parse([]string{arg})
47+
if err != nil && tc.success == true {
48+
t.Errorf("expected success, got %q", err)
49+
continue
50+
} else if err == nil && tc.success == false {
51+
t.Errorf("expected failure")
52+
continue
53+
} else if tc.success {
54+
ip, err := f.GetIP("address")
55+
if err != nil {
56+
t.Errorf("Got error trying to fetch the IP flag: %v", err)
57+
}
58+
if ip.String() != tc.expected {
59+
t.Errorf("expected %q, got %q", tc.expected, ip.String())
60+
}
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)