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

test: enhance test coverage for keptn-cert-manager #3143

Merged
merged 2 commits into from
Aug 5, 2024
Merged
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
101 changes: 101 additions & 0 deletions keptn-cert-manager/eventfilter/eventfilter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"github.com/stretchr/testify/assert"
v1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"sigs.k8s.io/controller-runtime/pkg/event"
)

const (
Expand Down Expand Up @@ -76,3 +78,102 @@ func Test_matchesName(t *testing.T) {

assert.False(t, matchesName(deployment, []string{"my-deployment"}))
}

YashPimple marked this conversation as resolved.
Show resolved Hide resolved
func Test_matchesLabels(t *testing.T) {
deployment := &v1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": "test",
"env": "dev",
},
},
}

firstSelector := labels.SelectorFromSet(labels.Set{
"app": "test",
"env": "dev", // different value for 'env'
})

assert.True(t, matchesLabels(deployment, firstSelector))

secondSelectors := labels.SelectorFromSet(labels.Set{
"app": "test",
"env": "prod",
})

assert.False(t, matchesLabels(deployment, secondSelectors))

deploymentNoLabels := &v1.Deployment{}

assert.False(t, matchesLabels(deploymentNoLabels, firstSelector))
}

func TestForLabelsAndNamespace(t *testing.T) {
deployment := &v1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: testName1,
Namespace: testNamespace1,
Labels: map[string]string{
"app": "test",
"env": "dev",
},
},
}

selector := labels.SelectorFromSet(labels.Set{
"app": "test",
"env": "dev",
})

// when the deployments matched with labels and is present in the required namespace.
assert.True(t, ForLabelsAndNamespace(selector, testNamespace1).Generic(event.GenericEvent{Object: deployment}))

// when the namespace doesn't match.
assert.False(t, ForLabelsAndNamespace(selector, "another-namespace").Generic(event.GenericEvent{Object: deployment}))

// when the labels don't match.
deploymentNoLabels := &v1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: testName1,
Namespace: testNamespace1,
},
}
assert.False(t, ForLabelsAndNamespace(selector, testNamespace1).Generic(event.GenericEvent{Object: deploymentNoLabels}))
}

func TestForNamesAndNamespace(t *testing.T) {
deployment1 := &v1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "deployment-1",
Namespace: "test-namespace-1",
},
}

deployment2 := &v1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "deployment-2",
Namespace: "test-namespace-2",
},
}

names := []string{"deployment-1", "deployment-2"}
namespace := "test-namespace-1"

// Test deployments in the same namespace and with matching names
pred := ForNamesAndNamespace(names, namespace)
assert.True(t, pred.Generic(event.GenericEvent{Object: deployment1}))
assert.False(t, pred.Generic(event.GenericEvent{Object: deployment2}))

// Test deployments in different namespace
namespace = "test-namespace-2"
pred = ForNamesAndNamespace(names, namespace)
assert.False(t, pred.Generic(event.GenericEvent{Object: deployment1}))
assert.True(t, pred.Generic(event.GenericEvent{Object: deployment2}))

// Test deployments with mismatched names
names = []string{"deployment-3", "deployment-4"}
namespace = "test-namespace-1"
pred = ForNamesAndNamespace(names, namespace)
assert.False(t, pred.Generic(event.GenericEvent{Object: deployment1}))
assert.False(t, pred.Generic(event.GenericEvent{Object: deployment2}))
}
77 changes: 77 additions & 0 deletions keptn-cert-manager/kubeutils/certificates_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package kubeutils

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"math/big"
"testing"
"time"
)

func TestValidateCertificateExpiration(t *testing.T) {
certTemplate := &x509.Certificate{
SerialNumber: big.NewInt(1),
NotBefore: time.Now(),
NotAfter: time.Now().Add(24 * time.Hour),
}

privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("Failed to generate private key: %v", err)
}

certBytes, err := x509.CreateCertificate(rand.Reader, certTemplate, certTemplate, &privateKey.PublicKey, privateKey)
if err != nil {
t.Fatalf("Failed to create certificate: %v", err)
}

certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certBytes})

testCases := []struct {
name string
certData []byte
renewalThreshold time.Duration
now time.Time
expectedValid bool
expectedErrorNil bool
}{
{
name: "Valid certificate",
certData: certPEM,
renewalThreshold: 2 * time.Hour,
now: time.Now().Add(21 * time.Hour), // Certificate is still valids
expectedValid: true,
expectedErrorNil: true,
},
{
name: "Expired certificate",
certData: certPEM,
renewalThreshold: 2 * time.Hour,
now: time.Now().Add(25 * time.Hour), // Certificate has expired
expectedValid: false,
expectedErrorNil: true,
},
{
name: "Invalid PEM data",
certData: []byte("invalid PEM data"),
renewalThreshold: 2 * time.Hour,
now: time.Now(),
expectedValid: false,
expectedErrorNil: true,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
valid, err := ValidateCertificateExpiration(tc.certData, tc.renewalThreshold, tc.now)
if valid != tc.expectedValid {
t.Errorf("Expected valid=%v, got %v", tc.expectedValid, valid)
}
if (err == nil) != tc.expectedErrorNil {
t.Errorf("Expected error nil=%v, got error=%v", tc.expectedErrorNil, err)
}
})
}
}
41 changes: 41 additions & 0 deletions keptn-cert-manager/kubeutils/secret_test.go
YashPimple marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ func TestSecretQuery(t *testing.T) {
t.Run(`Update secret when data has changed`, testUpdateSecretWhenDataChanged)
t.Run(`Update secret when labels have changed`, testUpdateSecretWhenLabelsChanged)
t.Run(`Create secret in target namespace`, testCreateSecretInTargetNamespace)
t.Run(`New Secret`, Secretwithmutiplekeys)
}

func testGetSecret(t *testing.T) {
Expand Down Expand Up @@ -259,3 +260,43 @@ func createTestSecret(labels map[string]string, data map[string][]byte) *corev1.
}
return secret
}

func Secretwithmutiplekeys(t *testing.T) {

testCases := []struct {
name string
namespace string
data map[string][]byte
}{
{
name: "test-secret-1",
YashPimple marked this conversation as resolved.
Show resolved Hide resolved
namespace: "test-namespace-1",
data: map[string][]byte{
"key1": []byte("value1"),
"key2": []byte("value2"),
},
},
{
name: "test-secret-2",
namespace: "test-namespace-2",
data: map[string][]byte{
"key1": []byte("value1"),
},
},
{
name: "test-secret-3",
namespace: "test-namespace-3",
data: map[string][]byte{},
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
secret := NewSecret(tc.name, tc.namespace, tc.data)

assert.Equal(t, tc.name, secret.Name)
assert.Equal(t, tc.namespace, secret.Namespace)
assert.Equal(t, tc.data, secret.Data)
})
}
}
37 changes: 37 additions & 0 deletions keptn-cert-manager/pkg/certificates/watcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,3 +360,40 @@ func TestNewCertificateWatcher(t *testing.T) {
func TestNewNoOpCertificateWatcher(t *testing.T) {
require.EqualValues(t, NewNoOpCertificateWatcher(), &NoOpCertificateWatcher{})
}

func TestCertificateWatcher_watchForCertificatesSecret(t *testing.T) {
mockReader := newFakeClient()
logger := testr.New(t)

watcher := &CertificateWatcher{
apiReader: mockReader,
fs: afero.NewOsFs(),
certificateDirectory: "",
namespace: "",
certificateSecretName: "",
ICertificateHandler: defaultCertificateHandler{},
Log: logger,
}

updateSignal := make(chan struct{})
defer close(updateSignal)

updateCalled := false
go func() {
time.Sleep(10 * time.Millisecond)
updateSignal <- struct{}{}
}()

go watcher.watchForCertificatesSecret()

select {
case <-time.After(20 * time.Millisecond):
t.Error("Expected update but did not receive it within the specified interval")
case <-updateSignal:
updateCalled = true
}

if !updateCalled {
t.Error("updateCertificatesFromSecret method was not called as expected")
}
}
Loading