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

Migrate unit tests to use gomock. #203

Closed
Closed
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
106 changes: 3 additions & 103 deletions controllers/controllers_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,48 +15,22 @@
package controllers

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

druidv1alpha1 "github.com/gardener/etcd-druid/api/v1alpha1"
controllersconfig "github.com/gardener/etcd-druid/controllers/config"

"github.com/gardener/gardener/pkg/utils/test"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/envtest"
"sigs.k8s.io/controller-runtime/pkg/envtest/printer"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
// +kubebuilder:scaffold:imports
)

// These tests use Ginkgo (BDD-style Go testing framework). Refer to
// http://onsi.github.io/ginkgo/ to learn more about Ginkgo.

var (
mgrCtx context.Context
mgrCancel context.CancelFunc
cfg *rest.Config
k8sClient client.Client
testEnv *envtest.Environment
mgr manager.Manager
mgrStopped *sync.WaitGroup

revertFns []func()

testLog = ctrl.Log.WithName("test")
)

func TestAPIs(t *testing.T) {
Expand All @@ -67,92 +41,18 @@ func TestAPIs(t *testing.T) {
[]Reporter{printer.NewlineReporter{}})
}

var _ = BeforeSuite(func(done Done) {
mgrCtx, mgrCancel = context.WithCancel(context.Background())
var err error
//logf.SetLogger(zap.LoggerTo(GinkgoWriter, true))
ctrl.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))
By("bootstrapping test environment")
testEnv = &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "config", "crd", "bases")},
}

testLog.Info("Starting tests")
cfg, err = testEnv.Start()
Expect(err).ToNot(HaveOccurred())
Expect(cfg).ToNot(BeNil())

err = druidv1alpha1.AddToScheme(scheme.Scheme)
Expect(err).NotTo(HaveOccurred())
var _ = BeforeSuite(func() {
Expect(druidv1alpha1.AddToScheme(scheme.Scheme)).To(Succeed())

// +kubebuilder:scaffold:scheme

k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme})
Expect(err).ToNot(HaveOccurred())
Expect(k8sClient).ToNot(BeNil())

revertFns = []func(){
test.WithVar(&DefaultTimeout, 20*time.Second),
WithWd(".."),
}

Expect(cfg).ToNot(BeNil())
mgr, err = manager.New(cfg, manager.Options{
MetricsBindAddress: "0",
ClientDisableCacheFor: UncachedObjectList,
})
Expect(err).NotTo(HaveOccurred())

Expect(err).NotTo(HaveOccurred())
er, err := NewEtcdReconcilerWithImageVector(mgr, false)
Expect(err).NotTo(HaveOccurred())

err = er.SetupWithManager(mgr, 1, true)
Expect(err).NotTo(HaveOccurred())

custodian := NewEtcdCustodian(mgr, controllersconfig.EtcdCustodianController{
EtcdMember: controllersconfig.EtcdMemberConfig{
EtcdMemberNotReadyThreshold: 1 * time.Minute,
},
})

err = custodian.SetupWithManager(mgrCtx, mgr, 1)
Expect(err).NotTo(HaveOccurred())

mgrStopped = startTestManager(mgrCtx, mgr)

close(done)
}, 60)
})

var _ = AfterSuite(func() {
mgrCancel()
mgrStopped.Wait()
Expect(testEnv.Stop()).To(Succeed())
for _, f := range revertFns {
f()
}
})

func startTestManager(ctx context.Context, mgr manager.Manager) *sync.WaitGroup {
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
Expect(mgr.Start(ctx)).NotTo(HaveOccurred())
wg.Done()
}()
syncCtx, syncCancel := context.WithTimeout(ctx, 1*time.Minute)
defer syncCancel()
mgr.GetCache().WaitForCacheSync(syncCtx)
return wg
}

func SetupWithManager(mgr ctrl.Manager, r reconcile.Reconciler) error {
return ctrl.NewControllerManagedBy(mgr).WithOptions(controller.Options{
MaxConcurrentReconciles: 10,
}).
For(&druidv1alpha1.Etcd{}).
Owns(&corev1.ConfigMap{}).
Owns(&corev1.Service{}).
Owns(&appsv1.StatefulSet{}).
Complete(r)
}
54 changes: 43 additions & 11 deletions controllers/etcd_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,15 @@ const (
FinalizerName = "druid.gardener.cloud/etcd-druid"
// DefaultImageVector is a constant for the path to the default image vector file.
DefaultImageVector = "images.yaml"
// DefaultInterval is the default interval for retry operations.
DefaultInterval = 5 * time.Second
// EtcdReady implies that etcd is ready
EtcdReady = true
// DefaultAutoCompactionRetention defines the default auto-compaction-retention length for etcd.
DefaultAutoCompactionRetention = "30m"
)

