github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/provider/azure/internal/iputils/iputils_test.go (about) 1 // Copyright 2015 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package iputils_test 5 6 import ( 7 "fmt" 8 "net" 9 10 jc "github.com/juju/testing/checkers" 11 gc "gopkg.in/check.v1" 12 13 "github.com/juju/juju/provider/azure/internal/iputils" 14 "github.com/juju/juju/testing" 15 ) 16 17 type iputilsSuite struct { 18 testing.BaseSuite 19 } 20 21 var _ = gc.Suite(&iputilsSuite{}) 22 23 func (*iputilsSuite) TestNextSubnetIP(c *gc.C) { 24 assertNextSubnetIP(c, "10.0.0.0/8", nil, "10.0.0.4") 25 assertNextSubnetIP(c, "10.0.0.0/8", []string{"10.0.0.1"}, "10.0.0.4") 26 assertNextSubnetIP(c, "10.0.0.0/8", []string{"10.0.0.1", "10.0.0.4"}, "10.0.0.5") 27 } 28 29 func (*iputilsSuite) TestNextSubnetIPErrors(c *gc.C) { 30 // The subnet is too small to have any non-reserved addresses. 31 assertNextSubnetIPError( 32 c, 33 "10.1.2.0/30", 34 nil, 35 "no addresses available in 10.1.2.0/30", 36 ) 37 38 // All addresses in use. 39 var addresses []string 40 for i := 1; i < 255; i++ { 41 addr := fmt.Sprintf("10.0.0.%d", i) 42 addresses = append(addresses, addr) 43 } 44 assertNextSubnetIPError( 45 c, "10.0.0.0/24", addresses, 46 "no addresses available in 10.0.0.0/24", 47 ) 48 } 49 50 func assertNextSubnetIP(c *gc.C, ipnetString string, inuseStrings []string, expectedString string) { 51 ipnet := parseIPNet(c, ipnetString) 52 inuse := parseIPs(c, inuseStrings...) 53 next, err := iputils.NextSubnetIP(ipnet, inuse) 54 c.Assert(err, jc.ErrorIsNil) 55 c.Assert(next.String(), gc.Equals, expectedString) 56 } 57 58 func assertNextSubnetIPError(c *gc.C, ipnetString string, inuseStrings []string, expect string) { 59 ipnet := parseIPNet(c, ipnetString) 60 inuse := parseIPs(c, inuseStrings...) 61 _, err := iputils.NextSubnetIP(ipnet, inuse) 62 c.Assert(err, gc.ErrorMatches, expect) 63 } 64 65 func parseIPs(c *gc.C, ipStrings ...string) []net.IP { 66 ips := make([]net.IP, len(ipStrings)) 67 for i, ipString := range ipStrings { 68 ip := net.ParseIP(ipString) 69 c.Assert(ip, gc.NotNil, gc.Commentf("failed to parse IP %q", ipString)) 70 ips[i] = ip 71 } 72 return ips 73 } 74 75 func parseIPNet(c *gc.C, cidr string) *net.IPNet { 76 _, ipnet, err := net.ParseCIDR(cidr) 77 c.Assert(err, jc.ErrorIsNil) 78 return ipnet 79 }