Skip to content

Commit

Permalink
update ut
Browse files Browse the repository at this point in the history
Signed-off-by: l1b0k <[email protected]>
  • Loading branch information
l1b0k committed Jan 3, 2025
1 parent e8c2532 commit 7c0d06f
Show file tree
Hide file tree
Showing 9 changed files with 545 additions and 8 deletions.
62 changes: 62 additions & 0 deletions pkg/eni/crdv2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/wait"
pkgclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"

networkv1beta1 "github.com/AliyunContainerService/terway/pkg/apis/network.alibabacloud.com/v1beta1"
Expand Down Expand Up @@ -470,3 +471,64 @@ func Test_removeDeleted(t *testing.T) {
})
}
}

func TestSyncNodeRuntimeReturnsNilWhenNoDeletedPods(t *testing.T) {
r := &CRDV2{
deletedPods: make(map[string]*networkv1beta1.RuntimePodStatus),
}
err := r.syncNodeRuntime(context.Background())
assert.NoError(t, err)
}

func TestSyncNodeRuntimeReturnsErrorWhenGetRuntimeNodeFails(t *testing.T) {
client := fake.NewClientBuilder().WithScheme(types.Scheme).Build()
r := &CRDV2{
client: client,
deletedPods: map[string]*networkv1beta1.RuntimePodStatus{"pod-1": {PodID: "pod-1"}},
}
err := r.syncNodeRuntime(context.Background())
assert.Error(t, err)
}

func TestSyncNodeRuntimeUpdatesDeletedPods(t *testing.T) {
n := &networkv1beta1.NodeRuntime{
ObjectMeta: metav1.ObjectMeta{Name: "node1"},
Spec: networkv1beta1.NodeRuntimeSpec{},
Status: networkv1beta1.NodeRuntimeStatus{Pods: map[string]*networkv1beta1.RuntimePodStatus{}},
}
client := fake.NewClientBuilder().WithScheme(types.Scheme).
WithStatusSubresource(n).
WithObjects(n).Build()
r := &CRDV2{
client: client,
nodeName: "node1",
deletedPods: map[string]*networkv1beta1.RuntimePodStatus{"pod-1": {PodID: "pod-1"}},
}

err := r.syncNodeRuntime(context.Background())
assert.NoError(t, err)

nodeRuntime := &networkv1beta1.NodeRuntime{}
err = client.Get(context.Background(), pkgclient.ObjectKey{Name: "node1"}, nodeRuntime)
assert.NoError(t, err)
assert.Contains(t, nodeRuntime.Status.Pods, "pod-1")
assert.Contains(t, nodeRuntime.Status.Pods["pod-1"].Status, networkv1beta1.CNIStatusDeleted)
}

func TestSyncNodeRuntimeClearsDeletedPods(t *testing.T) {
n := &networkv1beta1.NodeRuntime{
ObjectMeta: metav1.ObjectMeta{Name: "node1"},
Spec: networkv1beta1.NodeRuntimeSpec{},
Status: networkv1beta1.NodeRuntimeStatus{Pods: map[string]*networkv1beta1.RuntimePodStatus{}},
}

client := fake.NewClientBuilder().WithScheme(types.Scheme).WithStatusSubresource(n).WithObjects(n).Build()
r := &CRDV2{
client: client,
nodeName: "node1",
deletedPods: map[string]*networkv1beta1.RuntimePodStatus{"pod-1": {PodID: "pod-1"}},
}
err := r.syncNodeRuntime(context.Background())
assert.NoError(t, err)
assert.Empty(t, r.deletedPods)
}
67 changes: 59 additions & 8 deletions pkg/eni/remote_test.go
Original file line number Diff line number Diff line change
@@ -1,46 +1,49 @@
package eni

import (
"context"
"net"
"testing"

"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client/fake"

"github.com/AliyunContainerService/terway/types"
"github.com/AliyunContainerService/terway/types/daemon"

podENITypes "github.com/AliyunContainerService/terway/pkg/apis/network.alibabacloud.com/v1beta1"
networkv1beta1 "github.com/AliyunContainerService/terway/pkg/apis/network.alibabacloud.com/v1beta1"
)

