Skip to content

Commit f98e5b5

Browse files
authored
test: add unit tests (#305)
* add unit tests * use port 8081
1 parent e618ab8 commit f98e5b5

File tree

5 files changed

+336
-0
lines changed

5 files changed

+336
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package pipelinegates_test
2+
3+
import (
4+
"context"
5+
"os"
6+
"time"
7+
8+
. "github.com/onsi/ginkgo/v2"
9+
. "github.com/onsi/gomega"
10+
console "github.com/pluralsh/console/go/client"
11+
"github.com/pluralsh/deployment-operator/api/v1alpha1"
12+
"github.com/pluralsh/deployment-operator/cmd/agent/args"
13+
"github.com/pluralsh/deployment-operator/pkg/cache"
14+
"github.com/pluralsh/deployment-operator/pkg/controller/pipelinegates"
15+
"github.com/pluralsh/deployment-operator/pkg/test/mocks"
16+
"github.com/stretchr/testify/mock"
17+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
18+
"k8s.io/apimachinery/pkg/types"
19+
)
20+
21+
var _ = Describe("Reconciler", Ordered, func() {
22+
Context("When reconciling a resource", func() {
23+
const (
24+
namespace = "default"
25+
gateId = "1"
26+
pipelinegateName = "test"
27+
)
28+
gateFragment := &console.PipelineGateFragment{
29+
ID: gateId,
30+
Type: console.GateTypeJob,
31+
}
32+
pipelinegate := &v1alpha1.PipelineGate{
33+
ObjectMeta: metav1.ObjectMeta{
34+
Namespace: namespace,
35+
Name: pipelinegateName,
36+
},
37+
Spec: v1alpha1.PipelineGateSpec{
38+
Name: pipelinegateName,
39+
Type: v1alpha1.GateType(console.GateTypeApproval),
40+
},
41+
}
42+
43+
ctx := context.Background()
44+
45+
BeforeEach(func() {
46+
os.Setenv("OPERATOR_NAMESPACE", "default")
47+
})
48+
AfterEach(func() {
49+
os.Unsetenv("OPERATOR_NAMESPACE")
50+
})
51+
52+
It("should create Gate object", func() {
53+
fakeConsoleClient := mocks.NewClientMock(mocks.TestingT)
54+
fakeConsoleClient.On("GetClusterGate", mock.Anything).Return(gateFragment, nil)
55+
fakeConsoleClient.On("ParsePipelineGateCR", mock.Anything, mock.Anything).Return(pipelinegate, nil)
56+
57+
cache.InitGateCache(args.ControllerCacheTTL(), fakeConsoleClient)
58+
59+
reconciler, err := pipelinegates.NewGateReconciler(fakeConsoleClient, kClient, cfg, time.Minute)
60+
Expect(err).NotTo(HaveOccurred())
61+
_, err = reconciler.Reconcile(ctx, gateId)
62+
Expect(err).NotTo(HaveOccurred())
63+
64+
Expect(kClient.Get(ctx, types.NamespacedName{Name: pipelinegateName, Namespace: namespace}, &v1alpha1.PipelineGate{})).NotTo(HaveOccurred())
65+
66+
})
67+
68+
})
69+
})
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
Copyright 2024.
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 pipelinegates_test
18+
19+
import (
20+
"fmt"
21+
"path/filepath"
22+
"runtime"
23+
"testing"
24+
25+
"k8s.io/client-go/rest"
26+
27+
. "github.com/onsi/ginkgo/v2"
28+
. "github.com/onsi/gomega"
29+
"github.com/pluralsh/deployment-operator/api/v1alpha1"
30+
"k8s.io/client-go/kubernetes/scheme"
31+
"sigs.k8s.io/controller-runtime/pkg/client"
32+
"sigs.k8s.io/controller-runtime/pkg/envtest"
33+
logf "sigs.k8s.io/controller-runtime/pkg/log"
34+
"sigs.k8s.io/controller-runtime/pkg/log/zap"
35+
)
36+
37+
// These tests use Ginkgo (BDD-style Go testing framework). Refer to
38+
// http://onsi.github.io/ginkgo/ to learn more about Ginkgo.
39+
var testEnv *envtest.Environment
40+
var kClient client.Client
41+
var cfg *rest.Config
42+
43+
func TestStacks(t *testing.T) {
44+
RegisterFailHandler(Fail)
45+
RunSpecs(t, "Stack Suite")
46+
}
47+
48+
var _ = BeforeSuite(func() {
49+
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))
50+
51+
By("bootstrapping test environment")
52+
testEnv = &envtest.Environment{
53+
CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "config", "crd", "bases")},
54+
ErrorIfCRDPathMissing: true,
55+
BinaryAssetsDirectory: filepath.Join("..", "..", "bin", "k8s", fmt.Sprintf("1.28.3-%s-%s", runtime.GOOS, runtime.GOARCH)),
56+
}
57+
var err error
58+
cfg, err = testEnv.Start()
59+
Expect(err).NotTo(HaveOccurred())
60+
Expect(cfg).NotTo(BeNil())
61+
62+
err = v1alpha1.AddToScheme(scheme.Scheme)
63+
Expect(err).NotTo(HaveOccurred())
64+
65+
kClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme})
66+
Expect(err).NotTo(HaveOccurred())
67+
Expect(kClient).NotTo(BeNil())
68+
})
69+
70+
var _ = AfterSuite(func() {
71+
By("tearing down the test environment")
72+
err := testEnv.Stop()
73+
Expect(err).NotTo(HaveOccurred())
74+
})
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
package service_test
2+
3+
import (
4+
"context"
5+
"log"
6+
"net/http"
7+
"os"
8+
"path/filepath"
9+
"time"
10+
11+
"github.com/gin-gonic/gin"
12+
. "github.com/onsi/ginkgo/v2"
13+
. "github.com/onsi/gomega"
14+
console "github.com/pluralsh/console/go/client"
15+
"github.com/pluralsh/deployment-operator/pkg/controller/service"
16+
"github.com/pluralsh/deployment-operator/pkg/test/mocks"
17+
"github.com/samber/lo"
18+
"github.com/stretchr/testify/mock"
19+
v1 "k8s.io/api/core/v1"
20+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
21+
"k8s.io/apimachinery/pkg/types"
22+
)
23+
24+
var _ = Describe("Reconciler", Ordered, func() {
25+
Context("When reconciling a resource", func() {
26+
const (
27+
namespace = "default"
28+
serviceId = "1"
29+
serviceName = "test"
30+
clusterId = "1"
31+
clusterName = "cluster-test"
32+
operatorNamespace = "plrl-deploy-operator"
33+
)
34+
consoleService := &console.GetServiceDeploymentForAgent_ServiceDeployment{
35+
ID: serviceId,
36+
Name: serviceName,
37+
Namespace: namespace,
38+
Tarball: lo.ToPtr("http://localhost:8081/ext/v1/digests"),
39+
Configuration: []*console.GetServiceDeploymentForAgent_ServiceDeployment_Configuration{
40+
{
41+
Name: "name",
42+
Value: serviceName,
43+
},
44+
},
45+
Cluster: &console.GetServiceDeploymentForAgent_ServiceDeployment_Cluster{
46+
ID: clusterId,
47+
Name: clusterName,
48+
},
49+
Revision: &console.GetServiceDeploymentForAgent_ServiceDeployment_Revision{
50+
ID: serviceId,
51+
},
52+
}
53+
ctx := context.Background()
54+
tarPath := filepath.Join("..", "..", "..", "test", "tarball", "test.tar.gz")
55+
56+
r := gin.Default()
57+
r.GET("/ext/v1/digests", func(c *gin.Context) {
58+
res, err := os.ReadFile(tarPath)
59+
Expect(err).NotTo(HaveOccurred())
60+
c.String(http.StatusOK, string(res))
61+
})
62+
63+
srv := &http.Server{
64+
Addr: ":8081",
65+
Handler: r,
66+
}
67+
dir := ""
68+
BeforeEach(func() {
69+
var err error
70+
dir, err = os.MkdirTemp("", "test")
71+
Expect(err).NotTo(HaveOccurred())
72+
Expect(kClient.Create(ctx, &v1.Namespace{
73+
ObjectMeta: metav1.ObjectMeta{
74+
Name: operatorNamespace,
75+
},
76+
})).NotTo(HaveOccurred())
77+
// Initializing the server in a goroutine so that
78+
// it won't block the graceful shutdown handling below
79+
go func() {
80+
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
81+
Expect(err).NotTo(HaveOccurred())
82+
}
83+
}()
84+
})
85+
AfterEach(func() {
86+
os.RemoveAll(dir)
87+
Expect(kClient.Delete(ctx, &v1.Namespace{
88+
ObjectMeta: metav1.ObjectMeta{
89+
Name: operatorNamespace,
90+
},
91+
})).NotTo(HaveOccurred())
92+
// The context is used to inform the server it has 5 seconds to finish
93+
// the request it is currently handling
94+
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
95+
defer cancel()
96+
if err := srv.Shutdown(ctx); err != nil {
97+
log.Fatal("Server forced to shutdown: ", err)
98+
}
99+
100+
log.Println("Server exiting")
101+
})
102+
103+
It("should create NewServiceReconciler and apply service", func() {
104+
fakeConsoleClient := mocks.NewClientMock(mocks.TestingT)
105+
fakeConsoleClient.On("GetCredentials").Return("", "")
106+
fakeConsoleClient.On("GetService", mock.Anything).Return(consoleService, nil)
107+
fakeConsoleClient.On("UpdateComponents", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
108+
109+
reconciler, err := service.NewServiceReconciler(fakeConsoleClient, cfg, time.Minute, time.Minute, namespace, "http://localhost:8080")
110+
Expect(err).NotTo(HaveOccurred())
111+
_, err = reconciler.Reconcile(ctx, serviceId)
112+
Expect(err).NotTo(HaveOccurred())
113+
114+
Expect(kClient.Get(ctx, types.NamespacedName{Name: serviceName, Namespace: namespace}, &v1.Pod{})).NotTo(HaveOccurred())
115+
})
116+
117+
})
118+
})
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
Copyright 2024.
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 service_test
18+
19+
import (
20+
"fmt"
21+
"path/filepath"
22+
"runtime"
23+
"testing"
24+
25+
"k8s.io/client-go/rest"
26+
27+
velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
28+
29+
. "github.com/onsi/ginkgo/v2"
30+
. "github.com/onsi/gomega"
31+
"k8s.io/client-go/kubernetes/scheme"
32+
"sigs.k8s.io/controller-runtime/pkg/client"
33+
"sigs.k8s.io/controller-runtime/pkg/envtest"
34+
logf "sigs.k8s.io/controller-runtime/pkg/log"
35+
"sigs.k8s.io/controller-runtime/pkg/log/zap"
36+
)
37+
38+
// These tests use Ginkgo (BDD-style Go testing framework). Refer to
39+
// http://onsi.github.io/ginkgo/ to learn more about Ginkgo.
40+
var testEnv *envtest.Environment
41+
var kClient client.Client
42+
var cfg *rest.Config
43+
44+
func TestStacks(t *testing.T) {
45+
RegisterFailHandler(Fail)
46+
RunSpecs(t, "Stack Suite")
47+
}
48+
49+
var _ = BeforeSuite(func() {
50+
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))
51+
52+
By("bootstrapping test environment")
53+
testEnv = &envtest.Environment{
54+
CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "test", "crd")},
55+
ErrorIfCRDPathMissing: true,
56+
BinaryAssetsDirectory: filepath.Join("..", "..", "bin", "k8s", fmt.Sprintf("1.28.3-%s-%s", runtime.GOOS, runtime.GOARCH)),
57+
}
58+
var err error
59+
cfg, err = testEnv.Start()
60+
Expect(err).NotTo(HaveOccurred())
61+
Expect(cfg).NotTo(BeNil())
62+
63+
err = velerov1.AddToScheme(scheme.Scheme)
64+
Expect(err).NotTo(HaveOccurred())
65+
66+
kClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme})
67+
Expect(err).NotTo(HaveOccurred())
68+
Expect(kClient).NotTo(BeNil())
69+
})
70+
71+
var _ = AfterSuite(func() {
72+
By("tearing down the test environment")
73+
err := testEnv.Stop()
74+
Expect(err).NotTo(HaveOccurred())
75+
})

test/tarball/test.tar.gz

244 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)