Skip to content

Commit

Permalink
Add a test around failure case.
Browse files Browse the repository at this point in the history
  • Loading branch information
externalreality committed May 29, 2018
1 parent 7f60d19 commit 098075a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
5 changes: 4 additions & 1 deletion network/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,9 @@ func SubnetInAnyRange(cidrs []*net.IPNet, subnet *net.IPNet) bool {
return false
}

// Export for testing
var ResolverFunc = net.ResolveIPAddr

// FormatAsCIDR converts the specified IP addresses to
// a slice of CIDRs.
func FormatAsCIDR(addresses []string) ([]string, error) {
Expand All @@ -616,7 +619,7 @@ func FormatAsCIDR(addresses []string) ([]string, error) {
cidr := a
// If address is not already a cidr, add a /32 (ipv4) or /128 (ipv6).
if _, _, err := net.ParseCIDR(a); err != nil {
address, err := net.ResolveIPAddr("ip", a)
address, err := ResolverFunc("ip", a)
if err != nil {
return nil, errors.Trace(err)
}
Expand Down
36 changes: 35 additions & 1 deletion network/network_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,9 @@ func (s *NetworkSuite) TestQuoteSpaceSet(c *gc.C) {
checkQuoteSpaceSet(c, `"", "b"`, "b", "")
}

type CIDRSuite struct{}
type CIDRSuite struct {
testing.BaseSuite
}

var _ = gc.Suite(&CIDRSuite{})

Expand Down Expand Up @@ -381,3 +383,35 @@ func (s *CIDRSuite) TestSubnetInAnyRange(c *gc.C) {
c.Assert(result, gc.Equals, t.included)
}
}

// This test shows that FormatAsCIDR will resolve a resolvable hostname to an IP
// address before formatting as a CIDR.
func (s *CIDRSuite) TestParseCIDR(c *gc.C) {
exampleAddress := "10.10.10.10"
exampleHostname := "Hostname"
expectedCIDR := "10.10.10.10/32"
testAddresses := []struct {
address string
cidr string
}{{
address: exampleAddress,
cidr: expectedCIDR,
}, {
address: exampleHostname,
cidr: expectedCIDR,
}}

s.PatchValue(&network.ResolverFunc, func(string, hostname string) (*net.IPAddr, error) {
return &net.IPAddr{IP: net.ParseIP(exampleAddress)}, nil
})

for _, testAddress := range testAddresses {
actualCIDRs, err := network.FormatAsCIDR([]string{testAddress.address})
c.Assert(err, jc.ErrorIsNil)
if len(actualCIDRs) <= 0 {
c.Fail()
}
actualCIDR := actualCIDRs[0]
c.Assert(actualCIDR, gc.Equals, expectedCIDR)
}
}

0 comments on commit 098075a

Please sign in to comment.