|
| 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