-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain_internal_test.go
255 lines (210 loc) · 7.52 KB
/
main_internal_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package main
import (
"context"
"flag"
"fmt"
"github.com/cloudogu/k8s-dogu-operator/v3/api/ecoSystem"
"os"
"sigs.k8s.io/controller-runtime/pkg/controller"
"testing"
"github.com/stretchr/testify/assert"
v2 "github.com/cloudogu/k8s-dogu-operator/v3/api/v2"
"github.com/cloudogu/k8s-dogu-operator/v3/controllers"
"github.com/cloudogu/k8s-dogu-operator/v3/controllers/config"
"github.com/go-logr/logr"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
runtimeconf "sigs.k8s.io/controller-runtime/pkg/config"
"sigs.k8s.io/controller-runtime/pkg/manager"
)
type mockDefinition struct {
Arguments []interface{}
ReturnValue interface{}
}
func getCopyMap(definitions map[string]mockDefinition) map[string]mockDefinition {
newCopyMap := map[string]mockDefinition{}
for k, v := range definitions {
newCopyMap[k] = v
}
return newCopyMap
}
func getNewMockManager(expectedErrorOnNewManager error, definitions map[string]mockDefinition) manager.Manager {
k8sManager := &MockControllerManager{}
ctrl.NewManager = func(config *rest.Config, options manager.Options) (manager.Manager, error) {
for key, value := range definitions {
k8sManager.On(key, value.Arguments...).Return(value.ReturnValue)
}
return k8sManager, expectedErrorOnNewManager
}
ctrl.SetLogger = func(l logr.Logger) {
k8sManager.Mock.On("GetLogger").Return(l)
}
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
return k8sManager
}
func Test_noSpamKey(t *testing.T) {
t.Run("should not return the same key", func(t *testing.T) {
// when
first := noSpamKey(nil)
second := noSpamKey(nil)
// then
assert.NotEqual(t, first, second)
})
}
func Test_noAggregationKey(t *testing.T) {
t.Run("should not return the same keys", func(t *testing.T) {
// when
firstAggregateKey, firstLocalKey := noAggregationKey(nil)
secondAggregateKey, secondLocalKey := noAggregationKey(nil)
// then
assert.NotEqual(t, firstAggregateKey, secondAggregateKey)
assert.NotEqual(t, firstLocalKey, secondLocalKey)
})
}
func Test_startDoguOperator(t *testing.T) {
t.Run("Error on missing namespace environment variable", func(t *testing.T) {
// given
resetFunc := setupOverrides()
defer resetFunc()
_ = os.Unsetenv("NAMESPACE")
getNewMockManager(nil, createMockDefinitions())
// when
err := startDoguOperator()
// then
require.Error(t, err)
require.Contains(t, err.Error(), "failed to read namespace: failed to get env var [NAMESPACE]")
})
t.Run("Test without logger environment variables", func(t *testing.T) {
// given
resetFunc := setupOverrides()
defer resetFunc()
setupEnvironment(t)
k8sManager := getNewMockManager(nil, createMockDefinitions())
// when
err := startDoguOperator()
// then
require.NoError(t, err)
mock.AssertExpectationsForObjects(t, k8sManager)
})
expectedError := fmt.Errorf("this is my expected error")
t.Run("Test with error on manager creation", func(t *testing.T) {
// given
resetFunc := setupOverrides()
defer resetFunc()
setupEnvironment(t)
getNewMockManager(expectedError, createMockDefinitions())
// when
err := startDoguOperator()
// then
require.ErrorIs(t, err, expectedError)
})
mockDefinitionsThatCanFail := []string{
"Add",
"AddHealthzCheck",
"AddReadyzCheck",
"Start",
}
for _, mockDefinitionName := range mockDefinitionsThatCanFail {
t.Run(fmt.Sprintf("fail setup when error on %s", mockDefinitionName), func(t *testing.T) {
// given
resetFunc := setupOverrides()
t.Cleanup(resetFunc)
setupEnvironment(t)
adaptedMockDefinitions := getCopyMap(createMockDefinitions())
adaptedMockDefinitions[mockDefinitionName] = mockDefinition{
Arguments: adaptedMockDefinitions[mockDefinitionName].Arguments,
ReturnValue: expectedError,
}
getNewMockManager(nil, adaptedMockDefinitions)
// when
startErr := startDoguOperator()
// then
require.ErrorIs(t, startErr, expectedError)
})
}
}
func setupEnvironment(t *testing.T) {
t.Setenv("NAMESPACE", "mynamespace")
t.Setenv("DOGU_REGISTRY_ENDPOINT", "mynamespace")
t.Setenv("DOGU_REGISTRY_USERNAME", "mynamespace")
t.Setenv("DOGU_REGISTRY_PASSWORD", "mynamespace")
t.Setenv("NETWORK_POLICIES_ENABLED", "true")
}
func setupOverrides() func() {
// override default controller method to create a new manager
oldNewManagerDelegate := ctrl.NewManager
// override default controller method to retrieve a kube config
oldGetConfigOrDieDelegate := ctrl.GetConfigOrDie
ctrl.GetConfigOrDie = func() *rest.Config {
return &rest.Config{}
}
// override default controller method to retrieve a kube config
oldGetConfigDelegate := ctrl.GetConfig
ctrl.GetConfig = func() (*rest.Config, error) {
return &rest.Config{}, nil
}
// override default controller method to signal the setup handler
oldHandler := ctrl.SetupSignalHandler
ctrl.SetupSignalHandler = func() context.Context {
return context.TODO()
}
// override default controller-builder and add skipNameValidation for tests
oldCtrlBuilder := ctrl.NewControllerManagedBy
ctrl.NewControllerManagedBy = func(m manager.Manager) *ctrl.Builder {
builder := oldCtrlBuilder(m)
skipNameValidation := true
builder.WithOptions(controller.Options{SkipNameValidation: &skipNameValidation})
return builder
}
// override default controller method to retrieve a kube config
oldSetLoggerDelegate := ctrl.SetLogger
oldDoguManager := controllers.NewManager
controllers.NewManager = func(client client.Client, ecosystemClient ecoSystem.EcoSystemV2Interface, operatorConfig *config.OperatorConfig, recorder record.EventRecorder) (*controllers.DoguManager, error) {
return &controllers.DoguManager{}, nil
}
return func() {
ctrl.NewManager = oldNewManagerDelegate
ctrl.GetConfigOrDie = oldGetConfigOrDieDelegate
ctrl.GetConfig = oldGetConfigDelegate
ctrl.SetupSignalHandler = oldHandler
ctrl.SetLogger = oldSetLoggerDelegate
ctrl.NewControllerManagedBy = oldCtrlBuilder
controllers.NewManager = oldDoguManager
}
}
func createMockDefinitions() map[string]mockDefinition {
scheme := runtime.NewScheme()
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
scheme.AddKnownTypeWithName(schema.GroupVersionKind{
Group: "k8s.cloudogu.com",
Version: "v2",
Kind: "dogu",
}, &v2.Dogu{})
scheme.AddKnownTypeWithName(schema.GroupVersionKind{
Group: "k8s.cloudogu.com",
Version: "v2",
Kind: "dogurestart",
}, &v2.DoguRestart{})
myClient := fake.NewClientBuilder().WithScheme(scheme).Build()
return map[string]mockDefinition{
"GetScheme": {ReturnValue: scheme},
"GetClient": {ReturnValue: myClient},
"GetCache": {ReturnValue: nil},
"GetConfig": {ReturnValue: &rest.Config{}},
"Add": {Arguments: []interface{}{mock.Anything}, ReturnValue: nil},
"AddHealthzCheck": {Arguments: []interface{}{mock.Anything, mock.Anything}, ReturnValue: nil},
"AddReadyzCheck": {Arguments: []interface{}{mock.Anything, mock.Anything}, ReturnValue: nil},
"Start": {Arguments: []interface{}{mock.Anything}, ReturnValue: nil},
"GetControllerOptions": {ReturnValue: runtimeconf.Controller{}},
"GetEventRecorderFor": {Arguments: []interface{}{mock.Anything}, ReturnValue: nil},
}
}