var (
// DefaultInterval is the default interval for retry operations.
DefaultInterval = 5 * time.Second
// DefaultTimeout is the default timeout for retry operations.
DefaultTimeout = 1 * time.Minute
)
Expand All @@ -115,13 +115,15 @@ func NewReconcilerWithImageVector(mgr manager.Manager) (*EtcdReconciler, error)

// NewEtcdReconciler creates a new EtcdReconciler object
func NewEtcdReconciler(mgr manager.Manager, enableBackupCompactionJobTempFS bool) (*EtcdReconciler, error) {
return (&EtcdReconciler{
Client: mgr.GetClient(),
Config: mgr.GetConfig(),
Scheme: mgr.GetScheme(),
logger: log.Log.WithName("etcd-controller"),
enableBackupCompactionJobTempFS: enableBackupCompactionJobTempFS,
}).InitializeControllerWithChartApplier()
return NewEtcdReconcilerWithAllFields(
mgr.GetClient(),
mgr.GetScheme(),
nil,
mgr.GetConfig(),
enableBackupCompactionJobTempFS,
nil,
log.Log.WithName("etcd-controller"),
).InitializeControllerWithChartApplier()
}

// NewEtcdReconcilerWithImageVector creates a new EtcdReconciler object
Expand All @@ -133,6 +135,28 @@ func NewEtcdReconcilerWithImageVector(mgr manager.Manager, enableBackupCompactio
return ec.InitializeControllerWithImageVector()
}

// NewEtcdReconcilerWithAllFields creates a new EtcdReconciler object.
// It must be directly used only for testing purposes.
func NewEtcdReconcilerWithAllFields(
c client.Client,
sch *runtime.Scheme,
chartApplier kubernetes.ChartApplier,
config *rest.Config,
enableBackupCompactionJobTempFS bool,
iv imagevector.ImageVector,
logger logr.Logger,
) *EtcdReconciler {
return &EtcdReconciler{
Client: c,
Scheme: sch,
chartApplier: chartApplier,
Config: config,
enableBackupCompactionJobTempFS: enableBackupCompactionJobTempFS,
ImageVector: iv,
logger: logger,
}
}

func getChartPath() string {
return filepath.Join("charts", "etcd")
}
Expand Down Expand Up @@ -1172,8 +1196,8 @@ func (r *EtcdReconciler) getMapFromEtcd(etcd *druidv1alpha1.Etcd) (map[string]in
"sharedConfig": sharedConfigValues,
"replicas": etcd.Spec.Replicas,
"statefulsetReplicas": statefulsetReplicas,
"serviceName": fmt.Sprintf("%s-client", etcd.Name),
"configMapName": fmt.Sprintf("etcd-bootstrap-%s", string(etcd.UID[:6])),
"serviceName": getServiceNameFor(etcd),
"configMapName": getConfigMapNameFor(etcd),
"cronJobName": getCronJobName(etcd),
"volumeClaimTemplateName": volumeClaimTemplateName,
}
Expand Down Expand Up @@ -1218,6 +1242,14 @@ func (r *EtcdReconciler) getMapFromEtcd(etcd *druidv1alpha1.Etcd) (map[string]in
return values, nil
}

func getServiceNameFor(etcd *druidv1alpha1.Etcd) string {
return fmt.Sprintf("%s-client", etcd.Name)
}

func getConfigMapNameFor(etcd *druidv1alpha1.Etcd) string {
return fmt.Sprintf("etcd-bootstrap-%s", string(etcd.UID[:6]))
}

func (r *EtcdReconciler) addFinalizersToDependantSecrets(ctx context.Context, logger logr.Logger, etcd *druidv1alpha1.Etcd) error {
secrets := []*corev1.SecretReference{}
if etcd.Spec.Etcd.TLS != nil {
Expand Down
Loading