forked from operator-framework/operator-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator_test.go
545 lines (480 loc) · 14.3 KB
/
generator_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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// Copyright 2018 The Operator-SDK 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 generator
import (
"bytes"
"path/filepath"
"strings"
"testing"
k8sutil "github.com/operator-framework/operator-sdk/pkg/util/k8sutil"
"github.com/sergi/go-diff/diffmatchpatch"
)
const updateGeneratedExp = `#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
vendor/k8s.io/code-generator/generate-groups.sh \
deepcopy \
github.com/example-inc/app-operator/pkg/generated \
github.com/example-inc/app-operator/pkg/apis \
app:v1alpha1 \
--go-header-file "./tmp/codegen/boilerplate.go.txt"
`
func TestCodeGen(t *testing.T) {
buf := &bytes.Buffer{}
td := tmplData{
RepoPath: appRepoPath,
APIDirName: appApiDirName,
Version: appVersion,
}
if err := renderFile(buf, "codegen/update-generated.sh", updateGeneratedTmpl, td); err != nil {
t.Error(err)
return
}
if updateGeneratedExp != buf.String() {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(updateGeneratedExp, buf.String(), false)
t.Errorf("\nTest failed. Below is the diff of the expected vs actual results.\nRed text is missing and green text is extra.\n\n" + dmp.DiffPrettyText(diffs))
}
}
const versionExp = `package version
var (
Version = "0.9.2+git"
)
`
func TestGenVersion(t *testing.T) {
buf := &bytes.Buffer{}
if err := renderFile(buf, "version/version.go", versionTmpl, tmplData{VersionNumber: "0.9.2+git"}); err != nil {
t.Error(err)
return
}
if versionExp != buf.String() {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(versionExp, buf.String(), false)
t.Errorf("\nTest failed. Below is the diff of the expected vs actual results.\nRed text is missing and green text is extra.\n\n" + dmp.DiffPrettyText(diffs))
}
}
const handlerExp = `package stub
import (
"context"
"github.com/example-inc/app-operator/pkg/apis/app/v1alpha1"
"github.com/operator-framework/operator-sdk/pkg/sdk"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
)
func NewHandler() sdk.Handler {
return &Handler{}
}
type Handler struct {
// Fill me
}
func (h *Handler) Handle(ctx context.Context, event sdk.Event) error {
switch o := event.Object.(type) {
case *v1alpha1.AppService:
err := sdk.Create(newbusyBoxPod(o))
if err != nil && !errors.IsAlreadyExists(err) {
logrus.Errorf("Failed to create busybox pod : %v", err)
return err
}
}
return nil
}
// newbusyBoxPod demonstrates how to create a busybox pod
func newbusyBoxPod(cr *v1alpha1.AppService) *corev1.Pod {
labels := map[string]string{
"app": "busy-box",
}
return &corev1.Pod{
TypeMeta: metav1.TypeMeta{
Kind: "Pod",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "busy-box",
Namespace: cr.Namespace,
OwnerReferences: []metav1.OwnerReference{
*metav1.NewControllerRef(cr, schema.GroupVersionKind{
Group: v1alpha1.SchemeGroupVersion.Group,
Version: v1alpha1.SchemeGroupVersion.Version,
Kind: "AppService",
}),
},
Labels: labels,
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "busybox",
Image: "busybox",
Command: []string{"sleep", "3600"},
},
},
},
}
}
`
func TestGenHandler(t *testing.T) {
buf := &bytes.Buffer{}
td := tmplData{
OperatorSDKImport: sdkImport,
RepoPath: appRepoPath,
Kind: appKind,
APIDirName: appApiDirName,
Version: appVersion,
}
if err := renderFile(buf, "stub/handler.go", handlerTmpl, td); err != nil {
t.Error(err)
return
}
if handlerExp != buf.String() {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(handlerExp, buf.String(), false)
t.Errorf("\nTest failed. Below is the diff of the expected vs actual results.\nRed text is missing and green text is extra.\n\n" + dmp.DiffPrettyText(diffs))
}
}
const crdYamlExp = `apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: appservices.app.example.com
spec:
group: app.example.com
names:
kind: AppService
listKind: AppServiceList
plural: appservices
singular: appservice
scope: Namespaced
version: v1alpha1
`
const operatorYamlExp = `apiVersion: apps/v1
kind: Deployment
metadata:
name: app-operator
spec:
replicas: 1
selector:
matchLabels:
name: app-operator
template:
metadata:
labels:
name: app-operator
spec:
containers:
- name: app-operator
image: quay.io/example-inc/app-operator:0.0.1
ports:
- containerPort: 60000
name: metrics
command:
- app-operator
imagePullPolicy: Always
env:
- name: WATCH_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: OPERATOR_NAME
value: "app-operator"
`
const rbacYamlExp = `kind: Role
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: app-operator
rules:
- apiGroups:
- app.example.com
resources:
- "*"
verbs:
- "*"
- apiGroups:
- ""
resources:
- pods
- services
- endpoints
- persistentvolumeclaims
- events
- configmaps
- secrets
verbs:
- "*"
- apiGroups:
- apps
resources:
- deployments
- daemonsets
- replicasets
- statefulsets
verbs:
- "*"
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: default-account-app-operator
subjects:
- kind: ServiceAccount
name: default
roleRef:
kind: Role
name: app-operator
apiGroup: rbac.authorization.k8s.io
`
func TestGenDeploy(t *testing.T) {
buf := &bytes.Buffer{}
crdTd := tmplData{
Kind: appKind,
KindSingular: strings.ToLower(appKind),
KindPlural: toPlural(strings.ToLower(appKind)),
GroupName: groupName(appAPIVersion),
Version: version(appAPIVersion),
}
if err := renderFile(buf, crdTmplName, crdTmpl, crdTd); err != nil {
t.Error(err)
}
if crdYamlExp != buf.String() {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(crdYamlExp, buf.String(), false)
t.Errorf("\nTest failed. Below is the diff of the expected vs actual results.\nRed text is missing and green text is extra.\n\n" + dmp.DiffPrettyText(diffs))
}
buf = &bytes.Buffer{}
td := tmplData{
ProjectName: appProjectName,
Image: appImage,
MetricsPort: k8sutil.PrometheusMetricsPort,
MetricsPortName: k8sutil.PrometheusMetricsPortName,
OperatorNameEnv: k8sutil.OperatorNameEnvVar,
}
if err := renderFile(buf, operatorTmplName, operatorYamlTmpl, td); err != nil {
t.Error(err)
}
if operatorYamlExp != buf.String() {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(operatorYamlExp, buf.String(), false)
t.Errorf("\nTest failed. Below is the diff of the expected vs actual results.\nRed text is missing and green text is extra.\n\n" + dmp.DiffPrettyText(diffs))
}
buf = &bytes.Buffer{}
if err := renderFile(buf, rbacTmplName, rbacYamlTmpl, tmplData{ProjectName: appProjectName, GroupName: appGroupName}); err != nil {
t.Error(err)
}
if rbacYamlExp != buf.String() {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(rbacYamlExp, buf.String(), false)
t.Errorf("\nTest failed. Below is the diff of the expected vs actual results.\nRed text is missing and green text is extra.\n\n" + dmp.DiffPrettyText(diffs))
}
}
const registerExp = `package v1alpha1
import (
sdkK8sutil "github.com/operator-framework/operator-sdk/pkg/util/k8sutil"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
const (
version = "v1alpha1"
groupName = "app.example.com"
)
var (
SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
AddToScheme = SchemeBuilder.AddToScheme
// SchemeGroupVersion is the group version used to register these objects.
SchemeGroupVersion = schema.GroupVersion{Group: groupName, Version: version}
)
func init() {
sdkK8sutil.AddToSDKScheme(AddToScheme)
}
// addKnownTypes adds the set of types defined in this package to the supplied scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&AppService{},
&AppServiceList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}
`
func TestGenRegister(t *testing.T) {
buf := &bytes.Buffer{}
arTd := tmplData{
Kind: appKind,
KindPlural: toPlural(strings.ToLower(appKind)),
GroupName: appGroupName,
Version: appVersion,
}
if err := renderFile(buf, "apis/<apiDirName>/<version>/register.go", apiRegisterTmpl, arTd); err != nil {
t.Error(err)
return
}
if registerExp != buf.String() {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(registerExp, buf.String(), false)
t.Errorf("\nTest failed. Below is the diff of the expected vs actual results.\nRed text is missing and green text is extra.\n\n" + dmp.DiffPrettyText(diffs))
}
}
const typesExp = `package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type AppServiceList struct {
metav1.TypeMeta ` + "`" + `json:",inline"` + "`\n" +
` metav1.ListMeta ` + "`" + `json:"metadata"` + "`\n" +
` Items []AppService ` + "`" + `json:"items"` + "`" + `
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type AppService struct {
metav1.TypeMeta ` + "`" + `json:",inline"` + "`\n" +
` metav1.ObjectMeta ` + "`" + `json:"metadata"` + "`\n" +
` Spec AppServiceSpec ` + "`" + `json:"spec"` + "`\n" +
` Status AppServiceStatus ` + "`" + `json:"status,omitempty"` + "`" + `
}
type AppServiceSpec struct {
// Fill me
}
type AppServiceStatus struct {
// Fill me
}
`
func TestGenTypes(t *testing.T) {
buf := &bytes.Buffer{}
atTd := tmplData{
Kind: appKind,
Version: appVersion,
}
if err := renderFile(buf, "apis/<apiDirName>/<version>/types.go", apiTypesTmpl, atTd); err != nil {
t.Error(err)
return
}
if typesExp != buf.String() {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(typesExp, buf.String(), false)
t.Errorf("\nTest failed. Below is the diff of the expected vs actual results.\nRed text is missing and green text is extra.\n\n" + dmp.DiffPrettyText(diffs))
}
}
const mainExp = `package main
import (
"context"
"runtime"
stub "github.com/example-inc/app-operator/pkg/stub"
sdk "github.com/operator-framework/operator-sdk/pkg/sdk"
k8sutil "github.com/operator-framework/operator-sdk/pkg/util/k8sutil"
sdkVersion "github.com/operator-framework/operator-sdk/version"
"github.com/sirupsen/logrus"
)
func printVersion() {
logrus.Infof("Go Version: %s", runtime.Version())
logrus.Infof("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH)
logrus.Infof("operator-sdk Version: %v", sdkVersion.Version)
}
func main() {
printVersion()
sdk.ExposeMetricsPort()
resource := "app.example.com/v1alpha1"
kind := "AppService"
namespace, err := k8sutil.GetWatchNamespace()
if err != nil {
logrus.Fatalf("Failed to get watch namespace: %v", err)
}
resyncPeriod := 5
logrus.Infof("Watching %s, %s, %s, %d", resource, kind, namespace, resyncPeriod)
sdk.Watch(resource, kind, namespace, resyncPeriod)
sdk.Handle(stub.NewHandler())
sdk.Run(context.TODO())
}
`
func TestGenMain(t *testing.T) {
buf := &bytes.Buffer{}
td := tmplData{
OperatorSDKImport: sdkImport,
StubImport: filepath.Join(appRepoPath, stubDir),
K8sutilImport: k8sutilImport,
SDKVersionImport: versionImport,
APIVersion: appAPIVersion,
Kind: appKind,
}
if err := renderFile(buf, "cmd/<projectName>/main.go", mainTmpl, td); err != nil {
t.Error(err)
return
}
if mainExp != buf.String() {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(mainExp, buf.String(), false)
t.Errorf("\nTest failed. Below is the diff of the expected vs actual results.\nRed text is missing and green text is extra.\n\n" + dmp.DiffPrettyText(diffs))
}
}
const buildExp = `#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
if ! which go > /dev/null; then
echo "golang needs to be installed"
exit 1
fi
BIN_DIR="$(pwd)/tmp/_output/bin"
mkdir -p ${BIN_DIR}
PROJECT_NAME="app-operator"
REPO_PATH="github.com/example-inc/app-operator"
BUILD_PATH="${REPO_PATH}/cmd/${PROJECT_NAME}"
echo "building "${PROJECT_NAME}"..."
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o ${BIN_DIR}/${PROJECT_NAME} $BUILD_PATH
`
const dockerFileExp = `FROM alpine:3.6
RUN adduser -D app-operator
USER app-operator
ADD tmp/_output/bin/app-operator /usr/local/bin/app-operator
`
func TestGenBuild(t *testing.T) {
buf := &bytes.Buffer{}
bTd := tmplData{
ProjectName: appProjectName,
RepoPath: appRepoPath,
}
if err := renderFile(buf, "tmp/build/build.sh", buildTmpl, bTd); err != nil {
t.Error(err)
return
}
if buildExp != buf.String() {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(buildExp, buf.String(), false)
t.Errorf("\nTest failed. Below is the diff of the expected vs actual results.\nRed text is missing and green text is extra.\n\n" + dmp.DiffPrettyText(diffs))
}
buf = &bytes.Buffer{}
if err := renderDockerBuildFile(buf); err != nil {
t.Error(err)
return
}
if dockerBuildTmpl != buf.String() {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(dockerBuildTmpl, buf.String(), false)
t.Errorf("\nTest failed. Below is the diff of the expected vs actual results.\nRed text is missing and green text is extra.\n\n" + dmp.DiffPrettyText(diffs))
}
buf = &bytes.Buffer{}
dTd := tmplData{
ProjectName: appProjectName,
}
if err := renderFile(buf, "tmp/build/Dockerfile", dockerFileTmpl, dTd); err != nil {
t.Error(err)
return
}
if dockerFileExp != buf.String() {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(dockerFileExp, buf.String(), false)
t.Errorf("\nTest failed. Below is the diff of the expected vs actual results.\nRed text is missing and green text is extra.\n\n" + dmp.DiffPrettyText(diffs))
}
}