func TestToRPC(t *testing.T) {
t.Run("test with valid IPv4 and IPv6 allocations", func(t *testing.T) {
l := &RemoteIPResource{
podENI: podENITypes.PodENI{
Spec: podENITypes.PodENISpec{
Allocations: []podENITypes.Allocation{
podENI: networkv1beta1.PodENI{
Spec: networkv1beta1.PodENISpec{
Allocations: []networkv1beta1.Allocation{
{
IPv4: "192.168.1.1",
IPv4CIDR: "192.168.1.0/24",
IPv6: "fd00:db8::1",
IPv6CIDR: "fd00:db8::/64",
ENI: podENITypes.ENI{
ENI: networkv1beta1.ENI{
ID: "eni-11",
MAC: "00:00:00:00:00:00",
},
Interface: "eth0",
ExtraRoutes: []podENITypes.Route{},
ExtraRoutes: []networkv1beta1.Route{},
DefaultRoute: true,
},
},
},
Status: podENITypes.PodENIStatus{
Status: networkv1beta1.PodENIStatus{
Phase: "",
InstanceID: "i-123456",
TrunkENIID: "eni-12345678",
Msg: "",
PodLastSeen: metav1.Time{},
ENIInfos: map[string]podENITypes.ENIInfo{
ENIInfos: map[string]networkv1beta1.ENIInfo{
"eni-11": {},
},
},
Expand Down Expand Up @@ -68,3 +71,51 @@ func TestToRPC(t *testing.T) {
assert.Equal(t, true, result[0].DefaultRoute)
})
}

func TestAllocateReturnsErrorWhenResourceTypeMismatch(t *testing.T) {
r := &Remote{}
resp, traces := r.Allocate(context.Background(), &daemon.CNI{}, &LocalIPResource{})
assert.Nil(t, resp)
assert.Equal(t, ResourceTypeMismatch, traces[0].Condition)
}

func TestAllocateReturnsNetworkResourcesWhenPodENIReady(t *testing.T) {
scheme := runtime.NewScheme()
_ = networkv1beta1.AddToScheme(scheme)
// Build the fake client with scheme and objects
client := fake.NewClientBuilder().
WithScheme(scheme).
WithObjects(&networkv1beta1.PodENI{
ObjectMeta: metav1.ObjectMeta{
Name: "pod-1",
Namespace: "default",
},
Spec: networkv1beta1.PodENISpec{
Allocations: []networkv1beta1.Allocation{
{
IPv4: "192.168.1.1",
IPv4CIDR: "192.168.1.0/24",
ENI: networkv1beta1.ENI{
ID: "eni-1",
MAC: "00:00:00:00:00:00",
},
Interface: "eth0",
DefaultRoute: true,
},
},
},
Status: networkv1beta1.PodENIStatus{
Phase: networkv1beta1.ENIPhaseBind,
InstanceID: "i-123456",
},
}).
Build()

r := NewRemote(client, nil)
cni := &daemon.CNI{PodNamespace: "default", PodName: "pod-1"}
resp, _ := r.Allocate(context.Background(), cni, &RemoteIPRequest{})
result := <-resp
assert.NoError(t, result.Err)
assert.NotNil(t, result.NetworkConfigs)
assert.Equal(t, "192.168.1.1", result.NetworkConfigs[0].ToRPC()[0].BasicInfo.PodIP.IPv4)
}
23 changes: 23 additions & 0 deletions pkg/ip/ip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ package ip

import (
"net"
"net/netip"
"testing"

"github.com/stretchr/testify/assert"
)

func Test_ipIntersect(t *testing.T) {
Expand Down Expand Up @@ -53,3 +56,23 @@ func Test_ipIntersect(t *testing.T) {
})
}
}

func TestIPAddrs2str_MultipleValidIPs_ReturnsCorrectStrings(t *testing.T) {
ip1, _ := netip.ParseAddr("192.0.2.1")
ip2, _ := netip.ParseAddr("192.0.2.2")
input := []netip.Addr{ip1, ip2}
expected := []string{"192.0.2.1", "192.0.2.2"}
result := IPAddrs2str(input)
if len(result) != len(expected) {
t.Errorf("Expected %v, got %v", expected, result)
}
for i := range expected {
if result[i] != expected[i] {
t.Errorf("Expected %v, got %v", expected, result)
}
}
}

func TestDeriveGatewayIP(t *testing.T) {
assert.Equal(t, "192.168.0.253", DeriveGatewayIP("192.168.0.0/24"))
}
69 changes: 69 additions & 0 deletions types/controlplane/annotations_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package controlplane

import (
"testing"

"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func TestParsePodNetworksFromAnnotation(t *testing.T) {
tests := []struct {
name string
podAnnotations map[string]string
expectedResult *PodNetworksAnnotation
expectedError string
}{
{
name: "AnnotationDoesNotExist",
podAnnotations: map[string]string{},
expectedResult: &PodNetworksAnnotation{},
expectedError: "",
},
{
name: "AnnotationExistsAndValid",
podAnnotations: map[string]string{
"k8s.aliyun.com/pod-networks": `{ "podNetworks": [{"vSwitchOptions": [
"vsw-a","vsw-b","vsw-c"
], "interface": "eth0",
"securityGroupIDs": [
"sg-1"
]}]}`,
},
expectedResult: &PodNetworksAnnotation{
PodNetworks: []PodNetworks{
{
Interface: "eth0",
VSwitchOptions: []string{
"vsw-a", "vsw-b", "vsw-c",
},
SecurityGroupIDs: []string{
"sg-1",
},
},
},
},
expectedError: "",
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Annotations: test.podAnnotations,
},
}

result, err := ParsePodNetworksFromAnnotation(pod)
if test.expectedError != "" {
assert.Error(t, err)
assert.Contains(t, err.Error(), test.expectedError)
} else {
assert.NoError(t, err)
assert.Equal(t, test.expectedResult, result)
}
})
}
}
60 changes: 60 additions & 0 deletions types/daemon/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"testing"

"github.com/stretchr/testify/assert"

"github.com/AliyunContainerService/terway/types"
)

func Test_MergeConfigAndUnmarshal(t *testing.T) {
Expand Down Expand Up @@ -105,3 +107,61 @@ func TestGetAddonSecret(t *testing.T) {
assert.Equal(t, "key", ak)
assert.Equal(t, "secret", sk)
}

func TestGetVSwitchIDsReturnsAllVSwitchIDs(t *testing.T) {
cfg := &Config{
VSwitches: map[string][]string{
"zone-a": {"vsw-1", "vsw-2"},
"zone-b": {"vsw-3"},
},
}
vsws := cfg.GetVSwitchIDs()
assert.ElementsMatch(t, []string{"vsw-1", "vsw-2", "vsw-3"}, vsws)
}

func TestGetVSwitchIDsReturnsEmptyWhenNoVSwitches(t *testing.T) {
cfg := &Config{
VSwitches: map[string][]string{},
}
vsws := cfg.GetVSwitchIDs()
assert.Empty(t, vsws)
}

func TestGetExtraRoutesReturnsAllRoutes(t *testing.T) {
cfg := &Config{
VSwitches: map[string][]string{
"zone-a": {"vsw-1", "vsw-2"},
"zone-b": {"vsw-3"},
},
}
routes := cfg.GetExtraRoutes()
assert.ElementsMatch(t, []string{"vsw-1", "vsw-2", "vsw-3"}, routes)
}

func TestGetExtraRoutesReturnsEmptyWhenNoRoutes(t *testing.T) {
cfg := &Config{
VSwitches: map[string][]string{},
}
routes := cfg.GetExtraRoutes()
assert.Empty(t, routes)
}

func TestPopulateSetsDefaultValues(t *testing.T) {
cfg := &Config{}
cfg.Populate()
assert.Equal(t, 1.0, cfg.EniCapRatio)
assert.Equal(t, VSwitchSelectionPolicyRandom, cfg.VSwitchSelectionPolicy)
assert.Equal(t, string(types.IPStackIPv4), cfg.IPStack)
}

func TestPopulateDoesNotOverrideExistingValues(t *testing.T) {
cfg := &Config{
EniCapRatio: 0.5,
VSwitchSelectionPolicy: "custom",
IPStack: string(types.IPStackDual),
}
cfg.Populate()
assert.Equal(t, 0.5, cfg.EniCapRatio)
assert.Equal(t, "custom", cfg.VSwitchSelectionPolicy)
assert.Equal(t, string(types.IPStackDual), cfg.IPStack)
}
Loading

0 comments on commit 7c0d06f

Please sign in to comment.