Skip to content

Commit

Permalink
Additional unit test coverage (#1780)
Browse files Browse the repository at this point in the history
  • Loading branch information
sebrandon1 authored Jan 4, 2024
1 parent 93da525 commit 6f4041b
Show file tree
Hide file tree
Showing 15 changed files with 271 additions and 65 deletions.
28 changes: 0 additions & 28 deletions cmd/tnf/generate/catalog/catalog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/test-network-function/cnf-certification-test/pkg/arrayhelper"
"github.com/test-network-function/test-network-function-claim/pkg/claim"
)

Expand Down Expand Up @@ -59,33 +58,6 @@ func TestRunGenerateMarkdownCmd(t *testing.T) {
assert.Nil(t, runGenerateMarkdownCmd(nil, nil))
}

func TestUnique(t *testing.T) {
testCases := []struct {
testSlice []string
expectedSlice []string
}{
{
testSlice: []string{"one", "two", "three"},
expectedSlice: []string{"one", "two", "three"},
},
{
testSlice: []string{"one", "two", "three", "three"},
expectedSlice: []string{"one", "two", "three"},
},
{
testSlice: []string{},
expectedSlice: []string{},
},
}

for _, tc := range testCases {
sort.Strings(tc.expectedSlice)
results := arrayhelper.Unique(tc.testSlice)
sort.Strings(results)
assert.True(t, reflect.DeepEqual(tc.expectedSlice, results))
}
}

