Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unit-test for SubnetSet controller #10

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions pkg/controllers/subnetset/namespace_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func (e *EnqueueRequestForNamespace) Update(_ context.Context, updateEvent event
obj := updateEvent.ObjectNew.(*v1.Namespace)
err := requeueSubnetSet(e.Client, obj.Name, l)
if err != nil {
log.Error(err, "failed to reconcile subnet")
log.Error(err, "Failed to requeue subnet")
}
}

Expand All @@ -52,9 +52,9 @@ var PredicateFuncsNs = predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
oldObj := e.ObjectOld.(*v1.Namespace)
newObj := e.ObjectNew.(*v1.Namespace)
log.V(1).Info("Receive Namespace update event", "name", oldObj.Name)
log.V(1).Info("Receive Namespace update event", "Name", oldObj.Name)
if reflect.DeepEqual(oldObj.ObjectMeta.Labels, newObj.ObjectMeta.Labels) {
log.Info("label of Namespace is not changed, ignore it", "name", oldObj.Name)
log.Info("Label of Namespace is not changed, ignore it", "name", oldObj.Name)
return false
}
return true
Expand All @@ -64,14 +64,21 @@ var PredicateFuncsNs = predicate.Funcs{
},
}

func requeueSubnetSet(c client.Client, namespace string, q workqueue.RateLimitingInterface) error {
func listSubnetSet(c client.Client, ctx context.Context, options ...client.ListOption) (*v1alpha1.SubnetSetList, error) {
subnetSetList := &v1alpha1.SubnetSetList{}
err := c.List(context.Background(), subnetSetList, client.InNamespace(namespace))
err := c.List(ctx, subnetSetList, options...)
if err != nil {
log.Error(err, "Failed to list all the Subnets")
return err
return nil, err
}
return subnetSetList, nil
}

func requeueSubnetSet(c client.Client, namespace string, q workqueue.RateLimitingInterface) error {
subnetSetList, err := listSubnetSet(c, context.Background(), client.InNamespace(namespace))
if err != nil {
log.Error(err, "Failed to list all the SubnetSets")
return err
}
for _, subnetSet := range subnetSetList.Items {
log.Info("Requeue SubnetSet because Namespace updated", "Namespace", subnetSet.Namespace, "Name", subnetSet.Name)
q.Add(reconcile.Request{
Expand Down
161 changes: 161 additions & 0 deletions pkg/controllers/subnetset/namespace_handler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
package subnetset

import (
"context"
"testing"

"github.com/agiledragon/gomonkey/v2"
"github.com/stretchr/testify/assert"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/util/workqueue"
ctlclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/event"

"github.com/vmware-tanzu/nsx-operator/pkg/apis/vpc/v1alpha1"
)

func TestEnqueueRequestForNamespace_Create(t *testing.T) {
client := fake.NewClientBuilder().Build()
e := &EnqueueRequestForNamespace{Client: client}
queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())

e.Create(context.TODO(), event.CreateEvent{}, queue)
// No asserts here because Create does nothing, just ensuring no errors.
}

func TestEnqueueRequestForNamespace_Delete(t *testing.T) {
client := fake.NewClientBuilder().Build()
e := &EnqueueRequestForNamespace{Client: client}
queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())

e.Delete(context.TODO(), event.DeleteEvent{}, queue)
// No asserts here because Delete does nothing, just ensuring no errors.
}

func TestEnqueueRequestForNamespace_Generic(t *testing.T) {
client := fake.NewClientBuilder().Build()
e := &EnqueueRequestForNamespace{Client: client}
queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())

e.Generic(context.TODO(), event.GenericEvent{}, queue)
// No asserts here because Generic does nothing, just ensuring no errors.
}

func TestEnqueueRequestForNamespace_Update(t *testing.T) {
// Prepare test data
oldNamespace := &v1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test-namespace",
Labels: map[string]string{"env": "test"},
},
}

newNamespace := &v1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test-namespace",
Labels: map[string]string{"env": "prod"},
},
}

