Skip to content

Commit

Permalink
chore: Add missing tests for rendering manifests (Mellanox#814)
Browse files Browse the repository at this point in the history
This PR adds tests for `GetManifestObjects` functions across the board.
The purpose of these tests is to ensure that each and every field can be
rendered, and to prevent regressions from changes in the yamls.

This PR includes Mellanox#813 and should be held until that one merges.
  • Loading branch information
adrianchiris authored Mar 1, 2024
2 parents 5e695f9 + 1a2d3b7 commit 117f9a0
Show file tree
Hide file tree
Showing 4 changed files with 238 additions and 1 deletion.
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,10 @@ $(CERT_MANAGER_YAML): | $(MANIFESTDIR)
lint: | $(GOLANGCI_LINT) ; $(info running golangci-lint...) @ ## Run golangci-lint
$Q $(GOLANGCI_LINT) run --timeout=10m

.PHONY: lint-fix
lint-fix: | $(GOLANGCI_LINT) ; $(info running golangci-lint...) @ ## Run golangci-lint and fix findings where possible
$Q $(GOLANGCI_LINT) run --timeout=10m --fix

.PHONY: lint-dockerfile
lint-dockerfile: $(HADOLINT) ; $(info running Dockerfile lint with hadolint...) @ ## Run hadolint
# Ignoring warning DL3029: Do not use --platform flag with FROM
Expand Down
2 changes: 1 addition & 1 deletion pkg/state/state_nic_feature_discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ func (s *stateNICFeatureDiscovery) Sync(
return syncState, nil
}

// Get a map of source kinds that should be watched for the state keyed by the source kind name
// GetWatchSources returns a map of source kinds that should be watched for the state keyed by the source kind name
func (s *stateNICFeatureDiscovery) GetWatchSources() map[string]client.Object {
wr := make(map[string]client.Object)
wr["DaemonSet"] = &appsv1.DaemonSet{}
Expand Down
180 changes: 180 additions & 0 deletions pkg/state/state_nic_feature_discovery_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
/*
2024 NVIDIA CORPORATION & AFFILIATES
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package state_test

import (
"context"
"fmt"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"

appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/log"

mellanoxv1alpha1 "github.com/Mellanox/network-operator/api/v1alpha1"
"github.com/Mellanox/network-operator/pkg/state"
)

var _ = Describe("NicClusterPolicyReconciler Controller", func() {
ctx := context.Background()

imageSpec := addContainerResources(getTestImageSpec(), "nic-feature-discovery", "5", "3")
cr := getTestClusterPolicyWithBaseFields()
cr.Spec.NicFeatureDiscovery = &mellanoxv1alpha1.NICFeatureDiscoverySpec{ImageSpec: *imageSpec}
_, s, err := state.NewStateNICFeatureDiscovery(fake.NewClientBuilder().Build(),
"../../manifests/state-nic-feature-discovery")
Expect(err).ToNot(HaveOccurred())

It("should test fields are set correctly", func() {
GetManifestObjectsTest(ctx, cr, getTestCatalog(), imageSpec, s)
})
})

func getTestClusterPolicyWithBaseFields() *mellanoxv1alpha1.NicClusterPolicy {
return &mellanoxv1alpha1.NicClusterPolicy{
Spec: mellanoxv1alpha1.NicClusterPolicySpec{
NodeAffinity: &corev1.NodeAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{
NodeSelectorTerms: []corev1.NodeSelectorTerm{
{
MatchExpressions: []corev1.NodeSelectorRequirement{{
Key: "node-label",
Operator: corev1.NodeSelectorOpIn,
Values: []string{"labels"},
},
},
},
},
},
PreferredDuringSchedulingIgnoredDuringExecution: nil,
},
Tolerations: []corev1.Toleration{{Key: "first-taint"}},
},
}
}

func assertCommonPodTemplateFields(template *corev1.PodTemplateSpec, image *mellanoxv1alpha1.ImageSpec) {
// Image name
Expect(template.Spec.Containers[0].Image).To(Equal(
fmt.Sprintf("%v/%v:%v", image.Repository, image.Image, image.Version)),
)

// ImagePullSecrets
Expect(template.Spec.ImagePullSecrets).To(ConsistOf(
corev1.LocalObjectReference{Name: "secret-one"},
corev1.LocalObjectReference{Name: "secret-two"},
))

// Container Resources
Expect(template.Spec.Containers[0].Resources.Limits).To(Equal(image.ContainerResources[0].Limits))
Expect(template.Spec.Containers[0].Resources.Requests).To(Equal(image.ContainerResources[0].Requests))
}

func assertCommonDeploymentFields(u *unstructured.Unstructured, image *mellanoxv1alpha1.ImageSpec) {
d := &appsv1.Deployment{}
err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.UnstructuredContent(), d)
Expect(err).ToNot(HaveOccurred())
assertCommonPodTemplateFields(&d.Spec.Template, image)
}

func assertCommonDaemonSetFields(u *unstructured.Unstructured,
image *mellanoxv1alpha1.ImageSpec, policy *mellanoxv1alpha1.NicClusterPolicy) {
ds := &appsv1.DaemonSet{}
err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.UnstructuredContent(), ds)
Expect(err).ToNot(HaveOccurred())
assertCommonPodTemplateFields(&ds.Spec.Template, image)
// Tolerations
Expect(ds.Spec.Template.Spec.Tolerations).To(ContainElements(
corev1.Toleration{Key: "first-taint"},
corev1.Toleration{
Key: "nvidia.com/gpu",
Operator: "Exists",
Value: "",
Effect: "NoSchedule",
TolerationSeconds: nil,
},
))

// NodeAffinity
Expect(ds.Spec.Template.Spec.Affinity.NodeAffinity).To(Equal(policy.Spec.NodeAffinity))
}

func getTestImageSpec() *mellanoxv1alpha1.ImageSpec {
return &mellanoxv1alpha1.ImageSpec{
Image: "image-one",
Repository: "repository",
Version: "five",
ImagePullSecrets: []string{"secret-one", "secret-two"},
}
}

func addContainerResources(imageSpec *mellanoxv1alpha1.ImageSpec,
containerName, requestValue, limitValue string) *mellanoxv1alpha1.ImageSpec {
i := imageSpec.DeepCopy()
i.ContainerResources = append(i.ContainerResources, []mellanoxv1alpha1.ResourceRequirements{
{
Name: containerName,
Limits: map[corev1.ResourceName]resource.Quantity{"resource-one": resource.MustParse(limitValue)},
Requests: map[corev1.ResourceName]resource.Quantity{"resource-one": resource.MustParse(requestValue)},
},
}...)
return i
}

func isNamespaced(obj *unstructured.Unstructured) bool {
return obj.GetKind() != "CustomResourceDefinition" &&
obj.GetKind() != "ClusterRole" &&
obj.GetKind() != "ClusterRoleBinding" &&
obj.GetKind() != "ValidatingWebhookConfiguration"
}

func assertCNIBinDirForDS(u *unstructured.Unstructured) {
ds := &appsv1.DaemonSet{}
err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.UnstructuredContent(), ds)
Expect(err).ToNot(HaveOccurred())
for i := range ds.Spec.Template.Spec.Volumes {
vol := ds.Spec.Template.Spec.Volumes[i]
if vol.Name == "cnibin" {
Expect(vol.HostPath).NotTo(BeNil())
Expect(vol.HostPath.Path).To(Equal("custom-cni-bin-directory"))
}
}
}

func GetManifestObjectsTest(ctx context.Context, cr *mellanoxv1alpha1.NicClusterPolicy, catalog state.InfoCatalog,
imageSpec *mellanoxv1alpha1.ImageSpec, renderer state.ManifestRenderer) {
got, err := renderer.GetManifestObjects(ctx, cr, catalog, log.FromContext(ctx))
Expect(err).ToNot(HaveOccurred())
for i := range got {
if isNamespaced(got[i]) {
Expect(got[i].GetNamespace()).To(Equal("nvidia-network-operator"))
}
switch got[i].GetKind() {
case "DaemonSet":
assertCommonDaemonSetFields(got[i], imageSpec, cr)
assertCNIBinDirForDS(got[i])
case "Deployment":
assertCommonDeploymentFields(got[i], imageSpec)
}
}
}
53 changes: 53 additions & 0 deletions pkg/state/state_nv_ipam_cni_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
2024 NVIDIA CORPORATION & AFFILIATES
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package state_test

import (
"context"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"sigs.k8s.io/controller-runtime/pkg/client/fake"

"github.com/Mellanox/network-operator/pkg/state"

mellanoxv1alpha1 "github.com/Mellanox/network-operator/api/v1alpha1"
"github.com/Mellanox/network-operator/pkg/staticconfig"
)

var _ = Describe("NVIPAM Controller", func() {
ctx := context.Background()

imageSpec := getTestImageSpec()
imageSpec = addContainerResources(imageSpec, "nv-ipam-node", "5", "3")
imageSpec = addContainerResources(imageSpec, "nv-ipam-controller", "5", "3")
cr := getTestClusterPolicyWithBaseFields()
cr.Spec.NvIpam = &mellanoxv1alpha1.NVIPAMSpec{
// TODO(killianmuldoon): Test with the webhook enabled.
EnableWebhook: false,
ImageSpec: *imageSpec,
}
catalog := getTestCatalog()
catalog.Add(state.InfoTypeStaticConfig,
staticconfig.NewProvider(staticconfig.StaticConfig{CniBinDirectory: "custom-cni-bin-directory"}))

_, s, err := state.NewStateNVIPAMCNI(fake.NewClientBuilder().Build(), "../../manifests/state-nv-ipam-cni")
Expect(err).NotTo(HaveOccurred())
It("should test that manifests are rendered and fields are set correctly", func() {
GetManifestObjectsTest(ctx, cr, catalog, imageSpec, s)
})
})

0 comments on commit 117f9a0

Please sign in to comment.