// SPDX-FileCopyrightText: SAP SE or an SAP affiliate company and IronCore contributors // SPDX-License-Identifier: Apache-2.0 package controller import ( "context" "fmt" "path/filepath" "runtime" "testing" "time" "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/config" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" "github.com/ironcore-dev/controller-utils/modutils" metalv1alpha1 "github.com/ironcore-dev/metal-operator/api/v1alpha1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ctrl "sigs.k8s.io/controller-runtime" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/envtest" . "sigs.k8s.io/controller-runtime/pkg/envtest/komega" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/log/zap" bootv1alpha1 "github.com/ironcore-dev/boot-operator/api/v1alpha1" "github.com/ironcore-dev/boot-operator/internal/registry" testregistry "github.com/ironcore-dev/boot-operator/test/registry" //+kubebuilder:scaffold:imports ) const ( pollingInterval = 50 * time.Millisecond eventuallyTimeout = 3 * time.Second consistentlyDuration = 1 * time.Second ) var ( cfg *rest.Config k8sClient client.Client testEnv *envtest.Environment mockRegistry *testregistry.MockRegistry allowedRegistries string ) func TestControllers(t *testing.T) { SetDefaultConsistentlyPollingInterval(pollingInterval) SetDefaultEventuallyPollingInterval(pollingInterval) SetDefaultEventuallyTimeout(eventuallyTimeout) SetDefaultConsistentlyDuration(consistentlyDuration) RegisterFailHandler(Fail) RunSpecs(t, "Controller Suite") } var _ = BeforeSuite(func() { logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) By("starting mock OCI registry") mockRegistry = testregistry.NewMockRegistry() DeferCleanup(mockRegistry.Close) // Push test images to mock registry (using simple paths without localhost prefix) Expect(mockRegistry.PushPXEImage("ironcore-dev/os-images/gardenlinux", "1877.0", runtime.GOARCH)).To(Succeed()) Expect(mockRegistry.PushPXEImageOldFormat("gardenlinux/gardenlinux", "1772.0", runtime.GOARCH)).To(Succeed()) Expect(mockRegistry.PushPXEImageNoSquashFS("ironcore-dev/os-images/sanitizer", "1.0.0", runtime.GOARCH)).To(Succeed()) Expect(mockRegistry.PushHTTPImage("ironcore-dev/os-images/test-image", "100.1")).To(Succeed()) // Set allowed registries to use mock registry allowedRegistries = mockRegistry.RegistryAddress() By("bootstrapping test environment") testEnv = &envtest.Environment{ CRDDirectoryPaths: []string{ filepath.Join("..", "..", "config", "crd", "bases"), filepath.Join(modutils.Dir("github.com/ironcore-dev/metal-operator", "config", "crd", "bases")), }, ErrorIfCRDPathMissing: true, // The BinaryAssetsDirectory is only required if you want to run the tests directly // without call the makefile target test. If not informed it will look for the // default path defined in controller-runtime which is /usr/local/kubebuilder/. // Note that you must have the required binaries setup under the bin directory to perform // the tests directly. When we run make test it will be setup and used automatically. BinaryAssetsDirectory: filepath.Join("..", "..", "bin", "k8s", fmt.Sprintf("1.35.0-%s-%s", runtime.GOOS, runtime.GOARCH)), } var err error // cfg is defined in this file globally. cfg, err = testEnv.Start() Expect(err).NotTo(HaveOccurred()) Expect(cfg).NotTo(BeNil()) DeferCleanup(testEnv.Stop) Expect(bootv1alpha1.AddToScheme(scheme.Scheme)).NotTo(HaveOccurred()) Expect(metalv1alpha1.AddToScheme(scheme.Scheme)).NotTo(HaveOccurred()) err = bootv1alpha1.AddToScheme(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) //+kubebuilder:scaffold:scheme k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) Expect(err).NotTo(HaveOccurred()) Expect(k8sClient).NotTo(BeNil()) // set komega client SetClient(k8sClient) }) func SetupTest() *corev1.Namespace { ns := &corev1.Namespace{} BeforeEach(func(ctx SpecContext) { var mgrCtx context.Context mgrCtx, cancel := context.WithCancel(context.Background()) DeferCleanup(cancel) *ns = corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "test-", }, } Expect(k8sClient.Create(ctx, ns)).To(Succeed(), "failed to create test namespace") DeferCleanup(k8sClient.Delete, ns) k8sManager, err := ctrl.NewManager(cfg, ctrl.Options{ Scheme: scheme.Scheme, Metrics: metricsserver.Options{ BindAddress: "0", // Disable metrics server to avoid port 8080 conflicts with Tilt }, Controller: config.Controller{ // need to skip unique controller name validation // since all tests need a dedicated controller SkipNameValidation: ptr.To(true), }, }) Expect(err).ToNot(HaveOccurred()) registryValidator := registry.NewValidator(allowedRegistries) Expect((&ServerBootConfigurationPXEReconciler{ Client: k8sManager.GetClient(), Scheme: k8sManager.GetScheme(), IPXEServiceURL: "http://localhost:5000", Architecture: runtime.GOARCH, RegistryValidator: registryValidator, }).SetupWithManager(k8sManager)).To(Succeed()) Expect((&ServerBootConfigurationHTTPReconciler{ Client: k8sManager.GetClient(), Scheme: k8sManager.GetScheme(), ImageServerURL: "http://localhost:5000/httpboot", Architecture: runtime.GOARCH, RegistryValidator: registryValidator, }).SetupWithManager(k8sManager)).To(Succeed()) go func() { defer GinkgoRecover() Expect(k8sManager.Start(mgrCtx)).To(Succeed(), "failed to start manager") }() }) return ns } // MockImageRef returns a fully qualified image reference for the mock registry func MockImageRef(name, tag string) string { return fmt.Sprintf("%s/%s:%s", mockRegistry.RegistryAddress(), name, tag) }