client := fake.NewClientBuilder().WithObjects(newNamespace).Build()
e := &EnqueueRequestForNamespace{Client: client}
queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())

updateEvent := event.UpdateEvent{
ObjectOld: oldNamespace,
ObjectNew: newNamespace,
}

subnetSet := v1alpha1.SubnetSet{
ObjectMeta: metav1.ObjectMeta{
Name: "test-subnetset",
Namespace: "test-namespace",
},
}
subnetSetList := &v1alpha1.SubnetSetList{
TypeMeta: metav1.TypeMeta{},
ListMeta: metav1.ListMeta{},
Items: []v1alpha1.SubnetSet{subnetSet},
}

e.Update(context.TODO(), updateEvent, queue)
assert.Equal(t, 0, queue.Len(), "Expected 1 item to be requeued")

patches := gomonkey.ApplyFunc(listSubnetSet, func(c ctlclient.Client, ctx context.Context, options ...ctlclient.ListOption) (*v1alpha1.SubnetSetList, error) {
return subnetSetList, nil
})
defer patches.Reset()

e.Update(context.TODO(), updateEvent, queue)
assert.Equal(t, 1, queue.Len(), "Expected 1 item to be requeued")
}

func TestPredicateFuncsNs_UpdateFunc(t *testing.T) {
oldNamespace := &v1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test-namespace",
Labels: map[string]string{"env": "test"},
},
}

newNamespace := &v1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test-namespace",
Labels: map[string]string{"env": "prod"},
},
}

updateEvent := event.UpdateEvent{
ObjectOld: oldNamespace,
ObjectNew: newNamespace,
}

// Test the update function logic in PredicateFuncsNs
result := PredicateFuncsNs.UpdateFunc(updateEvent)
assert.True(t, result, "Expected update event to trigger requeue")

// Test with no label change
noChangeEvent := event.UpdateEvent{
ObjectOld: oldNamespace,
ObjectNew: oldNamespace,
}

result = PredicateFuncsNs.UpdateFunc(noChangeEvent)
assert.False(t, result, "Expected no action when labels have not changed")

res := PredicateFuncsNs.CreateFunc(event.CreateEvent{Object: newNamespace})
assert.False(t, res, "Expected no action when labels have not changed")

res = PredicateFuncsNs.DeleteFunc(event.DeleteEvent{Object: newNamespace})
assert.False(t, res, "Expected no action when labels have not changed")
}

func TestRequeueSubnetSet(t *testing.T) {
// Prepare test data
subnetSet := &v1alpha1.SubnetSet{
ObjectMeta: metav1.ObjectMeta{
Name: "test-subnetset",
Namespace: "test-namespace",
},
}

scheme := clientgoscheme.Scheme
v1alpha1.AddToScheme(scheme)

// Test for empty namespace (no SubnetSets found)
emptyClient := fake.NewClientBuilder().Build()
queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())
err := requeueSubnetSet(emptyClient, "empty-namespace", queue)
assert.NoError(t, err, "Expected no error with empty namespace")
assert.Equal(t, 0, queue.Len(), "Expected no items to be requeued for empty namespace")

client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(subnetSet).Build()
queue = workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())

err = requeueSubnetSet(client, "test-namespace", queue)
assert.NoError(t, err, "Expected no error while requeueing SubnetSets")
assert.Equal(t, 1, queue.Len(), "Expected 1 item to be requeued")
}
3 changes: 1 addition & 2 deletions pkg/controllers/subnetset/subnetset_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,8 +261,7 @@ func (r *SubnetSetReconciler) CollectGarbage(ctx context.Context) {
log.Info("SubnetSet garbage collection completed", "duration(ms)", time.Since(startTime).Milliseconds())
}()

crdSubnetSetList := &v1alpha1.SubnetSetList{}
err := r.Client.List(ctx, crdSubnetSetList)
crdSubnetSetList, err := listSubnetSet(r.Client, ctx)
if err != nil {
log.Error(err, "Failed to list SubnetSet CRs")
return
Expand Down
Loading
Loading