Skip to content

Commit 9d40f9e

Browse files
committed
Bootstrap controller tests and add basic test cases
Bootstrap test files for DevWorkspace controller and add a basic DevWorkspace creation test. Signed-off-by: Angel Misevski <[email protected]>
1 parent 047d66e commit 9d40f9e

File tree

4 files changed

+410
-0
lines changed

4 files changed

+410
-0
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
// Copyright (c) 2019-2022 Red Hat, Inc.
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
package controllers_test
15+
16+
import (
17+
"os"
18+
"path/filepath"
19+
"time"
20+
21+
dw "github.com/devfile/api/v2/pkg/apis/workspaces/v1alpha2"
22+
"github.com/devfile/devworkspace-operator/pkg/conditions"
23+
. "github.com/onsi/ginkgo/v2"
24+
. "github.com/onsi/gomega"
25+
corev1 "k8s.io/api/core/v1"
26+
"k8s.io/apimachinery/pkg/types"
27+
"sigs.k8s.io/controller-runtime/pkg/client"
28+
"sigs.k8s.io/yaml"
29+
)
30+
31+
func loadObjectFromFile(objName string, obj client.Object, filename string) error {
32+
path := filepath.Join("testdata", filename)
33+
bytes, err := os.ReadFile(path)
34+
if err != nil {
35+
return err
36+
}
37+
err = yaml.Unmarshal(bytes, obj)
38+
if err != nil {
39+
return err
40+
}
41+
obj.SetNamespace(testNamespace)
42+
obj.SetName(objName)
43+
44+
return nil
45+
}
46+
47+
var _ = Describe("DevWorkspace Controller", func() {
48+
const (
49+
timeout = 10 * time.Second
50+
interval = 250 * time.Millisecond
51+
)
52+
53+
Context("Basic DevWorkspace Tests", func() {
54+
It("Sets DevWorkspace ID and Starting status", func() {
55+
By("Reading DevWorkspace from testdata file")
56+
devworkspace := &dw.DevWorkspace{}
57+
err := loadObjectFromFile(devWorkspaceName, devworkspace, "test-devworkspace.yaml")
58+
Expect(err).NotTo(HaveOccurred())
59+
60+
By("Creating a new DevWorkspace")
61+
Expect(k8sClient.Create(ctx, devworkspace)).Should(Succeed())
62+
dwNamespacedName := types.NamespacedName{
63+
Namespace: testNamespace,
64+
Name: devWorkspaceName,
65+
}
66+
defer deleteDevWorkspace(devWorkspaceName)
67+
68+
createdDW := &dw.DevWorkspace{}
69+
Eventually(func() bool {
70+
err := k8sClient.Get(ctx, dwNamespacedName, createdDW)
71+
return err == nil
72+
}, timeout, interval).Should(BeTrue(), "DevWorkspace should exist in cluster")
73+
74+
By("Checking DevWorkspace ID has been set")
75+
Eventually(func() (devworkspaceID string, err error) {
76+
if err := k8sClient.Get(ctx, dwNamespacedName, createdDW); err != nil {
77+
return "", err
78+
}
79+
return createdDW.Status.DevWorkspaceId, nil
80+
}, timeout, interval).Should(Not(Equal("")), "Should set DevWorkspace ID after creation")
81+
82+
By("Checking DevWorkspace Status is updated to starting")
83+
Eventually(func() (phase dw.DevWorkspacePhase, err error) {
84+
if err := k8sClient.Get(ctx, dwNamespacedName, createdDW); err != nil {
85+
return "", err
86+
}
87+
return createdDW.Status.Phase, nil
88+
}, timeout, interval).Should(Equal(dw.DevWorkspaceStatusStarting), "DevWorkspace should have Starting phase")
89+
Expect(createdDW.Status.Message).ShouldNot(BeEmpty(), "Status message should be set for starting workspaces")
90+
startingCondition := conditions.GetConditionByType(createdDW.Status.Conditions, conditions.Started)
91+
Expect(startingCondition).ShouldNot(BeNil(), "Should have 'Starting' condition")
92+
Expect(startingCondition.Status).Should(Equal(corev1.ConditionTrue), "Starting condition should be 'true'")
93+
})
94+
95+
})
96+
})
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
// Copyright (c) 2019-2022 Red Hat, Inc.
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
package controllers_test
15+
16+
import (
17+
"context"
18+
"fmt"
19+
"os"
20+
"path/filepath"
21+
"testing"
22+
23+
dwv1 "github.com/devfile/api/v2/pkg/apis/workspaces/v1alpha1"
24+
dwv2 "github.com/devfile/api/v2/pkg/apis/workspaces/v1alpha2"
25+
controllerv1alpha1 "github.com/devfile/devworkspace-operator/apis/controller/v1alpha1"
26+
appsv1 "k8s.io/api/apps/v1"
27+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
28+
"sigs.k8s.io/yaml"
29+
30+
workspacecontroller "github.com/devfile/devworkspace-operator/controllers/workspace"
31+
"github.com/devfile/devworkspace-operator/pkg/cache"
32+
"github.com/devfile/devworkspace-operator/pkg/config"
33+
"github.com/devfile/devworkspace-operator/pkg/infrastructure"
34+
. "github.com/onsi/ginkgo/v2"
35+
. "github.com/onsi/gomega"
36+
corev1 "k8s.io/api/core/v1"
37+
"k8s.io/client-go/kubernetes/scheme"
38+
"k8s.io/client-go/rest"
39+
ctrl "sigs.k8s.io/controller-runtime"
40+
"sigs.k8s.io/controller-runtime/pkg/client"
41+
"sigs.k8s.io/controller-runtime/pkg/envtest"
42+
logf "sigs.k8s.io/controller-runtime/pkg/log"
43+
"sigs.k8s.io/controller-runtime/pkg/log/zap"
44+
)
45+
46+
const (
47+
testNamespace = "devworkspace-test"
48+
devWorkspaceName = "test-devworkspace"
49+
)
50+
51+
var (
52+
cfg *rest.Config
53+
k8sClient client.Client
54+
testEnv *envtest.Environment
55+
ctx context.Context
56+
cancel context.CancelFunc
57+
testControllerCfg = &controllerv1alpha1.OperatorConfiguration{
58+
Routing: &controllerv1alpha1.RoutingConfig{
59+
ClusterHostSuffix: "test-environment-cluster-suffix",
60+
},
61+
}
62+
)
63+
64+
func TestAPIs(t *testing.T) {
65+
// if os.Getenv("TEST_CONTROLLER") != "true" {
66+
// t.Skip()
67+
// }
68+
69+
RegisterFailHandler(Fail)
70+
71+
RunSpecs(t, "Controller Suite")
72+
}
73+
74+
var _ = BeforeSuite(func() {
75+
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))
76+
77+
ctx, cancel = context.WithCancel(context.TODO())
78+
79+
By("setting up controller environment")
80+
Expect(setupEnvVars()).To(Succeed())
81+
82+
By("bootstrapping test environment")
83+
testEnv = &envtest.Environment{
84+
CRDDirectoryPaths: []string{filepath.Join("..", "..", "deploy", "templates", "crd", "bases")},
85+
ErrorIfCRDPathMissing: true,
86+
}
87+
88+
cfg, err := testEnv.Start()
89+
Expect(err).NotTo(HaveOccurred())
90+
Expect(cfg).NotTo(BeNil())
91+
92+
infrastructure.InitializeForTesting(infrastructure.Kubernetes)
93+
94+
err = controllerv1alpha1.AddToScheme(scheme.Scheme)
95+
Expect(err).NotTo(HaveOccurred())
96+
err = dwv1.AddToScheme(scheme.Scheme)
97+
Expect(err).NotTo(HaveOccurred())
98+
err = dwv2.AddToScheme(scheme.Scheme)
99+
Expect(err).NotTo(HaveOccurred())
100+
101+
k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme})
102+
Expect(err).NotTo(HaveOccurred())
103+
Expect(k8sClient).NotTo(BeNil())
104+
105+
// Replicate controller setup similarly to how we do for main.go
106+
cacheFunc, err := cache.GetCacheFunc()
107+
Expect(err).NotTo(HaveOccurred())
108+
109+
mgr, err := ctrl.NewManager(cfg, ctrl.Options{
110+
Scheme: scheme.Scheme,
111+
Port: 9443,
112+
NewCache: cacheFunc,
113+
})
114+
Expect(err).NotTo(HaveOccurred())
115+
// Use default config
116+
config.SetConfigForTesting(testControllerCfg)
117+
118+
nonCachingClient, err := client.New(mgr.GetConfig(), client.Options{Scheme: scheme.Scheme})
119+
Expect(err).NotTo(HaveOccurred())
120+
121+
err = mgr.GetFieldIndexer().IndexField(context.Background(), &corev1.Event{}, "involvedObject.name", func(obj client.Object) []string {
122+
ev := obj.(*corev1.Event)
123+
return []string{ev.InvolvedObject.Name}
124+
})
125+
Expect(err).NotTo(HaveOccurred())
126+
127+
// Don't set up DevWorkspaceRouting Reconciler so that we can manage routings
128+
129+
err = (&workspacecontroller.DevWorkspaceReconciler{
130+
Client: mgr.GetClient(),
131+
NonCachingClient: nonCachingClient,
132+
Log: ctrl.Log.WithName("controllers").WithName("DevWorkspace"),
133+
Scheme: mgr.GetScheme(),
134+
}).SetupWithManager(mgr)
135+
Expect(err).NotTo(HaveOccurred())
136+
137+
// Skip trying to set up / test webhooks for now
138+
139+
By("Creating Namespace for the DevWorkspace")
140+
ns := &corev1.Namespace{
141+
ObjectMeta: metav1.ObjectMeta{
142+
Name: testNamespace,
143+
},
144+
}
145+
Expect(k8sClient.Create(ctx, ns)).Should(Succeed())
146+
147+
go func() {
148+
defer GinkgoRecover()
149+
err = mgr.Start(ctx)
150+
Expect(err).ToNot(HaveOccurred(), "failed to run manager")
151+
}()
152+
})
153+
154+
var _ = AfterSuite(func() {
155+
cancel()
156+
By("tearing down the test environment")
157+
err := testEnv.Stop()
158+
Expect(err).NotTo(HaveOccurred())
159+
})
160+
161+
func setupEnvVars() error {
162+
bytes, err := os.ReadFile(filepath.Join("..", "..", "deploy", "templates", "components", "manager", "manager.yaml"))
163+
if err != nil {
164+
return err
165+
}
166+
deploy := &appsv1.Deployment{}
167+
if err := yaml.Unmarshal(bytes, deploy); err != nil {
168+
return err
169+
}
170+
171+
var dwContainer *corev1.Container
172+
for _, container := range deploy.Spec.Template.Spec.Containers {
173+
if container.Name == "devworkspace-controller" {
174+
dwContainer = &container
175+
break
176+
}
177+
}
178+
if dwContainer == nil {
179+
return fmt.Errorf("could not read devworkspace-controller container from manager.yaml")
180+
}
181+
182+
for _, envvar := range dwContainer.Env {
183+
if err := os.Setenv(envvar.Name, envvar.Value); err != nil {
184+
return err
185+
}
186+
}
187+
188+
return nil
189+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
kind: DevWorkspace
2+
apiVersion: workspace.devfile.io/v1alpha2
3+
metadata:
4+
labels:
5+
controller.devfile.io/creator: ""
6+
spec:
7+
started: true
8+
routingClass: 'basic'
9+
template:
10+
projects:
11+
- name: web-nodejs-sample
12+
git:
13+
remotes:
14+
origin: "https://github.com/che-samples/web-nodejs-sample.git"
15+
components:
16+
- name: web-terminal
17+
container:
18+
image: quay.io/wto/web-terminal-tooling:latest
19+
memoryLimit: 512Mi
20+
mountSources: true
21+
command:
22+
- "tail"
23+
- "-f"
24+
- "/dev/null"

0 commit comments

Comments
 (0)