generated from crossplane/function-template-go
-
Notifications
You must be signed in to change notification settings - Fork 17
/
fn_test.go
583 lines (563 loc) · 20 KB
/
fn_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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
package main
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/go-logr/logr/testr"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/structpb"
"github.com/crossplane/crossplane-runtime/pkg/logging"
fnv1 "github.com/crossplane/function-sdk-go/proto/v1"
"github.com/crossplane/function-sdk-go/resource"
"github.com/crossplane/function-sdk-go/response"
"kcl-lang.io/krm-kcl/pkg/kube"
)
func TestRunFunctionSimple(t *testing.T) {
type args struct {
ctx context.Context
req *fnv1.RunFunctionRequest
}
type want struct {
rsp *fnv1.RunFunctionResponse
err error
}
var (
cd = `{"apiVersion":"example.org/v1","kind":"CD","metadata":{"annotations":{"krm.kcl.dev/composition-resource-name":"cool-cd"},"name":"cool-cd"}}`
xr = `{"apiVersion":"example.org/v1","kind":"XR","metadata":{"name":"cool-xr"},"spec":{"count":2}}`
)
cases := map[string]struct {
reason string
defaultSource string
args args
want want
}{
"ResponseIsReturned": {
reason: "The Function should return a fatal result if no input was specified",
args: args{
req: &fnv1.RunFunctionRequest{
Meta: &fnv1.RequestMeta{Tag: "hello"},
Input: resource.MustStructJSON(`{
"apiVersion": "krm.kcl.dev/v1alpha1",
"kind": "KCLInput",
"metadata": {
"name": "basic"
},
"spec": {
"target": "Resources",
"source": "{\n apiVersion: \"example.org/v1\"\n kind: \"Generated\"\n}"
}
}`),
Observed: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"XR"}`),
},
},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: &fnv1.ResponseMeta{Tag: "hello", Ttl: durationpb.New(response.DefaultTTL)},
Desired: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"XR"}`),
},
Resources: map[string]*fnv1.Resource{
"": {
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"Generated"}`),
},
},
},
},
},
},
"DatabaseInstance": {
reason: "The Function should return a fatal result if no input was specified",
args: args{
req: &fnv1.RunFunctionRequest{
Meta: &fnv1.RequestMeta{Tag: "database-instance"},
Input: resource.MustStructJSON(`{
"apiVersion": "krm.kcl.dev/v1alpha1",
"kind": "KCLInput",
"metadata": {
"name": "basic"
},
"spec": {
"source": "items = [{ \n apiVersion: \"sql.gcp.upbound.io/v1beta1\"\n kind: \"DatabaseInstance\"\n spec: {\n forProvider: {\n project: \"test-project\"\n settings: [{databaseFlags: [{\n name: \"log_checkpoints\"\n value: \"on\"\n }]}]\n }\n }\n}]\n"
}
}`),
Observed: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"XR"}`),
},
},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: &fnv1.ResponseMeta{Tag: "database-instance", Ttl: durationpb.New(response.DefaultTTL)},
Desired: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"XR"}`),
},
Resources: map[string]*fnv1.Resource{
"": {
Resource: resource.MustStructJSON(`{"apiVersion": "sql.gcp.upbound.io/v1beta1", "kind": "DatabaseInstance", "spec": {"forProvider": {"project": "test-project", "settings": [{"databaseFlags": [{"name": "log_checkpoints", "value": "on"}]}]}}}`),
},
},
},
},
},
},
"CustomCompositionResourceNameIsSet": {
reason: "The Function should set value of crossplane.io/composition-resource-name annotation by krm.kcl.dev/composition-resource-name annotation ",
args: args{
req: &fnv1.RunFunctionRequest{
Meta: &fnv1.RequestMeta{Tag: "hello"},
Input: resource.MustStructJSON(`{
"apiVersion": "krm.kcl.dev/v1alpha1",
"kind": "KCLInput",
"metadata": {
"name": "basic"
},
"spec": {
"target": "Default",
"source": "{\n apiVersion: \"example.org/v1\"\n kind: \"Generated\"\n metadata.annotations = {\"krm.kcl.dev/composition-resource-name\": \"custom-composition-resource-name\"}\n}"
}
}`),
Observed: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"XR"}`),
},
},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: &fnv1.ResponseMeta{Tag: "hello", Ttl: durationpb.New(response.DefaultTTL)},
Desired: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"XR"}`),
},
Resources: map[string]*fnv1.Resource{
"custom-composition-resource-name": {
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"Generated","metadata":{"annotations":{}}}`),
},
},
},
},
},
},
"MultipleResource": {
reason: "The Function should return multiple resources with different resource names",
args: args{
req: &fnv1.RunFunctionRequest{
Meta: &fnv1.RequestMeta{Tag: "multiple-resource"},
Input: resource.MustStructJSON(`{
"apiVersion": "krm.kcl.dev/v1alpha1",
"kind": "KCLInput",
"metadata": {
"name": "basic"
},
"spec": {
"source": "items = [\n{\n apiVersion: \"example.org/v1\"\n kind: \"Generated\"\n metadata.annotations = {\"krm.kcl.dev/composition-resource-name\": \"custom-composition-resource-name-0\"}\n}\n{\n apiVersion: \"example.org/v1\"\n kind: \"Generated\"\n metadata.annotations = {\"krm.kcl.dev/composition-resource-name\": \"custom-composition-resource-name-1\"}\n}\n]\n"
}
}`),
Observed: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"XR"}`),
},
},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: &fnv1.ResponseMeta{Tag: "multiple-resource", Ttl: durationpb.New(response.DefaultTTL)},
Desired: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"XR"}`),
},
Resources: map[string]*fnv1.Resource{
"custom-composition-resource-name-0": {
Resource: resource.MustStructJSON(`{"apiVersion": "example.org/v1", "kind": "Generated", "metadata": {"annotations": {}}}`),
},
"custom-composition-resource-name-1": {
Resource: resource.MustStructJSON(`{"apiVersion": "example.org/v1", "kind": "Generated", "metadata": {"annotations": {}}}`),
},
},
},
},
},
},
"ExtraResources": {
reason: "The Function should return the desired composite with extra resources.",
args: args{
req: &fnv1.RunFunctionRequest{
Meta: &fnv1.RequestMeta{Tag: "extra-resources"},
Input: resource.MustStructJSON(`{
"apiVersion": "krm.kcl.dev/v1alpha1",
"kind": "KCLInput",
"metadata": {
"name": "basic"
},
"spec": {
"target": "Default",
"source": "items = [\n{\n apiVersion: \"meta.krm.kcl.dev/v1alpha1\"\n kind: \"ExtraResources\"\n requirements = {\n \"cool-extra-resource\" = {\n apiVersion: \"example.org/v1\"\n kind: \"CoolExtraResource\"\n matchName: \"cool-extra-resource\"\n }\n }\n},\n{\n apiVersion: \"meta.krm.kcl.dev/v1alpha1\"\n kind: \"ExtraResources\"\n requirements = {\n \"another-cool-extra-resource\" = {\n apiVersion: \"example.org/v1\"\n kind: \"CoolExtraResource\"\n matchLabels = {\n key: \"value\"\n }\n }\n \"yet-another-cool-extra-resource\" = {\n apiVersion: \"example.org/v1\"\n kind: \"CoolExtraResource\"\n matchName: \"foo\"\n }\n }\n},\n{\n apiVersion: \"meta.krm.kcl.dev/v1alpha1\"\n kind: \"ExtraResources\"\n requirements = {\n \"all-cool-resources\" = {\n apiVersion: \"example.org/v1\"\n kind: \"CoolExtraResource\"\n matchLabels = {}\n }\n }\n}\n]\n"
}
}`),
Observed: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(xr),
},
},
Desired: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(xr),
},
Resources: map[string]*fnv1.Resource{
"cool-cd": {
Resource: resource.MustStructJSON(cd),
},
},
},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: &fnv1.ResponseMeta{Tag: "extra-resources", Ttl: durationpb.New(response.DefaultTTL)},
Results: []*fnv1.Result{},
Requirements: &fnv1.Requirements{
ExtraResources: map[string]*fnv1.ResourceSelector{
"cool-extra-resource": {
ApiVersion: "example.org/v1",
Kind: "CoolExtraResource",
Match: &fnv1.ResourceSelector_MatchName{
MatchName: "cool-extra-resource",
},
},
"another-cool-extra-resource": {
ApiVersion: "example.org/v1",
Kind: "CoolExtraResource",
Match: &fnv1.ResourceSelector_MatchLabels{
MatchLabels: &fnv1.MatchLabels{
Labels: map[string]string{"key": "value"},
},
},
},
"yet-another-cool-extra-resource": {
ApiVersion: "example.org/v1",
Kind: "CoolExtraResource",
Match: &fnv1.ResourceSelector_MatchName{
MatchName: "foo",
},
},
"all-cool-resources": {
ApiVersion: "example.org/v1",
Kind: "CoolExtraResource",
Match: &fnv1.ResourceSelector_MatchLabels{
MatchLabels: &fnv1.MatchLabels{
Labels: map[string]string{},
},
},
},
},
},
Desired: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(xr),
},
Resources: map[string]*fnv1.Resource{
"cool-cd": {
Resource: resource.MustStructJSON(cd),
},
},
},
},
},
},
"ExtraResourcesIn": {
reason: "The Function should return the extra resources from the request.",
args: args{
req: &fnv1.RunFunctionRequest{
Meta: &fnv1.RequestMeta{Tag: "extra-resources-in"},
Input: resource.MustStructJSON(`{
"apiVersion": "krm.kcl.dev/v1alpha1",
"kind": "KCLInput",
"metadata": {
"name": "basic"
},
"spec": {
"target": "Default",
"source": "items = [v.Resource for v in option(\"params\").extraResources[\"cool1\"]]\n"
}
}`),
ExtraResources: map[string]*fnv1.Resources{
"cool1": {
Items: []*fnv1.Resource{
{Resource: resource.MustStructJSON(xr)},
{Resource: resource.MustStructJSON(cd)},
},
},
},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: &fnv1.ResponseMeta{Tag: "extra-resources-in", Ttl: durationpb.New(response.DefaultTTL)},
Results: []*fnv1.Result{},
Desired: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(`{"apiVersion":"","kind":""}`),
},
Resources: map[string]*fnv1.Resource{
"cool-xr": {
Resource: resource.MustStructJSON(xr),
},
"cool-cd": {
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"CD","metadata":{"annotations":{},"name":"cool-cd"}}`),
},
},
},
},
},
},
"DuplicateExtraResourceKey": {
reason: "The Function should return a fatal result if the extra resource key is duplicated.",
args: args{
req: &fnv1.RunFunctionRequest{
Meta: &fnv1.RequestMeta{Tag: "duplicate-extra-resources"},
Input: resource.MustStructJSON(`{
"apiVersion": "krm.kcl.dev/v1alpha1",
"kind": "KCLInput",
"metadata": {
"name": "basic"
},
"spec": {
"target": "Default",
"source": "items = [\n{\n apiVersion: \"meta.krm.kcl.dev/v1alpha1\"\n kind: \"ExtraResources\"\n requirements = {\n \"cool-extra-resource\" = {\n apiVersion: \"example.org/v1\"\n kind: \"CoolExtraResource\"\n matchName: \"cool-extra-resource\"\n }\n }\n}\n{\n apiVersion: \"meta.krm.kcl.dev/v1alpha1\"\n kind: \"ExtraResources\"\n requirements = {\n \"cool-extra-resource\" = {\n apiVersion: \"example.org/v1\"\n kind: \"CoolExtraResource\"\n matchName: \"another-cool-extra-resource\"\n }\n }\n}\n]\n"
}
}`),
Observed: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(xr),
},
},
Desired: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(xr),
},
Resources: map[string]*fnv1.Resource{
"cool-cd": {
Resource: resource.MustStructJSON(cd),
},
},
},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: &fnv1.ResponseMeta{Tag: "duplicate-extra-resources", Ttl: durationpb.New(response.DefaultTTL)},
Results: []*fnv1.Result{
{
Severity: fnv1.Severity_SEVERITY_FATAL,
Target: fnv1.Target_TARGET_COMPOSITE.Enum(),
Message: "cannot process xr and state with the pipeline output in *v1.RunFunctionResponse: duplicate extra resource key \"cool-extra-resource\"",
},
},
Desired: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(xr),
},
Resources: map[string]*fnv1.Resource{
"cool-cd": {
Resource: resource.MustStructJSON(cd),
},
},
},
},
},
},
"EmptyInputWithDefaultSource": {
reason: "The function should use the default source when input is not provided and default source is set",
defaultSource: "{\n apiVersion: \"example.org/v1\"\n kind: \"Generated\"\n}",
args: args{
req: &fnv1.RunFunctionRequest{
Meta: &fnv1.RequestMeta{Tag: "empty-input"},
Input: nil,
Observed: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"XR"}`),
},
},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: &fnv1.ResponseMeta{Tag: "empty-input", Ttl: durationpb.New(response.DefaultTTL)},
Desired: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"XR"}`),
},
Resources: map[string]*fnv1.Resource{
"": {
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"Generated"}`),
},
},
},
},
},
},
"EmptyInputWithoutDefaultSource": {
reason: "The function should fail when input is not provided and default source is not set",
args: args{
req: &fnv1.RunFunctionRequest{
Meta: &fnv1.RequestMeta{Tag: "empty-input"},
Input: nil,
Observed: &fnv1.State{
Composite: &fnv1.Resource{
Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"XR"}`),
},
},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: &fnv1.ResponseMeta{Tag: "empty-input", Ttl: durationpb.New(response.DefaultTTL)},
Results: []*fnv1.Result{{
Target: fnv1.Target_TARGET_COMPOSITE.Enum(),
Severity: fnv1.Severity_SEVERITY_FATAL,
Message: "invalid function input: spec.source: Required value: kcl source cannot be empty",
}},
},
},
},
// TODO: disable the resource check, and fix the kcl dup resource evaluation issues.
// "MultipleResourceError": {
// reason: "The Function should return a fatal result if input resources have duplicate names",
// args: args{
// req: &fnv1.RunFunctionRequest{
// Meta: &fnv1.RequestMeta{Tag: "multiple-resource-error"},
// Input: resource.MustStructJSON(`{
// "apiVersion": "krm.kcl.dev/v1alpha1",
// "kind": "KCLInput",
// "metadata": {
// "name": "basic"
// },
// "spec": {
// "source": "items = [\n{\n apiVersion: \"example.org/v1\"\n kind: \"Generated\"\n metadata.annotations = {\"krm.kcl.dev/composition-resource-name\": \"custom-composition-resource-name\"}\n}\n{\n apiVersion: \"example.org/v1\"\n kind: \"Generated\"\n metadata.annotations = {\"krm.kcl.dev/composition-resource-name\": \"custom-composition-resource-name\"}\n}\n]\n"
// }
// }`),
// Observed: &fnv1.State{
// Composite: &fnv1.Resource{
// Resource: resource.MustStructJSON(`{"apiVersion":"example.org/v1","kind":"XR"}`),
// },
// },
// },
// },
// want: want{
// rsp: &fnv1.RunFunctionResponse{
// Meta: &fnv1.ResponseMeta{Tag: "multiple-resource-error", Ttl: durationpb.New(response.DefaultTTL)},
// Results: []*fnv1.Result{
// {
// Severity: fnv1.Severity_SEVERITY_FATAL,
// Message: "cannot process xr and state with the pipeline output in *v1beta1.RunFunctionResponse: duplicate resource names custom-composition-resource-name found, when returning multiple resources, you need to set different metadata.name or metadata.annotations.\"krm.kcl.dev/composition-resource-name\" to distinguish between different resources in the composition functions.",
// },
// }},
// },
// },
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
// NOTE: This means we can't run tests in parallel.
defaultSource = tc.defaultSource
// f := &Function{log: logging.NewNopLogger()}
f := &Function{log: logging.NewLogrLogger(testr.New(t))}
rsp, err := f.RunFunction(tc.args.ctx, tc.args.req)
if diff := cmp.Diff(tc.want.rsp, rsp, protocmp.Transform()); diff != "" {
t.Errorf("%s\nf.RunFunction(...): -want rsp, +got rsp:\n%s", tc.reason, diff)
}
if diff := cmp.Diff(tc.want.err, err, cmpopts.EquateErrors()); diff != "" {
t.Errorf("%s\nf.RunFunction(...): -want err, +got err:\n%s", tc.reason, diff)
}
})
}
}
const (
xrFile = "xr.yaml"
compositionFile = "composition.yaml"
)
func findXRandCompositionYAMLFiles(rootPath string) ([]string, error) {
var dirs []string
// Walk receives the root directory and a function to process each path
err := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
if err != nil { // Handle potential errors
return err
}
// Check if the current path is a directory and it contains xr.yaml file
if info.IsDir() {
xrPath := filepath.Join(path, xrFile)
compositionPath := filepath.Join(path, compositionFile)
if _, err := os.Stat(xrPath); err == nil {
if _, err := os.Stat(compositionPath); err == nil {
dirs = append(dirs, path) // File exists, add directory to list
}
}
}
return nil
})
return dirs, err
}
func readResourceFromFile(p string) (*structpb.Struct, error) {
c, err := os.ReadFile(p)
if err != nil {
return nil, err
}
o, err := kube.ParseKubeObject(c)
if err != nil {
return nil, err
}
j, err := o.Node().MarshalJSON()
if err != nil {
return nil, err
}
return resource.MustStructJSON(string(j)), nil
}
func TestFunctionExamples(t *testing.T) {
rootPath := "examples" // Change to your examples folder path
dirs, err := findXRandCompositionYAMLFiles(rootPath)
if err != nil {
t.Fatal(err)
}
// Print all directories containing xr.yaml file
for _, dir := range dirs {
xrPath := filepath.Join(dir, xrFile)
compositionPath := filepath.Join(dir, compositionFile)
t.Run(compositionPath, func(t *testing.T) {
f := &Function{log: logging.NewNopLogger()}
input, err := readResourceFromFile(xrPath)
if err != nil {
t.Fatal(err)
}
oxr, err := readResourceFromFile(compositionPath)
if err != nil {
t.Fatal(err)
}
req := &fnv1.RunFunctionRequest{
Input: input,
// option("params").oxr
Observed: &fnv1.State{
Composite: &fnv1.Resource{
Resource: oxr,
},
},
}
_, err = f.RunFunction(context.TODO(), req)
if err != nil {
t.Fatal(err)
}
})
}
}