Skip to content

Commit

Permalink
Add ParseAddressString tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mateoflorido committed Jun 4, 2024
1 parent e07f1ed commit b71c4dd
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/k8s/pkg/utils/cidr.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ func ParseAddressString(address string, port int64) (string, error) {
}
}

if port < 0 || port > 65535 {
return "", fmt.Errorf("invalid port number %d", port)
}

if address == "" {
address = util.NetworkInterfaceAddress()
} else if _, ipNet, err := net.ParseCIDR(address); err == nil {
Expand Down
44 changes: 44 additions & 0 deletions src/k8s/pkg/utils/cidr_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package utils_test

import (
"fmt"
"net"
"testing"

"github.com/canonical/k8s/pkg/utils"
"github.com/canonical/lxd/lxd/util"
. "github.com/onsi/gomega"
)

Expand Down Expand Up @@ -68,3 +71,44 @@ func TestGetKubernetesServiceIPsFromServiceCIDRs(t *testing.T) {
}
})
}

func TestParseAddressString(t *testing.T) {
g := NewWithT(t)

// Seed the default address
defaultAddress := util.NetworkInterfaceAddress()
ip := net.ParseIP(defaultAddress)
subnetMask := net.CIDRMask(24, 32)
networkAddress := ip.Mask(subnetMask)
// Infer the CIDR notation
networkAddressCIDR := fmt.Sprintf("%s/24", networkAddress.String())

for _, tc := range []struct {
name string
address string
port int64
want string
wantErr bool
}{
{name: "EmptyAddress", address: "", port: 8080, want: fmt.Sprintf("%s:8080", defaultAddress), wantErr: false},
{name: "CIDR", address: networkAddressCIDR, port: 8080, want: fmt.Sprintf("%s:8080", defaultAddress), wantErr: false},
{name: "CIDRAndPort", address: fmt.Sprintf("%s:9090", networkAddressCIDR), port: 8080, want: fmt.Sprintf("%s:9090", defaultAddress), wantErr: false},
{name: "IPv4", address: "10.0.0.10", port: 8080, want: "10.0.0.10:8080", wantErr: false},
{name: "IPv4AndPort", address: "10.0.0.10:9090", port: 8080, want: "10.0.0.10:9090", wantErr: false},
{name: "NonMatchingCIDR", address: "10.10.5.0/24", port: 8080, want: "", wantErr: true},
{name: "IPv6", address: "fe80::1:234", port: 8080, want: "[fe80::1:234]:8080", wantErr: false},
{name: "IPv6AndPort", address: "[fe80::1:234]:9090", port: 8080, want: "[fe80::1:234]:9090", wantErr: false},
{name: "InvalidPort", address: "127.0.0.1:invalid-port", port: 0, want: "", wantErr: true},
{name: "PortOutOfBounds", address: "10.0.0.10:70799", port: 8080, want: "", wantErr: true},
} {
t.Run(tc.name, func(t *testing.T) {
got, err := utils.ParseAddressString(tc.address, tc.port)
if tc.wantErr {
g.Expect(err).To(HaveOccurred())
} else {
g.Expect(err).ToNot(HaveOccurred())
g.Expect(got).To(Equal(tc.want))
}
})
}
}

0 comments on commit b71c4dd

Please sign in to comment.