Skip to content

Commit

Permalink
Update unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Mario Manno committed Nov 27, 2023
1 parent 11b7007 commit c10f21e
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 66 deletions.
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
package bundledeployment
package deployer

//go:generate mockgen --build_flags=--mod=mod -destination=../../../controller/mocks/dynamic_mock.go -package mocks k8s.io/client-go/dynamic Interface,NamespaceableResourceInterface

import (
"context"
"errors"
"testing"

"github.com/golang/mock/gomock"

"github.com/rancher/fleet/internal/cmd/controller/mocks"
fleet "github.com/rancher/fleet/pkg/apis/fleet.cattle.io/v1alpha1"

corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)

func TestSetNamespaceLabelsAndAnnotations(t *testing.T) {
Expand All @@ -33,13 +34,14 @@ func TestSetNamespaceLabelsAndAnnotations(t *testing.T) {
}},
ns: corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"name": "test"},
Name: "namespace1234",
Labels: map[string]string{"name": "namespace"},
},
},
release: "namespace/foo/bar",
expectedNs: corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"name": "test", "optLabel1": "optValue1", "optLabel2": "optValue2"},
Labels: map[string]string{"name": "namespace", "optLabel1": "optValue1", "optLabel2": "optValue2"},
Annotations: map[string]string{"optAnn1": "optValue1"},
},
},
Expand All @@ -54,14 +56,15 @@ func TestSetNamespaceLabelsAndAnnotations(t *testing.T) {
}},
ns: corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"nsLabel": "nsValue", "name": "test"},
Name: "namespace1234",
Labels: map[string]string{"nsLabel": "nsValue", "name": "namespace"},
Annotations: map[string]string{"nsAnn": "nsValue"},
},
},
release: "namespace/foo/bar",
expectedNs: corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"optLabel": "optValue", "name": "test"},
Labels: map[string]string{"optLabel": "optValue", "name": "namespace"},
Annotations: map[string]string{},
},
},
Expand All @@ -76,14 +79,15 @@ func TestSetNamespaceLabelsAndAnnotations(t *testing.T) {
}},
ns: corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"bdLabel": "nsValue"},
Name: "namespace1234",
Labels: map[string]string{"bdLabel": "nsValue", "name": "namespace"},
Annotations: map[string]string{"bdAnn": "nsValue"},
},
},
release: "namespace/foo/bar",
expectedNs: corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"bdLabel": "labelUpdated"},
Labels: map[string]string{"bdLabel": "labelUpdated", "name": "namespace"},
Annotations: map[string]string{"bdAnn": "annUpdated"},
},
},
Expand All @@ -92,30 +96,32 @@ func TestSetNamespaceLabelsAndAnnotations(t *testing.T) {

for name, test := range tests {
t.Run(name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()

mockDynamic := mocks.NewMockInterface(ctrl)
mockNamespaceableResourceInterface := mocks.NewMockNamespaceableResourceInterface(ctrl)
u, _ := runtime.DefaultUnstructuredConverter.ToUnstructured(&test.ns)
// Resource will be called twice, one time for UPDATE and another time for LIST
mockDynamic.EXPECT().Resource(gomock.Any()).Return(mockNamespaceableResourceInterface).Times(2)
mockNamespaceableResourceInterface.EXPECT().List(gomock.Any(), metav1.ListOptions{
LabelSelector: "name=namespace",
}).Return(&unstructured.UnstructuredList{
Items: []unstructured.Unstructured{{Object: u}},
}, nil).Times(1)
uns, _ := runtime.DefaultUnstructuredConverter.ToUnstructured(&test.expectedNs)
mockNamespaceableResourceInterface.EXPECT().Update(gomock.Any(), &unstructured.Unstructured{Object: uns}, gomock.Any()).Times(1)

h := handler{
dynamic: mockDynamic,
scheme := runtime.NewScheme()
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&test.ns).Build()
h := Deployer{
client: client,
}
err := h.setNamespaceLabelsAndAnnotations(context.Background(), test.bd, test.release)
if err != nil {
t.Errorf("expected nil error: got %v", err)
}
err := h.setNamespaceLabelsAndAnnotations(test.bd, test.release)

ns := &corev1.Namespace{}
err = client.Get(context.Background(), types.NamespacedName{Name: test.ns.Name}, ns)
if err != nil {
t.Errorf("expected nil error: got %v", err)
}
for k, v := range test.expectedNs.Labels {
if ns.Labels[k] != v {
t.Errorf("expected label %s: %s, got %s", k, v, ns.Labels[k])
}
}
for k, v := range test.expectedNs.Annotations {
if ns.Annotations[k] != v {
t.Errorf("expected annotation %s: %s, got %s", k, v, ns.Annotations[k])
}
}
})
}
}
Expand All @@ -130,20 +136,14 @@ func TestSetNamespaceLabelsAndAnnotationsError(t *testing.T) {
release := "test/foo/bar"
expectedErr := errors.New("namespace test not found")

ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockDynamic := mocks.NewMockInterface(ctrl)
mockNamespaceableResourceInterface := mocks.NewMockNamespaceableResourceInterface(ctrl)
mockDynamic.EXPECT().Resource(gomock.Any()).Return(mockNamespaceableResourceInterface).Times(1)
mockNamespaceableResourceInterface.EXPECT().List(gomock.Any(), metav1.ListOptions{
LabelSelector: "name=test",
}).Return(&unstructured.UnstructuredList{
Items: []unstructured.Unstructured{},
}, nil).Times(1)
h := handler{
dynamic: mockDynamic,
scheme := runtime.NewScheme()
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
client := fake.NewClientBuilder().WithScheme(scheme).Build()
h := Deployer{
client: client,
}
err := h.setNamespaceLabelsAndAnnotations(bd, release)

err := h.setNamespaceLabelsAndAnnotations(context.Background(), bd, release)

if err.Error() != expectedErr.Error() {
t.Errorf("expected error %v: got %v", expectedErr, err)
Expand Down
63 changes: 40 additions & 23 deletions internal/helmdeployer/helmcache/secret_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,69 +4,80 @@ import (
"context"
"testing"

"github.com/golang/mock/gomock"
"github.com/google/go-cmp/cmp"
"github.com/rancher/wrangler/v2/pkg/generic/fake"

corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
applycorev1 "k8s.io/client-go/applyconfigurations/core/v1"
v1 "k8s.io/client-go/applyconfigurations/meta/v1"
k8sfake "k8s.io/client-go/kubernetes/fake"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)

const (
secretName = "test"
secretNamespace = "test-ns"
)

var secret = corev1.Secret{
var defaultSecret = corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
Namespace: secretNamespace,
},
}

func TestGet(t *testing.T) {
ctrl := gomock.NewController(t)
mockCache := fake.NewMockCacheInterface[*corev1.Secret](ctrl)
secretClient := NewSecretClient(mockCache, nil, secretNamespace)
mockCache.EXPECT().Get(secretNamespace, secretName).Return(&secret, nil)
scheme := runtime.NewScheme()
utilruntime.Must(clientgoscheme.AddToScheme(scheme))

secretGot, err := secretClient.Get(context.TODO(), secretName, metav1.GetOptions{})
secret := defaultSecret
cache := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&secret).Build()
secretClient := NewSecretClient(cache, nil, secretNamespace)

secretGot, err := secretClient.Get(context.TODO(), secretName, metav1.GetOptions{})
if err != nil {
t.Errorf("unexpected error %v", err)
}
if !cmp.Equal(&secret, secretGot) {
t.Errorf("expected secret %v, got %v", secret, secretGot)
if !cmp.Equal(secret.ObjectMeta, secretGot.ObjectMeta) {
t.Errorf("expected secret meta %#v, got %#v", secret.ObjectMeta, secretGot.ObjectMeta)
}
if !cmp.Equal(secret.Data, secretGot.Data) {
t.Errorf("expected secret data %#v, got %#v", secret.Data, secretGot.Data)
}
}

func TestList(t *testing.T) {
ctrl := gomock.NewController(t)
mockCache := fake.NewMockCacheInterface[*corev1.Secret](ctrl)
secretClient := NewSecretClient(mockCache, nil, secretNamespace)
labelSelector, err := labels.Parse("foo=bar")
if err != nil {
t.Errorf("unexpected error %v", err)
}
mockCache.EXPECT().List(secretNamespace, labelSelector).Return([]*corev1.Secret{&secret}, nil)
secretList, err := secretClient.List(context.TODO(), metav1.ListOptions{LabelSelector: "foo=bar"})
scheme := runtime.NewScheme()
utilruntime.Must(clientgoscheme.AddToScheme(scheme))

secret := defaultSecret
secret.Labels = map[string]string{"foo": "bar"}
cache := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&secret).Build()
secretClient := NewSecretClient(cache, nil, secretNamespace)

secretList, err := secretClient.List(context.TODO(), metav1.ListOptions{LabelSelector: "foo=bar"})
if err != nil {
t.Errorf("unexpected error %v", err)
}
secretListExpected := &corev1.SecretList{Items: []corev1.Secret{secret}}
if !cmp.Equal(secretListExpected, secretList) {
t.Errorf("expected secret %v, got %v", secretListExpected, secretList)
if len(secretList.Items) != 1 {
t.Errorf("expected secret list to have 1 element, got %v", len(secretList.Items))
}
if !cmp.Equal(secret.ObjectMeta, secretList.Items[0].ObjectMeta) {
t.Errorf("expected secret meta %#v, got %#v", secret, secretList.Items[0])
}
if !cmp.Equal(secret.Data, secretList.Items[0].Data) {
t.Errorf("expected secret data %#v, got %#v", secret, secretList.Items[0])
}
}

func TestCreate(t *testing.T) {
client := k8sfake.NewSimpleClientset()
secretClient := NewSecretClient(nil, client, secretNamespace)
secret := defaultSecret
secretCreated, err := secretClient.Create(context.TODO(), &secret, metav1.CreateOptions{})

if err != nil {
Expand All @@ -85,6 +96,7 @@ func TestUpdate(t *testing.T) {
},
Data: map[string][]byte{"test": []byte("data")},
}
secret := defaultSecret
client := k8sfake.NewSimpleClientset(&secret)
secretClient := NewSecretClient(nil, client, secretNamespace)
secretUpdated, err := secretClient.Update(context.TODO(), &secretUpdate, metav1.UpdateOptions{})
Expand All @@ -98,6 +110,7 @@ func TestUpdate(t *testing.T) {
}

func TestDelete(t *testing.T) {
secret := defaultSecret
client := k8sfake.NewSimpleClientset(&secret)
secretClient := NewSecretClient(nil, client, secretNamespace)
err := secretClient.Delete(context.TODO(), secretName, metav1.DeleteOptions{})
Expand All @@ -108,6 +121,7 @@ func TestDelete(t *testing.T) {
}

func TestDeleteCollection(t *testing.T) {
secret := defaultSecret
client := k8sfake.NewSimpleClientset(&secret)
secretClient := NewSecretClient(nil, client, secretNamespace)
err := secretClient.DeleteCollection(context.TODO(), metav1.DeleteOptions{}, metav1.ListOptions{FieldSelector: "name=" + secretName})
Expand All @@ -118,6 +132,7 @@ func TestDeleteCollection(t *testing.T) {
}

func TestWatch(t *testing.T) {
secret := defaultSecret
client := k8sfake.NewSimpleClientset(&secret)
secretClient := NewSecretClient(nil, client, secretNamespace)
watch, err := secretClient.Watch(context.TODO(), metav1.ListOptions{FieldSelector: "name=" + secretName})
Expand All @@ -138,6 +153,7 @@ func TestPatch(t *testing.T) {
},
Data: map[string][]byte{"test": []byte("content")},
}
secret := defaultSecret
client := k8sfake.NewSimpleClientset(&secret)
secretClient := NewSecretClient(nil, client, secretNamespace)
patch := []byte(`{"data":{"test":"Y29udGVudA=="}}`) // "content", base64-encoded
Expand All @@ -159,6 +175,7 @@ func TestApply(t *testing.T) {
},
Data: map[string][]byte{"test": []byte("content")},
}
secret := defaultSecret
client := k8sfake.NewSimpleClientset(&secret)
secretClient := NewSecretClient(nil, client, secretNamespace)
secretName := "test"
Expand Down

0 comments on commit c10f21e

Please sign in to comment.