ParseNetworks belongs in report

This commit is contained in:
Peter Bourgon
2015-09-09 12:59:20 +02:00
parent bd2a75687f
commit 30cb5299cf
2 changed files with 42 additions and 0 deletions

View File

@@ -2,11 +2,30 @@ package report
import (
"net"
"strings"
)
// Networks represent a set of subnets
type Networks []*net.IPNet
// ParseNetworks converts a string of space-separated CIDRs to a Networks.
func ParseNetworks(v string) Networks {
set := map[string]struct{}{}
for _, s := range strings.Fields(v) {
_, ipNet, err := net.ParseCIDR(s)
if err != nil {
continue
}
set[ipNet.String()] = struct{}{}
}
nets := Networks{}
for s := range set {
_, ipNet, _ := net.ParseCIDR(s)
nets = append(nets, ipNet)
}
return nets
}
// Interface is exported for testing.
type Interface interface {
Addrs() ([]net.Addr, error)

View File

@@ -1,6 +1,7 @@
package report_test
import (
"fmt"
"net"
"reflect"
"testing"
@@ -24,6 +25,28 @@ func TestContains(t *testing.T) {
}
}
func TestParseNetworks(t *testing.T) {
var (
bignetStr = "10.1.0.1/16"
smallnetStr = "5.6.7.8/32"
bignet = mustParseCIDR(bignetStr)
smallnet = mustParseCIDR(smallnetStr)
)
for _, tc := range []struct {
input string
want report.Networks
}{
{"", report.Networks{}},
{fmt.Sprintf("%s", bignetStr), report.Networks([]*net.IPNet{bignet})},
{fmt.Sprintf("%s %s", bignetStr, bignetStr), report.Networks([]*net.IPNet{bignet})},
{fmt.Sprintf("%s foo %s oops %s", smallnetStr, smallnetStr, smallnetStr), report.Networks([]*net.IPNet{smallnet})},
} {
if want, have := tc.want, report.ParseNetworks(tc.input); !reflect.DeepEqual(want, have) {
t.Error(test.Diff(want, have))
}
}
}
func mustParseCIDR(s string) *net.IPNet {
_, ipNet, err := net.ParseCIDR(s)
if err != nil {