github.com/k8snetworkplumbingwg/sriov-network-operator@v1.2.1-0.20240408194816-2d2e5a45d453/controllers/suite_test.go (about)

     1  /*
     2  Copyright 2021.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package controllers
    18  
    19  import (
    20  	"context"
    21  	"os"
    22  	"path/filepath"
    23  	"testing"
    24  	"time"
    25  
    26  	. "github.com/onsi/ginkgo/v2"
    27  	. "github.com/onsi/gomega"
    28  
    29  	"go.uber.org/zap/zapcore"
    30  	corev1 "k8s.io/api/core/v1"
    31  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    32  	"k8s.io/client-go/kubernetes/scheme"
    33  	"k8s.io/client-go/rest"
    34  	ctrl "sigs.k8s.io/controller-runtime"
    35  	"sigs.k8s.io/controller-runtime/pkg/client"
    36  	"sigs.k8s.io/controller-runtime/pkg/envtest"
    37  	logf "sigs.k8s.io/controller-runtime/pkg/log"
    38  	"sigs.k8s.io/controller-runtime/pkg/log/zap"
    39  	"sigs.k8s.io/controller-runtime/pkg/manager"
    40  
    41  	netattdefv1 "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1"
    42  	openshiftconfigv1 "github.com/openshift/api/config/v1"
    43  	mcfgv1 "github.com/openshift/machine-config-operator/pkg/apis/machineconfiguration.openshift.io/v1"
    44  
    45  	//+kubebuilder:scaffold:imports
    46  	sriovnetworkv1 "github.com/k8snetworkplumbingwg/sriov-network-operator/api/v1"
    47  	"github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/vars"
    48  	"github.com/k8snetworkplumbingwg/sriov-network-operator/test/util"
    49  )
    50  
    51  // These tests use Ginkgo (BDD-style Go testing framework). Refer to
    52  // http://onsi.github.io/ginkgo/ to learn more about Ginkgo.
    53  
    54  var (
    55  	k8sClient client.Client
    56  	testEnv   *envtest.Environment
    57  	cfg       *rest.Config
    58  )
    59  
    60  // Define utility constants for object names and testing timeouts/durations and intervals.
    61  const testNamespace = "openshift-sriov-network-operator"
    62  
    63  func setupK8sManagerForTest() (manager.Manager, error) {
    64  	k8sManager, err := ctrl.NewManager(cfg, ctrl.Options{
    65  		Scheme: scheme.Scheme,
    66  	})
    67  
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  
    72  	k8sManager.GetCache().IndexField(context.Background(), &sriovnetworkv1.SriovNetwork{}, "spec.networkNamespace", func(o client.Object) []string {
    73  		return []string{o.(*sriovnetworkv1.SriovNetwork).Spec.NetworkNamespace}
    74  	})
    75  
    76  	k8sManager.GetCache().IndexField(context.Background(), &sriovnetworkv1.SriovIBNetwork{}, "spec.networkNamespace", func(o client.Object) []string {
    77  		return []string{o.(*sriovnetworkv1.SriovIBNetwork).Spec.NetworkNamespace}
    78  	})
    79  
    80  	return k8sManager, nil
    81  }
    82  
    83  var _ = BeforeSuite(func() {
    84  	var err error
    85  
    86  	logf.SetLogger(zap.New(
    87  		zap.WriteTo(GinkgoWriter),
    88  		zap.UseDevMode(true),
    89  		func(o *zap.Options) {
    90  			o.TimeEncoder = zapcore.RFC3339NanoTimeEncoder
    91  		}))
    92  
    93  	// Go to project root directory
    94  	err = os.Chdir("..")
    95  
    96  	By("setting up env variables for tests")
    97  	Expect(err).NotTo(HaveOccurred())
    98  	err = os.Setenv("RESOURCE_PREFIX", "openshift.io")
    99  	Expect(err).NotTo(HaveOccurred())
   100  	err = os.Setenv("NAMESPACE", "openshift-sriov-network-operator")
   101  	Expect(err).NotTo(HaveOccurred())
   102  	err = os.Setenv("ADMISSION_CONTROLLERS_ENABLED", "true")
   103  	Expect(err).NotTo(HaveOccurred())
   104  	err = os.Setenv("ADMISSION_CONTROLLERS_CERTIFICATES_OPERATOR_SECRET_NAME", "operator-webhook-cert")
   105  	Expect(err).NotTo(HaveOccurred())
   106  	err = os.Setenv("ADMISSION_CONTROLLERS_CERTIFICATES_INJECTOR_SECRET_NAME", "network-resources-injector-cert")
   107  	Expect(err).NotTo(HaveOccurred())
   108  	err = os.Setenv("SRIOV_CNI_IMAGE", "mock-image")
   109  	Expect(err).NotTo(HaveOccurred())
   110  	err = os.Setenv("SRIOV_INFINIBAND_CNI_IMAGE", "mock-image")
   111  	Expect(err).NotTo(HaveOccurred())
   112  	err = os.Setenv("OVS_CNI_IMAGE", "mock-image")
   113  	Expect(err).NotTo(HaveOccurred())
   114  	err = os.Setenv("SRIOV_DEVICE_PLUGIN_IMAGE", "mock-image")
   115  	Expect(err).NotTo(HaveOccurred())
   116  	err = os.Setenv("NETWORK_RESOURCES_INJECTOR_IMAGE", "mock-image")
   117  	Expect(err).NotTo(HaveOccurred())
   118  	err = os.Setenv("SRIOV_NETWORK_CONFIG_DAEMON_IMAGE", "mock-image")
   119  	Expect(err).NotTo(HaveOccurred())
   120  	err = os.Setenv("SRIOV_NETWORK_WEBHOOK_IMAGE", "mock-image")
   121  	Expect(err).NotTo(HaveOccurred())
   122  	err = os.Setenv("RELEASE_VERSION", "4.7.0")
   123  	Expect(err).NotTo(HaveOccurred())
   124  	err = os.Setenv("OPERATOR_NAME", "sriov-network-operator")
   125  	Expect(err).NotTo(HaveOccurred())
   126  
   127  	By("bootstrapping test environment")
   128  	testEnv = &envtest.Environment{
   129  		CRDDirectoryPaths:     []string{filepath.Join("config", "crd", "bases"), filepath.Join("test", "util", "crds")},
   130  		ErrorIfCRDPathMissing: true,
   131  	}
   132  
   133  	testEnv.ControlPlane.GetAPIServer().Configure().Set("disable-admission-plugins", "MutatingAdmissionWebhook", "ValidatingAdmissionWebhook")
   134  
   135  	cfg, err = testEnv.Start()
   136  	Expect(err).NotTo(HaveOccurred())
   137  	Expect(cfg).NotTo(BeNil())
   138  
   139  	By("registering schemes")
   140  	err = sriovnetworkv1.AddToScheme(scheme.Scheme)
   141  	Expect(err).NotTo(HaveOccurred())
   142  	err = netattdefv1.AddToScheme(scheme.Scheme)
   143  	Expect(err).NotTo(HaveOccurred())
   144  	err = mcfgv1.AddToScheme(scheme.Scheme)
   145  	Expect(err).NotTo(HaveOccurred())
   146  	err = openshiftconfigv1.AddToScheme(scheme.Scheme)
   147  	Expect(err).NotTo(HaveOccurred())
   148  
   149  	vars.Config = cfg
   150  	vars.Scheme = scheme.Scheme
   151  	vars.Namespace = testNamespace
   152  
   153  	By("creating K8s client")
   154  	k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme})
   155  	Expect(err).NotTo(HaveOccurred())
   156  	Expect(k8sClient).NotTo(BeNil())
   157  
   158  	By("creating default/common k8s objects for tests")
   159  	// Create test namespace
   160  	ns := &corev1.Namespace{
   161  		TypeMeta: metav1.TypeMeta{},
   162  		ObjectMeta: metav1.ObjectMeta{
   163  			Name: testNamespace,
   164  		},
   165  		Spec:   corev1.NamespaceSpec{},
   166  		Status: corev1.NamespaceStatus{},
   167  	}
   168  	Expect(k8sClient.Create(context.Background(), ns)).Should(Succeed())
   169  
   170  	// Create openshift Infrastructure
   171  	infra := &openshiftconfigv1.Infrastructure{
   172  		ObjectMeta: metav1.ObjectMeta{
   173  			Name: "cluster",
   174  		},
   175  		Spec: openshiftconfigv1.InfrastructureSpec{},
   176  		Status: openshiftconfigv1.InfrastructureStatus{
   177  			ControlPlaneTopology: openshiftconfigv1.HighlyAvailableTopologyMode,
   178  		},
   179  	}
   180  	Expect(k8sClient.Create(context.Background(), infra)).Should(Succeed())
   181  })
   182  
   183  var _ = AfterSuite(func() {
   184  	By("tearing down the test environment")
   185  	if testEnv != nil {
   186  		Eventually(func() error {
   187  			return testEnv.Stop()
   188  		}, util.APITimeout, time.Second).ShouldNot(HaveOccurred())
   189  	}
   190  })
   191  
   192  func TestAPIs(t *testing.T) {
   193  	_, reporterConfig := GinkgoConfiguration()
   194  
   195  	RegisterFailHandler(Fail)
   196  
   197  	RunSpecs(t, "Controller Suite", reporterConfig)
   198  }