forked from jonasz-lasut/function-aicr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfn_test.go
More file actions
1303 lines (1233 loc) · 50.8 KB
/
Copy pathfn_test.go
File metadata and controls
1303 lines (1233 loc) · 50.8 KB
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"flag"
"fmt"
"maps"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/structpb"
"k8s.io/apimachinery/pkg/runtime"
sigsyaml "sigs.k8s.io/yaml"
xpv2 "github.com/crossplane/crossplane/apis/v2/core/v2"
"github.com/crossplane/function-sdk-go/logging"
fnv1 "github.com/crossplane/function-sdk-go/proto/v1"
"github.com/crossplane/function-sdk-go/resource"
"github.com/crossplane/function-sdk-go/resource/composed"
"github.com/crossplane/function-sdk-go/response"
"github.com/NVIDIA/aicr/pkg/recipe"
"github.com/jonasz-lasut/function-aicr/input/v1beta1"
"github.com/jonasz-lasut/function-aicr/internal/compose"
"github.com/jonasz-lasut/function-aicr/internal/schema"
)
// update regenerates test-fixtures/want from the function's own output instead
// of comparing against it. It is driven by `go generate ./...` (see
// test-fixtures/generate.go); the resulting diff is what the function will
// deploy after a github.com/NVIDIA/aicr bump, and deserves review.
var update = flag.Bool("update", false, "regenerate test-fixtures/want from the function's output")
const (
fixturesDir = "test-fixtures"
wantDir = "want"
goldenHeader = "# Generated by `go generate ./...` from the request fixtures. DO NOT EDIT.\n"
// testRecipeVersion stands in for the aicr module version main.go reads
// from build info, which test binaries do not carry.
testRecipeVersion = "v0.0.0-test"
)
// yamlToProto loads a single-document YAML fixture (relative to test-fixtures/)
// as a protobuf Struct. For test use only; panics on error.
func yamlToProto(name string) *structpb.Struct {
y, err := os.ReadFile(filepath.Join(fixturesDir, name))
if err != nil {
panic(err)
}
j, err := sigsyaml.YAMLToJSON(y)
if err != nil {
panic(err)
}
return resource.MustStructJSON(string(j))
}
func fixture(name string) *fnv1.Resource { return &fnv1.Resource{Resource: yamlToProto(name)} }
// golden names the generated fixtures under test-fixtures/want that a case's
// desired state is compared against; either may be empty when the case is
// expected to produce none.
type golden struct {
resources string // directory holding one <name>.yaml per desired composed resource
composite string // file holding the desired composite resource
}
// loadGolden reads the desired state a case expects, or nil if it expects none.
func loadGolden(t *testing.T, g golden) *fnv1.State {
t.Helper()
if g.resources == "" && g.composite == "" {
return nil
}
state := &fnv1.State{}
if g.resources != "" {
entries, err := os.ReadDir(filepath.Join(fixturesDir, wantDir, g.resources))
if err != nil {
t.Fatalf("cannot read golden resources %q (run `go generate ./...`): %v", g.resources, err)
}
state.Resources = make(map[string]*fnv1.Resource, len(entries))
for _, e := range entries {
name := strings.TrimSuffix(e.Name(), ".yaml")
state.Resources[name] = fixture(filepath.Join(wantDir, g.resources, e.Name()))
}
}
if g.composite != "" {
state.Composite = fixture(filepath.Join(wantDir, g.composite))
}
return state
}
// writtenGolden guards against two cases regenerating the same golden file
// with different content, which check mode would otherwise report as a
// failure that `go generate` cannot fix.
var writtenGolden = map[string][]byte{}
// writeGolden regenerates the golden fixtures a case names from the desired
// state the function produced.
func writeGolden(t *testing.T, g golden, got *fnv1.State) {
t.Helper()
write := func(rel string, s *structpb.Struct) {
j, err := protojson.Marshal(s)
if err != nil {
t.Fatalf("cannot marshal %q: %v", rel, err)
}
y, err := sigsyaml.JSONToYAML(j)
if err != nil {
t.Fatalf("cannot convert %q to YAML: %v", rel, err)
}
y = append([]byte(goldenHeader), y...)
path := filepath.Join(fixturesDir, wantDir, rel)
if prev, ok := writtenGolden[path]; ok && !slices.Equal(prev, y) {
t.Fatalf("golden %q regenerated with different content by two cases; give them separate goldens", rel)
}
writtenGolden[path] = y
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatalf("cannot create %q: %v", filepath.Dir(path), err)
}
if err := os.WriteFile(path, y, 0o644); err != nil {
t.Fatalf("cannot write %q: %v", path, err)
}
}
if len(got.GetResources()) > 0 && g.resources == "" {
t.Fatalf("case produced %d desired resources but names no golden resources directory", len(got.GetResources()))
}
if got.GetComposite() != nil && g.composite == "" {
t.Fatalf("case produced a desired composite but names no golden composite file")
}
for name, r := range got.GetResources() {
write(filepath.Join(g.resources, name+".yaml"), r.GetResource())
}
if c := got.GetComposite(); c != nil {
write(g.composite, c.GetResource())
}
}
// permissiveSchema accepts any object. It proves the plumbing without pinning
// this test to provider-helm's real CRD; schema.Validate is tested separately.
func permissiveSchema() *fnv1.Schema {
s, err := structpb.NewStruct(map[string]any{
"type": "object",
"x-kubernetes-preserve-unknown-fields": true,
})
if err != nil {
panic(err)
}
return &fnv1.Schema{OpenapiV3: s}
}
func meta() *fnv1.RequestMeta {
return &fnv1.RequestMeta{
Tag: "test",
Capabilities: []fnv1.Capability{
fnv1.Capability_CAPABILITY_CAPABILITIES,
fnv1.Capability_CAPABILITY_REQUIRED_SCHEMAS,
},
}
}
func releaseRequirement() *fnv1.Requirements {
return &fnv1.Requirements{Schemas: map[string]*fnv1.SchemaSelector{
"release": {ApiVersion: "helm.m.crossplane.io/v1beta1", Kind: "Release"},
}}
}
func releaseAndObjectRequirements() *fnv1.Requirements {
return &fnv1.Requirements{Schemas: map[string]*fnv1.SchemaSelector{
"release": {ApiVersion: "helm.m.crossplane.io/v1beta1", Kind: "Release"},
"object": {ApiVersion: "kubernetes.m.crossplane.io/v1alpha1", Kind: "Object"},
}}
}
func functionSuccess() *fnv1.Condition {
return &fnv1.Condition{
Type: "FunctionSuccess",
Status: fnv1.Status_STATUS_CONDITION_TRUE,
Reason: "Success",
Target: fnv1.Target_TARGET_COMPOSITE_AND_CLAIM.Enum(),
}
}
func fatal(msg string) []*fnv1.Result {
return []*fnv1.Result{{
Severity: fnv1.Severity_SEVERITY_FATAL,
Message: msg,
Target: fnv1.Target_TARGET_COMPOSITE.Enum(),
}}
}
// TestRunFunction drives the function end to end against the embedded AICR
// recipe data. The desired state each case expects lives under
// test-fixtures/want and is the function's own output, regenerated by
// `go generate ./...`; the static parts of the response — requirements,
// results, conditions — are asserted here and are what a recipe bump must
// not change.
func TestRunFunction(t *testing.T) {
respMeta := &fnv1.ResponseMeta{Tag: "test", Ttl: durationpb.New(response.DefaultTTL)}
type args struct {
ctx context.Context
req *fnv1.RunFunctionRequest
}
type want struct {
rsp *fnv1.RunFunctionResponse
golden golden
err error
}
cases := map[string]struct {
reason string
args args
want want
}{
"ResolvesRecipeFromAnyXR": {
reason: "With schemas resolved, criteriaFrom pulls criteria off an XR the function knows nothing about; overrides and skips are applied.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/resolve.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
RequiredSchemas: map[string]*fnv1.Schema{"release": permissiveSchema()},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Requirements: releaseRequirement(),
Conditions: []*fnv1.Condition{functionSuccess()},
},
golden: golden{resources: "resolve"},
},
},
"ResolvesProviderConfigFromXR": {
reason: "providerConfigRefFrom pulls the provider config off the XR, so one Composition can target the cluster each XR names; the composed Release carries it.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/provider-config-from-xr.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr-with-provider-config.yaml")},
RequiredSchemas: map[string]*fnv1.Schema{"release": permissiveSchema()},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Requirements: releaseRequirement(),
Conditions: []*fnv1.Condition{functionSuccess()},
},
golden: golden{resources: "provider-config-from-xr"},
},
},
"RendersManifestsIntoObjects": {
reason: "A component's manifest files are Helm-style templates; they are rendered with the recipe's values and emitted as Objects — here the manifest-only nodewright-customizations' Skyhook CR next to nodewright-operator's Release — and the Object schema is required only because the recipe carries manifests.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/render-manifests.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
RequiredSchemas: map[string]*fnv1.Schema{
"release": permissiveSchema(),
"object": permissiveSchema(),
},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Requirements: releaseAndObjectRequirements(),
Conditions: []*fnv1.Condition{functionSuccess()},
},
golden: golden{resources: "render-manifests"},
},
},
"WritesSummaryToTarget": {
reason: "With target set, the resolved-recipe summary lands at the named field path on the desired XR.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/resolve-with-target.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
Desired: &fnv1.State{Composite: fixture("desired/xr.yaml")},
RequiredSchemas: map[string]*fnv1.Schema{"release": permissiveSchema()},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Requirements: releaseRequirement(),
Conditions: []*fnv1.Condition{functionSuccess()},
},
golden: golden{resources: "resolve", composite: "composite/summary.yaml"},
},
},
"PreservesSiblingsAtTarget": {
reason: "A bare status target must not clobber keys other pipeline steps put there: siblings survive and stale summary keys are overwritten.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/resolve-with-status-target.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
Desired: &fnv1.State{Composite: fixture("desired/xr-with-status-siblings.yaml")},
RequiredSchemas: map[string]*fnv1.Schema{"release": permissiveSchema()},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Requirements: releaseRequirement(),
Conditions: []*fnv1.Condition{functionSuccess()},
},
golden: golden{resources: "resolve", composite: "composite/summary-with-siblings.yaml"},
},
},
"WritesNoSummaryWithoutTarget": {
reason: "Without target the desired composite passes through untouched.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/resolve.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
Desired: &fnv1.State{Composite: fixture("desired/xr.yaml")},
RequiredSchemas: map[string]*fnv1.Schema{"release": permissiveSchema()},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Requirements: releaseRequirement(),
Conditions: []*fnv1.Condition{functionSuccess()},
},
golden: golden{resources: "resolve", composite: "composite/passthrough.yaml"},
},
},
"RequestsSchemasAndEmitsNothingWhenUnresolved": {
reason: "On the first pass Crossplane has not resolved the schema; the function asks for it and composes nothing.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/resolve.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Requirements: releaseRequirement(),
},
},
},
"FatalWhenCrossplaneLacksCapability": {
reason: "Without the required-schemas capability the function could never validate, and would otherwise loop forever composing nothing.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: &fnv1.RequestMeta{Tag: "test"},
Input: yamlToProto("input/resolve.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Results: fatal("function-aicr requires a Crossplane that supports required schemas; upgrade Crossplane, or pass --required-schemas to crossplane render"),
},
},
},
"FatalWhenProviderNotInstalled": {
reason: "A resolved-but-nil schema means the CRD is absent; emitting a Release nobody reconciles would strand the XR.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/resolve.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
RequiredSchemas: map[string]*fnv1.Schema{"release": {}},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Requirements: releaseRequirement(),
Results: fatal(`no schema for helm.m.crossplane.io/v1beta1, Kind=Release: is provider-helm installed?`),
},
},
},
"FatalWhenProviderConfigNameMissing": {
reason: "A provider config name must come from providerConfigRef or a providerConfigRefFrom path.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/missing-provider-config.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Results: fatal("cannot resolve the provider config reference: providerConfigRef.name is required: set it, or a providerConfigRefFrom.name field path that resolves on the composite resource"),
},
},
},
"FatalWhenOverrideValuesNotObject": {
reason: "componentOverrides values that are valid JSON but not an object are rejected up front, by name and kind, before any schema is requested.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/override-values-not-object.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Results: fatal(`componentOverrides["gpu-operator"].values must be an object, got string`),
},
},
},
"FatalWhenCriteriaInvalid": {
reason: "A criteria value outside AICR's enums fails fast with AICR's own message; anything AICR accepts is passed through, since only its catalog knows which combinations exist.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/invalid-criteria.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Results: fatal("invalid AICR recipe criteria: [INVALID_REQUEST] invalid accelerator: [INVALID_REQUEST] invalid accelerator type: bogus"),
},
},
},
"FatalWhenTargetNotUnderStatus": {
reason: "Writing outside status would corrupt the desired composite's spec.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/target-not-status.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Results: fatal(`target.fieldPath must begin with "status", got "spec.aicr"`),
},
},
},
"GatesDependentsWithoutObserved": {
reason: "With gating on and nothing observed, gpu-operator is withheld until cert-manager is Ready.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/gate.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
RequiredSchemas: map[string]*fnv1.Schema{"release": permissiveSchema()},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Requirements: releaseRequirement(),
Results: []*fnv1.Result{{
Severity: fnv1.Severity_SEVERITY_NORMAL,
Message: `delaying "gpu-operator" until dependency "cert-manager" is ready`,
Target: fnv1.Target_TARGET_COMPOSITE.Enum(),
}},
Conditions: []*fnv1.Condition{functionSuccess()},
},
golden: golden{resources: "gate-none"},
},
},
"WritesSummaryExcludingGatedComponents": {
reason: "A component withheld by the dependency gate must not be reported as deployed in the summary.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/gate-with-target.yaml"),
Observed: &fnv1.State{Composite: fixture("observed/xr.yaml")},
Desired: &fnv1.State{Composite: fixture("desired/xr.yaml")},
RequiredSchemas: map[string]*fnv1.Schema{"release": permissiveSchema()},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Requirements: releaseRequirement(),
Results: []*fnv1.Result{{
Severity: fnv1.Severity_SEVERITY_NORMAL,
Message: `delaying "gpu-operator" until dependency "cert-manager" is ready`,
Target: fnv1.Target_TARGET_COMPOSITE.Enum(),
}},
Conditions: []*fnv1.Condition{functionSuccess()},
},
golden: golden{resources: "gate-none", composite: "composite/summary-gated.yaml"},
},
},
"EmitsDependentWhenDepsReady": {
reason: "Once cert-manager is observed Ready, gpu-operator is emitted.",
args: args{
ctx: context.Background(),
req: &fnv1.RunFunctionRequest{
Meta: meta(),
Input: yamlToProto("input/gate.yaml"),
Observed: &fnv1.State{
Composite: fixture("observed/xr.yaml"),
Resources: map[string]*fnv1.Resource{
"cert-manager": fixture("observed/cert-manager-ready.yaml"),
},
},
RequiredSchemas: map[string]*fnv1.Schema{"release": permissiveSchema()},
},
},
want: want{
rsp: &fnv1.RunFunctionResponse{
Meta: respMeta,
Requirements: releaseRequirement(),
Conditions: []*fnv1.Condition{functionSuccess()},
},
golden: golden{resources: "gate-ready"},
},
},
}
dp := newDataProvider()
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
f := &Function{log: logging.NewNopLogger(), ttl: response.DefaultTTL, dp: dp, recipeVersion: testRecipeVersion}
rsp, err := f.RunFunction(tc.args.ctx, tc.args.req)
if *update {
writeGolden(t, tc.want.golden, rsp.GetDesired())
}
tc.want.rsp.Desired = loadGolden(t, tc.want.golden)
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)
}
})
}
}
// TestCatalogInvariants resolves every leaf recipe of the embedded AICR
// catalog through the function's own building blocks and asserts the
// properties the function relies on but TestRunFunction — which pins the
// content of a single, manifest-free tier — cannot see. An AICR bump that ships
// a manifest that does not render, two documents that map to the same Object
// name, a disabled component in the deployment order, a dependency on a
// component that is not in the recipe, or a dependency graph the gate can
// never drain fails here, not in a cluster.
func TestCatalogInvariants(t *testing.T) {
ctx := context.Background()
dp := newDataProvider()
leaves, err := recipe.ResolveLeaves(ctx, recipe.ResolveLeavesOptions{Provider: dp, Version: testRecipeVersion})
if err != nil {
t.Fatalf("recipe.ResolveLeaves(...): %v", err)
}
if len(leaves) == 0 {
t.Fatal("recipe.ResolveLeaves(...): the embedded catalog has no leaf recipes")
}
pcRef := compose.ProviderConfigRef{Kind: "ClusterProviderConfig", Name: "gpu-cluster"}
permissive, err := schema.NewValidator(permissiveSchema().GetOpenapiV3())
if err != nil {
t.Fatalf("schema.NewValidator(...): %v", err)
}
for _, leaf := range leaves {
t.Run(leaf.Entry.Name, func(t *testing.T) {
t.Parallel()
if leaf.Err != nil {
t.Fatalf("the catalog cannot resolve this leaf: %v", leaf.Err)
}
criteria := leaf.Entry.Criteria
if err := criteria.Validate(); err != nil {
t.Fatalf("a shipped leaf's criteria must pass AICR's own validation, or the function could never resolve it: %v", err)
}
// The function's own resolution path, without a snapshot evaluator.
res, err := recipe.NewBuilder(recipe.WithVersion(testRecipeVersion), recipe.WithDataProvider(dp)).BuildFromCriteria(ctx, criteria)
if err != nil {
t.Fatalf("BuildFromCriteria(%s): %v", criteria, err)
}
rsp := &fnv1.RunFunctionResponse{}
managed := managedComponents(rsp, res, &v1beta1.Input{})
for _, r := range rsp.GetResults() {
if r.GetSeverity() == fnv1.Severity_SEVERITY_WARNING {
t.Errorf("managedComponents(...) warned with no skips or overrides configured: %s", r.GetMessage())
}
}
if len(managed) == 0 {
t.Fatalf("no managed component: the leaf would deploy nothing")
}
inRecipe := make(map[string]bool, len(res.ComponentRefs))
enabled := make(map[string]bool, len(res.ComponentRefs))
for _, c := range res.ComponentRefs {
inRecipe[c.Name] = true
enabled[c.Name] = c.IsEnabled()
}
ordered := make(map[string]bool, len(res.DeploymentOrder))
for _, name := range res.DeploymentOrder {
ordered[name] = true
if !enabled[name] {
t.Errorf("DeploymentOrder lists %q, which is disabled or absent; the summary would report a component the function never deploys", name)
}
}
for _, name := range slices.Sorted(maps.Keys(managed)) {
if !ordered[name] {
t.Errorf("managed component %q is not in DeploymentOrder — is it disabled by the recipe?", name)
}
}
for _, name := range slices.Sorted(maps.Keys(managed)) {
for _, dep := range managed[name].DependencyRefs {
if !inRecipe[dep] {
t.Errorf("%q depends on %q, which is not a component of the recipe", name, dep)
}
}
}
values, err := resolveValues(ctx, res, managed)
if err != nil {
t.Fatalf("resolveValues(...): %v", err)
}
// Every Release must build and every manifest file must render
// and parse — the function is Fatal otherwise, and a recipe with
// a Fatal tier is unusable.
s := &stack{
managed: managed,
values: values,
pcRef: pcRef,
dp: dp,
releaseSchema: permissive,
objectSchema: permissive,
desired: make(map[resource.Name]*resource.DesiredComposed),
}
if err := s.composeReleases(); err != nil {
t.Fatalf("composeReleases(): %v", err)
}
if err := s.composeObjects(ctx); err != nil {
t.Fatalf("composeObjects(...): %v", err)
}
releases, emitted := 0, 0
for _, name := range slices.Sorted(maps.Keys(managed)) {
if !managed[name].IsManifestOnlyHelm() {
releases++
}
emitted += len(s.objects.all(name))
}
all := s.desired
if releases+emitted != len(all) {
t.Errorf("names collide: %d Releases and %d Objects composed but %d distinct names; a later resource overwrote an earlier one", releases, emitted, len(all))
}
// The gate must eventually emit everything: starting from nothing
// observed, and marking whatever it emits Ready between rounds,
// the withheld set must reach zero. A dependency graph it cannot
// drain — the manifest-only deadlock class — shows up as
// resources it never emits.
total := len(all)
observed := make(map[resource.Name]resource.ObservedComposed, total)
converged := false
for round := 0; round <= 3*len(managed)+3; round++ {
d := maps.Clone(all)
(&stack{managed: managed, desired: d, observed: observed, objects: s.objects}).gate(&fnv1.RunFunctionResponse{})
if len(d) == total {
converged = true
break
}
progressed := false
for name := range d {
if _, ok := observed[name]; ok {
continue
}
cd := composed.New()
cd.SetName(string(name))
cd.SetConditions(xpv2.Available())
observed[name] = resource.ObservedComposed{Resource: cd}
progressed = true
}
if !progressed {
break
}
}
if !converged {
never := make([]string, 0)
for name := range all {
if _, ok := observed[name]; !ok {
never = append(never, string(name))
}
}
slices.Sort(never)
t.Errorf("the gate never emits %d of %d resources even with everything it emitted Ready — a dependency it can never see satisfied: %v", len(never), total, never)
}
})
}
}
// TestGate exercises the gate directly. The embedded "kind" recipe used by
// TestRunFunction carries no manifest files, and its gate cases only ever place
// the dependency (cert-manager) in observed, never the dependent itself; so
// neither the pre-/post-manifest waves nor the "never gate something already
// created" guards have coverage there. The gate withholds resources by deleting
// map entries from desired, which is authoritative — untested deletion logic
// can silently tear down a running component.
func TestGate(t *testing.T) {
observedResource := func(name string, ready bool) (resource.Name, resource.ObservedComposed) {
cd := composed.New()
cd.SetName(name)
if ready {
cd.SetConditions(xpv2.Available())
}
return resource.Name(name), resource.ObservedComposed{Resource: cd}
}
observe := func(entries ...func() (resource.Name, resource.ObservedComposed)) map[resource.Name]resource.ObservedComposed {
observed := make(map[resource.Name]resource.ObservedComposed, len(entries))
for _, e := range entries {
name, oc := e()
observed[name] = oc
}
return observed
}
ready := func(name string) func() (resource.Name, resource.ObservedComposed) {
return func() (resource.Name, resource.ObservedComposed) { return observedResource(name, true) }
}
notReady := func(name string) func() (resource.Name, resource.ObservedComposed) {
return func() (resource.Name, resource.ObservedComposed) { return observedResource(name, false) }
}
delay := func(format string, a ...any) *fnv1.Result {
return &fnv1.Result{
Severity: fnv1.Severity_SEVERITY_NORMAL,
Message: fmt.Sprintf(format, a...),
Target: fnv1.Target_TARGET_COMPOSITE.Enum(),
}
}
const (
dependency = "cert-manager"
component = "gpu-operator"
preObject = "gpu-operator-pre-namespace-gpu-operator"
postObject = "gpu-operator-post-clusterpolicy-cluster-policy"
manifestOnly = "nodewright-customizations"
mOnlyObject = "nodewright-customizations-post-configmap-tuning"
)
chart := func(name string, deps ...string) *recipe.ComponentRef {
return &recipe.ComponentRef{Name: name, Type: recipe.ComponentTypeHelm, Source: "https://example.com", Chart: name, DependencyRefs: deps}
}
manifests := func(name string, deps ...string) *recipe.ComponentRef {
return &recipe.ComponentRef{Name: name, Type: recipe.ComponentTypeHelm, ManifestFiles: []string{"post/tuning.yaml"}, DependencyRefs: deps}
}
// Component sets.
componentWithDependency := map[string]*recipe.ComponentRef{
dependency: chart(dependency),
component: chart(component, dependency),
}
componentWithUnmanagedDependency := map[string]*recipe.ComponentRef{
component: chart(component, "nfd"),
}
componentAlone := map[string]*recipe.ComponentRef{
component: chart(component),
}
componentOnManifestOnly := map[string]*recipe.ComponentRef{
manifestOnly: manifests(manifestOnly),
component: chart(component, manifestOnly),
}
manifestOnlyWithDependency := map[string]*recipe.ComponentRef{
dependency: chart(dependency),
manifestOnly: manifests(manifestOnly, dependency),
}
// Object sets.
none := manifestObjects{}
pre := manifestObjects{pre: map[string][]string{component: {preObject}}}
post := manifestObjects{post: map[string][]string{component: {postObject}}}
mOnly := manifestObjects{post: map[string][]string{manifestOnly: {mOnlyObject}}}
type args struct {
managed map[string]*recipe.ComponentRef
desired []string
observed map[resource.Name]resource.ObservedComposed
objects manifestObjects
}
type want struct {
desired []string
results []*fnv1.Result
}
cases := map[string]struct {
reason string
args args
want want
}{
// Release ← managed dependencies.
"GatesReleaseWhenDependencyAbsent": {
reason: "Nothing observed: the dependent Release is withheld and the dependency survives.",
args: args{managed: componentWithDependency, desired: []string{dependency, component}, objects: none},
want: want{
desired: []string{dependency},
results: []*fnv1.Result{delay(`delaying %q until dependency %q is ready`, component, dependency)},
},
},
"GatesReleaseWhenDependencyNotReady": {
reason: "The dependency is observed but not Ready: the dependent Release is still withheld.",
args: args{managed: componentWithDependency, desired: []string{dependency, component}, observed: observe(notReady(dependency)), objects: none},
want: want{
desired: []string{dependency},
results: []*fnv1.Result{delay(`delaying %q until dependency %q is ready`, component, dependency)},
},
},
"EmitsReleaseWhenDependencyReady": {
reason: "The dependency is observed Ready: both Releases survive.",
args: args{managed: componentWithDependency, desired: []string{dependency, component}, observed: observe(ready(dependency)), objects: none},
want: want{desired: []string{dependency, component}},
},
"NeverDeletesLiveRelease": {
reason: "The dependent is already live while its dependency is absent: the gate must not tear down a running component when its dependency goes briefly unready.",
args: args{managed: componentWithDependency, desired: []string{component}, observed: observe(ready(component)), objects: none},
want: want{desired: []string{component}},
},
"EmitsReleaseWhenDependencyUnmanaged": {
reason: "A dependency absent from the managed set is treated as satisfied — the user opted to manage it elsewhere.",
args: args{managed: componentWithUnmanagedDependency, desired: []string{component}, objects: none},
want: want{desired: []string{component}},
},
// Release ← its pre-manifest Objects.
"GatesReleaseWhenPreObjectAbsent": {
reason: "Nothing observed: the Release is withheld and its pre-manifest Object stays in desired.",
args: args{managed: componentAlone, desired: []string{component, preObject}, objects: pre},
want: want{
desired: []string{preObject},
results: []*fnv1.Result{delay(`delaying %q until pre-manifest object %q is ready`, component, preObject)},
},
},
"GatesReleaseWhenPreObjectNotReady": {
reason: "The pre-manifest Object is observed but not Ready: the Release is still withheld.",
args: args{managed: componentAlone, desired: []string{component, preObject}, observed: observe(notReady(preObject)), objects: pre},
want: want{
desired: []string{preObject},
results: []*fnv1.Result{delay(`delaying %q until pre-manifest object %q is ready`, component, preObject)},
},
},
"EmitsReleaseWhenPreObjectReady": {
reason: "The pre-manifest Object is observed Ready: the Release survives.",
args: args{managed: componentAlone, desired: []string{component, preObject}, observed: observe(ready(preObject)), objects: pre},
want: want{desired: []string{component, preObject}},
},
"NeverDeletesLiveReleaseWhenPreObjectAbsent": {
reason: "The Release is already live while its pre-manifest Object is absent: the gate must not tear down a running component when a sibling goes briefly unready.",
args: args{managed: componentAlone, desired: []string{component, preObject}, observed: observe(ready(component)), objects: pre},
want: want{desired: []string{component, preObject}},
},
// Pre-manifest Objects ← managed dependencies.
"GatesPreObjectsAndReleaseWhenDependencyNotReady": {
reason: "A component's pre-manifest Objects wait for its dependencies too: aicr's pre wave follows the dependencies' waves.",
args: args{managed: componentWithDependency, desired: []string{dependency, component, preObject}, objects: pre},
want: want{
desired: []string{dependency},
results: []*fnv1.Result{
delay(`delaying pre-manifest objects of %q until dependency %q is ready`, component, dependency),
delay(`delaying %q until dependency %q is ready`, component, dependency),
},
},
},
"NeverDeletesLivePreObject": {
reason: "The pre-manifest Object is already live while the dependency is absent: only the not-yet-created Release is withheld, and no pre-manifest delay is reported for nothing.",
args: args{managed: componentWithDependency, desired: []string{dependency, component, preObject}, observed: observe(ready(preObject)), objects: pre},
want: want{
desired: []string{dependency, preObject},
results: []*fnv1.Result{delay(`delaying %q until dependency %q is ready`, component, dependency)},
},
},
// Post-manifest Objects ← the component's Release.
"GatesPostObjectsWhenReleaseAbsent": {
reason: "The Release is not yet created: its post-manifest Objects are withheld (aicr's post wave lands after the chart).",
args: args{managed: componentAlone, desired: []string{component, postObject}, objects: post},
want: want{
desired: []string{component},
results: []*fnv1.Result{delay(`delaying post-manifest objects of %q until its Release is ready`, component)},
},
},
"GatesPostObjectsWhenReleaseNotReady": {
reason: "The Release is observed but not Ready (still installing): its post-manifest Objects are still withheld.",
args: args{managed: componentAlone, desired: []string{component, postObject}, observed: observe(notReady(component)), objects: post},
want: want{
desired: []string{component},
results: []*fnv1.Result{delay(`delaying post-manifest objects of %q until its Release is ready`, component)},
},
},
"EmitsPostObjectsWhenReleaseReady": {
reason: "The Release is observed Ready: its post-manifest Objects survive.",
args: args{managed: componentAlone, desired: []string{component, postObject}, observed: observe(ready(component)), objects: post},
want: want{desired: []string{component, postObject}},
},
"NeverDeletesLivePostObject": {
reason: "The post-manifest Object is already live while its Release is not observed: the gate must not tear it down.",
args: args{managed: componentAlone, desired: []string{component, postObject}, observed: observe(ready(postObject)), objects: post},
want: want{desired: []string{component, postObject}},
},
// Manifest-only component's Objects ← managed dependencies.
"GatesManifestOnlyObjectsWhenDependencyNotReady": {
reason: "A manifest-only component has no Release, so all of its Objects wait for its dependencies.",
args: args{managed: manifestOnlyWithDependency, desired: []string{dependency, mOnlyObject}, objects: mOnly},
want: want{
desired: []string{dependency},
results: []*fnv1.Result{delay(`delaying objects of %q until dependency %q is ready`, manifestOnly, dependency)},
},
},
"EmitsManifestOnlyObjectsWhenDependencyReady": {
reason: "The manifest-only component's dependency is observed Ready: its Objects survive.",
args: args{managed: manifestOnlyWithDependency, desired: []string{dependency, mOnlyObject}, observed: observe(ready(dependency)), objects: mOnly},
want: want{desired: []string{dependency, mOnlyObject}},
},
"NeverDeletesLiveManifestOnlyObject": {
reason: "The manifest-only component's Object is already live while its dependency is absent: the gate must not tear it down.",
args: args{managed: manifestOnlyWithDependency, desired: []string{dependency, mOnlyObject}, observed: observe(ready(mOnlyObject)), objects: mOnly},
want: want{desired: []string{dependency, mOnlyObject}},
},
// Manifest-only component as a dependency: readiness is that of its Objects.
"GatesDependentOnManifestOnlyDependencyWhoseObjectsAreNotReady": {
reason: "The dependent's manifest-only dependency has an Object observed but not Ready: the dependent Release is withheld.",
args: args{managed: componentOnManifestOnly, desired: []string{component, mOnlyObject}, observed: observe(notReady(mOnlyObject)), objects: mOnly},
want: want{
desired: []string{mOnlyObject},
results: []*fnv1.Result{delay(`delaying %q until dependency %q is ready`, component, manifestOnly)},
},
},
"EmitsDependentWhenManifestOnlyDependencyObjectsReady": {
reason: "No Release carries a manifest-only component's name, so a bare-name lookup would deadlock; its readiness is that of every Object it emitted.",
args: args{managed: componentOnManifestOnly, desired: []string{component, mOnlyObject}, observed: observe(ready(mOnlyObject)), objects: mOnly},
want: want{desired: []string{component, mOnlyObject}},
},
"EmitsDependentWhenManifestOnlyDependencyHasNoObjects": {
reason: "The manifest-only dependency emitted no Objects at all: there is nothing to wait for.",
args: args{managed: componentOnManifestOnly, desired: []string{component}, objects: none},
want: want{desired: []string{component}},
},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
desired := make(map[resource.Name]*resource.DesiredComposed, len(tc.args.desired))
for _, n := range tc.args.desired {
desired[resource.Name(n)] = &resource.DesiredComposed{Resource: composed.New()}
}
rsp := &fnv1.RunFunctionResponse{}
s := &stack{managed: tc.args.managed, desired: desired, observed: tc.args.observed, objects: tc.args.objects}
s.gate(rsp)
gotDesired := slices.Sorted(maps.Keys(desired))
wantDesired := make([]resource.Name, 0, len(tc.want.desired))
for _, n := range tc.want.desired {
wantDesired = append(wantDesired, resource.Name(n))
}
slices.Sort(wantDesired)
if diff := cmp.Diff(wantDesired, gotDesired); diff != "" {
t.Errorf("%s\ngate(...): -want desired keys, +got desired keys:\n%s", tc.reason, diff)
}
if diff := cmp.Diff(tc.want.results, rsp.GetResults(), protocmp.Transform()); diff != "" {
t.Errorf("%s\ngate(...): -want results, +got results:\n%s", tc.reason, diff)
}
})
}
}