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