Skip to content

Commit

Permalink
added basic reconciler test
Browse files Browse the repository at this point in the history
moved controller manifests to controller pkg as an asset
  • Loading branch information
hellt committed Mar 11, 2023
1 parent da6ff95 commit 133ccd5
Show file tree
Hide file tree
Showing 11 changed files with 173 additions and 17 deletions.
4 changes: 1 addition & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ RUN go mod download
COPY main.go main.go
COPY api/ api/
COPY controllers/ controllers/
# srl-controller specific manifests that we embed in the controller binary
# such as configmaps with entrypoints, topology files and auxiliary scripts.
COPY manifests/ manifests/


# Build
# the GOARCH has not a default value to allow the binary be built according to the host where the command
Expand Down
3 changes: 2 additions & 1 deletion api/v1/srlinux_types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,8 @@ func TestGetConstraints(t *testing.T) {
{
desc: "constraints are present",
spec: &SrlinuxSpec{
Constraints: map[string]string{"cpu": "2", "memory": "4Gi"}},
Constraints: map[string]string{"cpu": "2", "memory": "4Gi"},
},

want: map[string]string{"cpu": "2", "memory": "4Gi"},
},
Expand Down
6 changes: 3 additions & 3 deletions controllers/cfgmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func createVariantsCfgMap(
if err != nil && errors.IsNotFound(err) {
log.Info("creating a new variants configmap")

data, err := VariantsFS.ReadFile("manifests/variants/srl_variants.yml")
data, err := variantsFS.ReadFile("manifests/variants/srl_variants.yml")
if err != nil {
return err
}
Expand Down Expand Up @@ -92,7 +92,7 @@ func createTopomacScriptCfgMap(
if err != nil && errors.IsNotFound(err) {
log.Info("creating a new topomac script configmap")

data, err := VariantsFS.ReadFile("manifests/variants/topomac.yml")
data, err := variantsFS.ReadFile("manifests/variants/topomac.yml")
if err != nil {
return err
}
Expand Down Expand Up @@ -130,7 +130,7 @@ func createKNEEntrypointCfgMap(
if err != nil && errors.IsNotFound(err) {
log.Info("creating a new kne-entrypoint configmap")

data, err := VariantsFS.ReadFile("manifests/variants/kne-entrypoint.yml")
data, err := variantsFS.ReadFile("manifests/variants/kne-entrypoint.yml")
if err != nil {
return err
}
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
5 changes: 2 additions & 3 deletions controllers/srlinux_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,8 @@ const (
srlinuxPodAffinityWeight = 100
)

// VariantsFS is variable without fs assignment, since it is used in main.go
// to assign a value for an fs that is in the outer scope of srlinux_controller.go.
var VariantsFS embed.FS //nolint:gochecknoglobals
//go:embed manifests/variants/*
var variantsFS embed.FS

// SrlinuxReconciler reconciles a Srlinux object.
type SrlinuxReconciler struct {
Expand Down
142 changes: 142 additions & 0 deletions controllers/srlinux_controller_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
Copyright (c) 2021 Nokia. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package controllers

import (
"context"
"time"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
srlinuxv1 "github.com/srl-labs/srl-controller/api/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)

var _ = Describe("Srlinux controller", func() {

// Define utility constants for object names and testing timeouts/durations and intervals.
const (
SrlinuxName = "test-srlinux"
SrlinuxNamespace = "test"

timeout = time.Second * 10
duration = time.Second * 10
interval = time.Millisecond * 250
)

Context("Srlinux controller test", func() {

ctx := context.Background()

namespace := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: SrlinuxNamespace,
},
}

typeNamespaceName := types.NamespacedName{Name: SrlinuxName, Namespace: SrlinuxNamespace}

BeforeEach(func() {
By("Creating the Namespace to perform the tests")
err := k8sClient.Create(ctx, namespace)
Expect(err).To(Not(HaveOccurred()))
})

AfterEach(func() {
By("Deleting the Namespace to perform the tests")
_ = k8sClient.Delete(ctx, namespace)

})

It("should succesfully reconcile a custom resource for Srlinux", func() {
By("Creating the custom resource for the Kind Srlinux")

srlinux := &srlinuxv1.Srlinux{}

err := k8sClient.Get(ctx, typeNamespaceName, srlinux)

if err != nil && errors.IsNotFound(err) {

srlinux := &srlinuxv1.Srlinux{
ObjectMeta: metav1.ObjectMeta{
Name: SrlinuxName,
Namespace: SrlinuxNamespace,
},
TypeMeta: metav1.TypeMeta{
Kind: "Srlinux",
APIVersion: "kne.srlinux.dev/v1",
},
Spec: srlinuxv1.SrlinuxSpec{
Config: &srlinuxv1.NodeConfig{
Image: "srlinux:latest",
},
},
}
// Expect(k8sClient.Create(ctx, srlinux)).Should(Succeed())
err = k8sClient.Create(ctx, srlinux)
Expect(err).To(Not(HaveOccurred()))
}

// srlinuxLookupKey := types.NamespacedName{Name: SrlinuxName, Namespace: SrlinuxNamespace}
// createdSrlinux := &srlinuxv1.Srlinux{}

// // We'll need to retry getting this newly created resource, given that creation may not immediately happen.
// Eventually(func() bool {
// err := k8sClient.Get(ctx, srlinuxLookupKey, createdSrlinux)
// return err == nil
// }, timeout, interval).Should(BeTrue())

// // Let's make sure our Schedule string value was properly converted/handled.
// Expect(createdSrlinux.Spec.Config.Image).Should(Equal("srlinux:latest"))

By("Checking if the custom resource was successfully created")
Eventually(func() error {
found := &srlinuxv1.Srlinux{}
return k8sClient.Get(ctx, typeNamespaceName, found)
}, time.Minute, time.Second).Should(Succeed())

By("Reconciling the custom resource created")
srlinuxReconciler := &SrlinuxReconciler{
Client: k8sClient,
Scheme: k8sClient.Scheme(),
}

_, err = srlinuxReconciler.Reconcile(ctx, reconcile.Request{
NamespacedName: typeNamespaceName,
})
Expect(err).To(Not(HaveOccurred()))
})
})
})
23 changes: 23 additions & 0 deletions controllers/suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package controllers

import (
"context"
"path/filepath"
"testing"

ctrl "sigs.k8s.io/controller-runtime"

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

Expand Down Expand Up @@ -66,6 +69,9 @@ func TestAPIs(t *testing.T) {
var _ = BeforeSuite(func() {
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))

ctx, cancel := context.WithCancel(context.TODO())
defer cancel()

By("bootstrapping test environment")
testEnv = &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "config", "crd", "bases")},
Expand All @@ -86,6 +92,23 @@ var _ = BeforeSuite(func() {
k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme})
Expect(err).NotTo(HaveOccurred())
Expect(k8sClient).NotTo(BeNil())

k8sManager, err := ctrl.NewManager(cfg, ctrl.Options{
Scheme: scheme.Scheme,
})
Expect(err).ToNot(HaveOccurred())

err = (&SrlinuxReconciler{
Client: k8sManager.GetClient(),
Scheme: k8sManager.GetScheme(),
}).SetupWithManager(k8sManager)
Expect(err).ToNot(HaveOccurred())

go func() {
defer GinkgoRecover()
err = k8sManager.Start(ctx)
Expect(err).ToNot(HaveOccurred(), "failed to run manager")
}()
})

var _ = AfterSuite(func() {
Expand Down
7 changes: 0 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
package main

import (
"embed"
"flag"
"os"

Expand All @@ -30,19 +29,13 @@ const ctrlManagerPort = 9443
var (
scheme = runtime.NewScheme() //nolint:gochecknoglobals
setupLog = ctrl.Log.WithName("setup") //nolint:gochecknoglobals

//go:embed manifests/variants/*
variantsFS embed.FS
)

func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))

utilruntime.Must(srlinuxv1.AddToScheme(scheme))
//+kubebuilder:scaffold:scheme

// make manifests available to controllers package
controllers.VariantsFS = variantsFS
}

func main() { //nolint:funlen
Expand Down

0 comments on commit 133ccd5

Please sign in to comment.