Skip to content
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
66 changes: 66 additions & 0 deletions pkg/controllers/v1alpha1/efc/efcruntime_controller_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
Copyright 2026 The Fluid Authors.

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 efc

import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"

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

datav1alpha1 "github.com/fluid-cloudnative/fluid/api/v1alpha1"
"github.com/fluid-cloudnative/fluid/pkg/utils/fake"
)

var _ = Describe("RuntimeReconciler (EFC)", func() {

Describe("ControllerName", func() {
It("should return the constant controller name", func() {
r := &RuntimeReconciler{}
Expect(r.ControllerName()).To(Equal("EFCRuntimeController"))
})
})

Describe("ManagedResource", func() {
It("should return an EFCRuntime with correct TypeMeta", func() {
r := &RuntimeReconciler{}
obj := r.ManagedResource()
efcRuntime, ok := obj.(*datav1alpha1.EFCRuntime)
Expect(ok).To(BeTrue())
Expect(efcRuntime.Kind).To(Equal(datav1alpha1.EFCRuntimeKind))
Expect(efcRuntime.APIVersion).To(ContainSubstring(datav1alpha1.GroupVersion.Group))
})
})

Describe("NewRuntimeReconciler", func() {
It("should initialize reconciler with all required fields set", func() {
s := runtime.NewScheme()
fakeClient := fake.NewFakeClientWithScheme(s)
log := ctrl.Log.WithName("test")
recorder := record.NewFakeRecorder(10)

r := NewRuntimeReconciler(fakeClient, log, s, recorder)
Expect(r).NotTo(BeNil())
Expect(r.Scheme).To(Equal(s))
Expect(r.mutex).NotTo(BeNil())
Expect(r.engines).NotTo(BeNil())
Expect(r.RuntimeReconciler).NotTo(BeNil())
})
})
})
211 changes: 211 additions & 0 deletions pkg/controllers/v1alpha1/efc/implement_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
/*
Copyright 2026 The Fluid Authors.

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 efc

import (
"context"
"fmt"
"sync"

"github.com/agiledragon/gomonkey/v2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"

datav1alpha1 "github.com/fluid-cloudnative/fluid/api/v1alpha1"
"github.com/fluid-cloudnative/fluid/pkg/controllers"
"github.com/fluid-cloudnative/fluid/pkg/dataoperation"
"github.com/fluid-cloudnative/fluid/pkg/ddc"
"github.com/fluid-cloudnative/fluid/pkg/ddc/base"
cruntime "github.com/fluid-cloudnative/fluid/pkg/runtime"
"github.com/fluid-cloudnative/fluid/pkg/utils/fake"
)

// mockEngine is a minimal no-op implementation of base.Engine used in tests only.
type mockEngine struct{}

func (m *mockEngine) ID() string { return "mock" }
func (m *mockEngine) Shutdown() error { return nil }
func (m *mockEngine) Setup(_ cruntime.ReconcileRequestContext) (bool, error) { return true, nil }
func (m *mockEngine) CreateVolume() error { return nil }
func (m *mockEngine) DeleteVolume() error { return nil }
func (m *mockEngine) Sync(_ cruntime.ReconcileRequestContext) error { return nil }
func (m *mockEngine) Validate(_ cruntime.ReconcileRequestContext) error { return nil }
func (m *mockEngine) Operate(_ cruntime.ReconcileRequestContext, _ *datav1alpha1.OperationStatus, _ dataoperation.OperationInterface) (ctrl.Result, error) {
return ctrl.Result{}, nil
}

// newTestEFCReconciler builds a RuntimeReconciler seeded with the
// given scheme and runtime objects. Pass nil scheme to get a default one.
func newTestEFCReconciler(s *runtime.Scheme, objs ...runtime.Object) *RuntimeReconciler {
if s == nil {
s = runtime.NewScheme()
_ = datav1alpha1.AddToScheme(s)
}
fakeClient := fake.NewFakeClientWithScheme(s, objs...)
log := ctrl.Log.WithName("efc-test")
recorder := record.NewFakeRecorder(10)
r := &RuntimeReconciler{
Scheme: s,
mutex: &sync.Mutex{},
engines: map[string]base.Engine{},
}
r.RuntimeReconciler = controllers.NewRuntimeReconciler(r, fakeClient, log, recorder)
return r
}

var _ = Describe("RuntimeReconciler (EFC) Implement", func() {

Describe("getRuntime", func() {
var r *RuntimeReconciler

BeforeEach(func() {
testRuntime := &datav1alpha1.EFCRuntime{
ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "default"},
}
s := runtime.NewScheme()
_ = datav1alpha1.AddToScheme(s)
r = newTestEFCReconciler(s, testRuntime)
})

It("should return the runtime when it exists in the cluster", func() {
ctx := cruntime.ReconcileRequestContext{
Context: context.Background(),
NamespacedName: types.NamespacedName{Name: "test", Namespace: "default"},
}
result, err := r.getRuntime(ctx)
Expect(err).NotTo(HaveOccurred())
Expect(result).NotTo(BeNil())
Expect(result.Name).To(Equal("test"))
Expect(result.Namespace).To(Equal("default"))
})

It("should return an error when the runtime does not exist", func() {
ctx := cruntime.ReconcileRequestContext{
Context: context.Background(),
NamespacedName: types.NamespacedName{Name: "nonexistent", Namespace: "default"},
}
result, err := r.getRuntime(ctx)
Expect(err).To(HaveOccurred())
Expect(result).To(BeNil())
})
})

Describe("GetOrCreateEngine", func() {
var r *RuntimeReconciler

BeforeEach(func() {
r = newTestEFCReconciler(nil)
})

It("should propagate engine creation errors", func() {
patches := gomonkey.ApplyFunc(ddc.CreateEngine,
func(_ string, _ cruntime.ReconcileRequestContext) (base.Engine, error) {
return nil, fmt.Errorf("engine creation failed")
})
defer patches.Reset()

ctx := cruntime.ReconcileRequestContext{
Context: context.Background(),
NamespacedName: types.NamespacedName{Name: "fail", Namespace: "default"},
}
engine, err := r.GetOrCreateEngine(ctx)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("engine creation failed"))
Expect(engine).To(BeNil())
})

It("should create engine on first call and return cached engine on second call", func() {
mock := &mockEngine{}
callCount := 0
patches := gomonkey.ApplyFunc(ddc.CreateEngine,
func(_ string, _ cruntime.ReconcileRequestContext) (base.Engine, error) {
callCount++
return mock, nil
})
defer patches.Reset()

ctx := cruntime.ReconcileRequestContext{
Context: context.Background(),
NamespacedName: types.NamespacedName{Name: "cached", Namespace: "default"},
}

// First call: engine is created and stored.
engine1, err := r.GetOrCreateEngine(ctx)
Expect(err).NotTo(HaveOccurred())
Expect(engine1).To(Equal(base.Engine(mock)))
Expect(callCount).To(Equal(1))

// Second call: engine should be retrieved from the cache without re-creation.
engine2, err := r.GetOrCreateEngine(ctx)
Expect(err).NotTo(HaveOccurred())
Expect(engine2).To(Equal(base.Engine(mock)))
Expect(callCount).To(Equal(1), "CreateEngine must not be called a second time")
})
})

Describe("RemoveEngine", func() {
var r *RuntimeReconciler

BeforeEach(func() {
r = newTestEFCReconciler(nil)
})

It("should remove a cached engine by namespaced name", func() {
id := ddc.GenerateEngineID(types.NamespacedName{Name: "test", Namespace: "default"})
r.engines[id] = &mockEngine{}

ctx := cruntime.ReconcileRequestContext{
Context: context.Background(),
NamespacedName: types.NamespacedName{Name: "test", Namespace: "default"},
}
r.RemoveEngine(ctx)

_, found := r.engines[id]
Expect(found).To(BeFalse())
})

It("should not panic when removing a non-existent engine", func() {
ctx := cruntime.ReconcileRequestContext{
Context: context.Background(),
NamespacedName: types.NamespacedName{Name: "ghost", Namespace: "default"},
}
Expect(func() { r.RemoveEngine(ctx) }).NotTo(Panic())
})
})

Describe("Reconcile", func() {
It("should return no error when the runtime is not found", func() {
// The fake client has no EFCRuntime objects, so getRuntime will
// return a NotFound error, which Reconcile should swallow gracefully.
s := runtime.NewScheme()
_ = datav1alpha1.AddToScheme(s)
r := newTestEFCReconciler(s)

req := ctrl.Request{
NamespacedName: types.NamespacedName{Name: "missing", Namespace: "default"},
}
result, err := r.Reconcile(context.Background(), req)
Expect(err).NotTo(HaveOccurred())
Expect(result).To(Equal(ctrl.Result{}))
})
})
})
50 changes: 5 additions & 45 deletions pkg/controllers/v1alpha1/efc/suite_test.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2023 The Fluid Authors.
Copyright 2026 The Fluid Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand All @@ -17,63 +17,23 @@ limitations under the License.
package efc

import (
"path/filepath"
"testing"

. "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"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/log/zap"

datav1alpha1 "github.com/fluid-cloudnative/fluid/api/v1alpha1"
// +kubebuilder:scaffold:imports
"github.com/fluid-cloudnative/fluid/pkg/utils/fake"
)

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

var cfg *rest.Config
var k8sClient client.Client
var testEnv *envtest.Environment

func TestAPIs(t *testing.T) {
RegisterFailHandler(Fail)

RunSpecs(t,
"Controller Suite")
RunSpecs(t, "EFC Controller Suite")
}

var _ = BeforeSuite(func(done Done) {
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))

By("bootstrapping test environment")
testEnv = &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "config", "crd", "bases")},
}

var err error
cfg, err = testEnv.Start()
Expect(err).ToNot(HaveOccurred())
Expect(cfg).ToNot(BeNil())

err = datav1alpha1.AddToScheme(scheme.Scheme)
Expect(err).NotTo(HaveOccurred())

// +kubebuilder:scaffold:scheme

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

close(done)
}, 60)

var _ = AfterSuite(func() {
By("tearing down the test environment")
err := testEnv.Stop()
Expect(err).ToNot(HaveOccurred())
var _ = BeforeSuite(func() {
logf.SetLogger(fake.NullLogger())
})
Loading