func TestGetSuitesFromIdentifiers(t *testing.T) {
testCases := []struct {
testKeys []claim.Identifier
Expand Down
11 changes: 5 additions & 6 deletions cnf-certification-test/accesscontrol/rbac/automount.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,14 @@ import (
"context"
"fmt"

"github.com/test-network-function/cnf-certification-test/internal/clientsholder"
"github.com/test-network-function/cnf-certification-test/internal/log"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
corev1typed "k8s.io/client-go/kubernetes/typed/core/v1"
)

func AutomountServiceAccountSetOnSA(serviceAccountName, podNamespace string) (*bool, error) {
clientsHolder := clientsholder.GetClientsHolder()
sa, err := clientsHolder.K8sClient.CoreV1().ServiceAccounts(podNamespace).Get(context.TODO(), serviceAccountName, metav1.GetOptions{})
func AutomountServiceAccountSetOnSA(client corev1typed.CoreV1Interface, serviceAccountName, podNamespace string) (*bool, error) {
sa, err := client.ServiceAccounts(podNamespace).Get(context.TODO(), serviceAccountName, metav1.GetOptions{})
if err != nil {
log.Error("executing serviceaccount command failed with error: %v", err)
return nil, err
Expand All @@ -37,7 +36,7 @@ func AutomountServiceAccountSetOnSA(serviceAccountName, podNamespace string) (*b
}

//nolint:gocritic
func EvaluateAutomountTokens(put *corev1.Pod) (bool, string) {
func EvaluateAutomountTokens(client corev1typed.CoreV1Interface, put *corev1.Pod) (bool, string) {
// The token can be specified in the pod directly
// or it can be specified in the service account of the pod
// if no service account is configured, then the pod will use the configuration
Expand All @@ -50,7 +49,7 @@ func EvaluateAutomountTokens(put *corev1.Pod) (bool, string) {
}

// Collect information about the service account attached to the pod.
saAutomountServiceAccountToken, err := AutomountServiceAccountSetOnSA(put.Spec.ServiceAccountName, put.Namespace)
saAutomountServiceAccountToken, err := AutomountServiceAccountSetOnSA(client, put.Spec.ServiceAccountName, put.Namespace)
if err != nil {
return false, ""
}
Expand Down
8 changes: 4 additions & 4 deletions cnf-certification-test/accesscontrol/rbac/automount_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ func TestAutomountServiceAccountSetOnSA(t *testing.T) {
var testRuntimeObjects []runtime.Object
testRuntimeObjects = append(testRuntimeObjects, &testSA)

_ = clientsholder.GetTestClientsHolder(testRuntimeObjects)
isSet, err := AutomountServiceAccountSetOnSA("testSA", "podNS")
client := clientsholder.GetTestClientsHolder(testRuntimeObjects)
isSet, err := AutomountServiceAccountSetOnSA(client.K8sClient.CoreV1(), "testSA", "podNS")
assert.Nil(t, err)
assert.Equal(t, tc.automountServiceTokenSet, *isSet)
}
Expand Down Expand Up @@ -138,8 +138,8 @@ func TestEvaluateAutomountTokens(t *testing.T) {
}

for _, tc := range testCases {
_ = clientsholder.GetTestClientsHolder(buildServiceAccountTokenTestObjects())
podPassed, msg := EvaluateAutomountTokens(tc.testPod)
client := clientsholder.GetTestClientsHolder(buildServiceAccountTokenTestObjects())
podPassed, msg := EvaluateAutomountTokens(client.K8sClient.CoreV1(), tc.testPod)
assert.Equal(t, tc.expectedMsg, msg)
assert.Equal(t, tc.expectedResult, podPassed)
}
Expand Down
3 changes: 2 additions & 1 deletion cnf-certification-test/accesscontrol/suite.go
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,8 @@ func testAutomountServiceToken(check *checksdb.Check, env *provider.TestEnvironm
}

// Evaluate the pod's automount service tokens and any attached service accounts
podPassed, newMsg := rbac.EvaluateAutomountTokens(put.Pod)
client := clientsholder.GetClientsHolder()
podPassed, newMsg := rbac.EvaluateAutomountTokens(client.K8sClient.CoreV1(), put.Pod)
if !podPassed {
nonCompliantObjects = append(nonCompliantObjects, testhelper.NewPodReportObject(put.Namespace, put.Name, newMsg, false))
msg = append(msg, newMsg)
Expand Down
3 changes: 3 additions & 0 deletions internal/clientsholder/clientsholder.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import (
corev1 "k8s.io/api/core/v1"
policyv1 "k8s.io/api/policy/v1"
rbacv1 "k8s.io/api/rbac/v1"
storagev1 "k8s.io/api/storage/v1"
apiextv1fake "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/fake"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8sFakeClient "k8s.io/client-go/kubernetes/fake"
Expand Down Expand Up @@ -122,6 +123,8 @@ func GetTestClientsHolder(k8sMockObjects []runtime.Object) *ClientsHolder {
k8sClientObjects = append(k8sClientObjects, v)
case *scalingv1.HorizontalPodAutoscaler:
k8sClientObjects = append(k8sClientObjects, v)
case *storagev1.StorageClass:
k8sClientObjects = append(k8sClientObjects, v)

// K8s Extension Client Objects
case *apiextv1c.CustomResourceDefinition:
Expand Down
28 changes: 28 additions & 0 deletions pkg/arrayhelper/arrayhelper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package arrayhelper

import (
"reflect"
"sort"
"strings"
"testing"

Expand Down Expand Up @@ -85,3 +86,30 @@ func TestArgListToMap(t *testing.T) {
assert.True(t, reflect.DeepEqual(tc.expectedMap, ArgListToMap(tc.argList)))
}
}

func TestUnique(t *testing.T) {
testCases := []struct {
testSlice []string
expectedSlice []string
}{
{
testSlice: []string{"one", "two", "three"},
expectedSlice: []string{"one", "two", "three"},
},
{
testSlice: []string{"one", "two", "three", "three"},
expectedSlice: []string{"one", "two", "three"},
},
{
testSlice: []string{},
expectedSlice: []string{},
},
}

for _, tc := range testCases {
sort.Strings(tc.expectedSlice)
results := Unique(tc.testSlice)
sort.Strings(results)
assert.True(t, reflect.DeepEqual(tc.expectedSlice, results))
}
}
8 changes: 4 additions & 4 deletions pkg/autodiscover/autodiscover.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ func DoAutoDiscover(config *configuration.TestConfiguration) DiscoveredTestData
oc := clientsholder.GetClientsHolder()

var err error
data.StorageClasses, err = getAllStorageClasses()
data.StorageClasses, err = getAllStorageClasses(oc.K8sClient.StorageV1())
if err != nil {
log.Error("Failed to retrieve storageClasses - err: %v", err)
os.Exit(1)
Expand Down Expand Up @@ -196,21 +196,21 @@ func DoAutoDiscover(config *configuration.TestConfiguration) DiscoveredTestData
data.Deployments = findDeploymentByLabel(oc.K8sClient.AppsV1(), podsUnderTestLabelsObjects, data.Namespaces)
data.StatefulSet = findStatefulSetByLabel(oc.K8sClient.AppsV1(), podsUnderTestLabelsObjects, data.Namespaces)
// Find ClusterRoleBindings
clusterRoleBindings, err := getClusterRoleBindings()
clusterRoleBindings, err := getClusterRoleBindings(oc.K8sClient.RbacV1())
if err != nil {
log.Error("Cannot get cluster role bindings, error: %v", err)
os.Exit(1)
}
data.ClusterRoleBindings = clusterRoleBindings
// Find RoleBindings
roleBindings, err := getRoleBindings()
roleBindings, err := getRoleBindings(oc.K8sClient.RbacV1())
if err != nil {
log.Error("Cannot get cluster role bindings, error: %v", err)
os.Exit(1)
}
data.RoleBindings = roleBindings
// find roles
roles, err := getRoles()
roles, err := getRoles(oc.K8sClient.RbacV1())
if err != nil {
log.Error("Cannot get roles, error: %v", err)
os.Exit(1)
Expand Down
4 changes: 0 additions & 4 deletions pkg/autodiscover/autodiscover_events.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,6 @@ import (
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
)

type Event struct {
*corev1.Event
}

func findAbnormalEvents(oc corev1client.CoreV1Interface, namespaces []string) (abnormalEvents []corev1.Event) {
abnormalEvents = []corev1.Event{}
for _, ns := range namespaces {
Expand Down
50 changes: 50 additions & 0 deletions pkg/autodiscover/autodiscover_events_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,53 @@
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

package autodiscover

import (
"testing"

"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
k8sfake "k8s.io/client-go/kubernetes/fake"
)

func TestFindAbnormalEvents(t *testing.T) {
testCases := []struct {
expectedEvents []*corev1.Event
}{
{
expectedEvents: []*corev1.Event{
{
Reason: "FailedMount",
Type: "Warning",
ObjectMeta: metav1.ObjectMeta{
Namespace: "test-namespace",
Name: "test-event",
},
},
},
},
}

for _, testCase := range testCases {
var runtimeObjects []runtime.Object
for _, event := range testCase.expectedEvents {
runtimeObjects = append(runtimeObjects, event)
}

// Create fake client
client := k8sfake.NewSimpleClientset(runtimeObjects...)
abnormalEvents := findAbnormalEvents(client.CoreV1(), []string{"test-namespace"})
assert.Len(t, abnormalEvents, len(testCase.expectedEvents))

for _, event := range abnormalEvents {
for _, event2 := range testCase.expectedEvents {
if event.Name == event2.Name {
assert.Equal(t, event.Reason, event2.Reason)
assert.Equal(t, event.Type, event2.Type)
}
}
}
}
}
40 changes: 40 additions & 0 deletions pkg/autodiscover/autodiscover_networkpolicies_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,43 @@
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

package autodiscover

import (
"testing"

"github.com/stretchr/testify/assert"
networkingv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
k8sfake "k8s.io/client-go/kubernetes/fake"
)

func TestGetNetworkPolicies(t *testing.T) {
testCases := []struct {
expectedNetworkPolicies []*networkingv1.NetworkPolicy
}{
{
expectedNetworkPolicies: []*networkingv1.NetworkPolicy{
{
ObjectMeta: metav1.ObjectMeta{
Name: "test-network-policy",
Namespace: "test-namespace",
},
},
},
},
}

for _, testCase := range testCases {
var runtimeObjects []runtime.Object
for _, networkPolicy := range testCase.expectedNetworkPolicies {
runtimeObjects = append(runtimeObjects, networkPolicy)
}

// Create fake client
client := k8sfake.NewSimpleClientset(runtimeObjects...)
networkPolicies, err := getNetworkPolicies(client.NetworkingV1())
assert.Nil(t, err)
assert.Len(t, networkPolicies, len(testCase.expectedNetworkPolicies))
}
}
76 changes: 76 additions & 0 deletions pkg/autodiscover/autodiscover_podset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,3 +217,79 @@ func TestFindHpaControllers(t *testing.T) {
assert.Equal(t, tc.expectedResults, hpas)
}
}

func TestFindDeploymentByNameByNamespace(t *testing.T) {
generateDeployment := func(name, namespace string) *appsv1.Deployment {
return &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
}
}

testCases := []struct {
testDeploymentName string
testDeploymentNamespace string
expectedResults *appsv1.Deployment
}{
{
testDeploymentName: "testName",
testDeploymentNamespace: "testNamespace",
expectedResults: &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "testName",
Namespace: "testNamespace",
},
},
},
}

for _, tc := range testCases {
var testRuntimeObjects []runtime.Object
testRuntimeObjects = append(testRuntimeObjects, generateDeployment(tc.testDeploymentName, tc.testDeploymentNamespace))
oc := clientsholder.GetTestClientsHolder(testRuntimeObjects)

deployment, err := FindDeploymentByNameByNamespace(oc.K8sClient.AppsV1(), tc.testDeploymentNamespace, tc.testDeploymentName)
assert.Nil(t, err)
assert.Equal(t, tc.expectedResults, deployment)
}
}

func TestFindStatefulSetByNameByNamespace(t *testing.T) {
generateStatefulSet := func(name, namespace string) *appsv1.StatefulSet {
return &appsv1.StatefulSet{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
}
}

testCases := []struct {
testStatefulSetName string
testStatefulSetNamespace string
expectedResults *appsv1.StatefulSet
}{
{
testStatefulSetName: "testName",
testStatefulSetNamespace: "testNamespace",
expectedResults: &appsv1.StatefulSet{
ObjectMeta: metav1.ObjectMeta{
Name: "testName",
Namespace: "testNamespace",
},
},
},
}

for _, tc := range testCases {
var testRuntimeObjects []runtime.Object
testRuntimeObjects = append(testRuntimeObjects, generateStatefulSet(tc.testStatefulSetName, tc.testStatefulSetNamespace))
oc := clientsholder.GetTestClientsHolder(testRuntimeObjects)

statefulSet, err := FindStatefulsetByNameByNamespace(oc.K8sClient.AppsV1(), tc.testStatefulSetNamespace, tc.testStatefulSetName)
assert.Nil(t, err)
assert.Equal(t, tc.expectedResults, statefulSet)
}
}
Loading

0 comments on commit 6f4041b

Please sign in to comment.