github.com/jlmeeker/kismatic@v1.10.1-0.20180612190640-57f9005a1f1a/pkg/util/ip_test.go (about)

     1  package util
     2  
     3  import (
     4  	"net"
     5  	"testing"
     6  )
     7  
     8  func TestGetIPFromCIDR(t *testing.T) {
     9  	tests := []struct {
    10  		cidr       string
    11  		n          int
    12  		expectedIP net.IP
    13  		expectErr  bool
    14  	}{
    15  		{
    16  			cidr:       "10.5.6.217/32",
    17  			n:          0,
    18  			expectedIP: net.ParseIP("10.5.6.217"),
    19  		},
    20  		{
    21  			cidr:      "10.5.6.217/32",
    22  			n:         1,
    23  			expectErr: true,
    24  		},
    25  		{
    26  			// max addresses = 256
    27  			cidr:       "10.20.0.0/24",
    28  			n:          100,
    29  			expectedIP: net.IP{byte(10), byte(20), byte(0), byte(100)},
    30  		},
    31  		{
    32  			// max addresses = 256
    33  			cidr:      "10.20.0.0/24",
    34  			n:         300,
    35  			expectErr: true,
    36  		},
    37  		{
    38  			// max addresses = 16
    39  			cidr:      "10.20.0.0/28",
    40  			n:         16,
    41  			expectErr: true,
    42  		},
    43  		{
    44  			// max addresses = 16
    45  			cidr:       "10.20.0.0/28",
    46  			n:          15,
    47  			expectedIP: net.ParseIP("10.20.0.15"),
    48  		},
    49  		{
    50  			// max addresses = 16
    51  			cidr:      "10.20.0.0/28",
    52  			n:         -1,
    53  			expectErr: true,
    54  		},
    55  		{
    56  			cidr:       "172.16.0.0/16",
    57  			n:          1,
    58  			expectedIP: net.ParseIP("172.16.0.1"),
    59  		},
    60  		{
    61  			cidr:       "172.16.0.0/16",
    62  			n:          2,
    63  			expectedIP: net.ParseIP("172.16.0.2"),
    64  		},
    65  	}
    66  
    67  	for i, test := range tests {
    68  		ip, err := GetIPFromCIDR(test.cidr, test.n)
    69  		if err != nil {
    70  			if !test.expectErr {
    71  				t.Errorf("test %d - got an unexpected error: %v", i, err)
    72  			}
    73  			continue
    74  		}
    75  
    76  		if !ip.Equal(test.expectedIP) {
    77  			t.Errorf("expected %q, but got %q", test.expectedIP, ip)
    78  		}
    79  
    80  		if test.expectErr {
    81  			t.Errorf("expected an error, but didn't get one")
    82  		}
    83  	}
    84  }