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

chore: Add missing tests for rendering manifests #814

Merged
merged 1 commit into from
Mar 1, 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
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
rollandf marked this conversation as resolved.
Show resolved Hide resolved
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,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we could expand this test to include more objects and checks. We'd then be able to run it on all Manifests for templating which is in common. Specific tests can then be run for fields which are different or novel between states.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the idea. This function is already used in two files. Should we put it to common_test.go?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1, this can be done in a followup.

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)
})
})
Loading