-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathyaml_test.go
More file actions
1257 lines (1082 loc) · 37.2 KB
/
yaml_test.go
File metadata and controls
1257 lines (1082 loc) · 37.2 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
// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
//
// 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.
// yaml_test.go validates the embedded recipe YAML files in recipes/ (overlays, components).
//
// Area of Concern: Static YAML data file validation
// - Schema conformance - all YAML files parse into RecipeMetadata
// - Reference validation - spec.base, valuesFile, dependencies exist
// - Enum validation - service, accelerator, os, intent use valid values
// - Constraint syntax - all constraint expressions are parseable
// - Inheritance chains - no circular spec.base references, reasonable depth
// - Criteria completeness - leaf recipes have accelerator, os, intent
//
// These tests iterate over actual embedded YAML files to catch data errors
// at build/test time before runtime.
//
// Related test files:
// - metadata_test.go: Tests RecipeMetadata types, Merge(), TopologicalSort(),
// ValidateDependencies(), and MetadataStore inheritance chain resolution
// - recipe_test.go: Tests Recipe struct validation methods after recipes
// are built (Validate, ValidateStructure, ValidateMeasurementExists)
package recipe
import (
"fmt"
"io/fs"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/NVIDIA/aicr/pkg/errors"
"gopkg.in/yaml.v3"
"k8s.io/client-go/kubernetes/scheme"
)
// Tests use GetEmbeddedFS() from adapter (embedded recipes/ at repo root).
// validMeasurementTypes are the valid top-level measurement types for constraints.
var validMeasurementTypes = map[string]bool{
"K8s": true,
"OS": true,
"GPU": true,
"SystemD": true,
}
// validConstraintOperators are the supported constraint operators.
var validConstraintOperators = []string{">=", "<=", ">", "<", "==", "!="}
// baseYAMLFile is the base recipe filename (overlays/base.yaml).
const baseYAMLFile = "overlays/base.yaml"
// ============================================================================
// Schema Conformance Tests
// ============================================================================
// TestAllMetadataFilesParseCorrectly verifies that all YAML files in overlays/
// parse into valid RecipeMetadata structures.
func TestAllMetadataFilesParseCorrectly(t *testing.T) {
files := collectMetadataFiles(t)
if len(files) == 0 {
t.Fatal("no metadata files found")
}
for _, path := range files {
t.Run(filepath.Base(path), func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Errorf("failed to parse %s: %v", path, err)
}
})
}
}
// TestAllMetadataFilesHaveRequiredFields verifies that all metadata files
// contain the required fields: kind, apiVersion, metadata.name.
func TestAllMetadataFilesHaveRequiredFields(t *testing.T) {
files := collectMetadataFiles(t)
for _, path := range files {
t.Run(filepath.Base(path), func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
// Check required fields
if metadata.Kind == "" {
t.Error("missing required field: kind")
}
if metadata.APIVersion == "" {
t.Error("missing required field: apiVersion")
}
if metadata.Metadata.Name == "" {
t.Error("missing required field: metadata.name")
}
// Validate kind and apiVersion values
if metadata.Kind != RecipeMetadataKind {
t.Errorf("invalid kind: got %q, want %q", metadata.Kind, RecipeMetadataKind)
}
if metadata.APIVersion != RecipeAPIVersion {
t.Errorf("invalid apiVersion: got %q, want %q", metadata.APIVersion, RecipeAPIVersion)
}
})
}
}
// ============================================================================
// Criteria Validation Tests
// ============================================================================
// TestAllOverlayCriteriaUseValidEnums verifies that all overlay files use
// only valid enum values for criteria fields (service, accelerator, os, intent).
func TestAllOverlayCriteriaUseValidEnums(t *testing.T) {
files := collectMetadataFiles(t)
for _, path := range files {
filename := filepath.Base(path)
// Skip base.yaml - it doesn't have criteria
if filename == filepath.Base(baseYAMLFile) {
continue
}
t.Run(filename, func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
criteria := metadata.Spec.Criteria
if criteria == nil {
t.Error("overlay missing criteria field")
return
}
// Validate service type
if criteria.Service != "" && criteria.Service != CriteriaServiceAny {
if _, err := ParseCriteriaServiceType(string(criteria.Service)); err != nil {
t.Errorf("invalid service type %q: %v", criteria.Service, err)
}
}
// Validate accelerator type
if criteria.Accelerator != "" && criteria.Accelerator != CriteriaAcceleratorAny {
if _, err := ParseCriteriaAcceleratorType(string(criteria.Accelerator)); err != nil {
t.Errorf("invalid accelerator type %q: %v", criteria.Accelerator, err)
}
}
// Validate intent type
if criteria.Intent != "" && criteria.Intent != CriteriaIntentAny {
if _, err := ParseCriteriaIntentType(string(criteria.Intent)); err != nil {
t.Errorf("invalid intent type %q: %v", criteria.Intent, err)
}
}
// Validate OS type
if criteria.OS != "" && criteria.OS != CriteriaOSAny {
if _, err := ParseCriteriaOSType(string(criteria.OS)); err != nil {
t.Errorf("invalid OS type %q: %v", criteria.OS, err)
}
}
})
}
}
// ============================================================================
// Reference Validation Tests
// ============================================================================
// TestAllValuesFileReferencesExist verifies that all valuesFile references
// in componentRefs point to existing files in the recipes/components/ directory.
func TestAllValuesFileReferencesExist(t *testing.T) {
files := collectMetadataFiles(t)
// Build set of available values files
availableFiles := collectValuesFiles(t)
for _, path := range files {
t.Run(filepath.Base(path), func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
for _, comp := range metadata.Spec.ComponentRefs {
if comp.ValuesFile == "" {
continue
}
if !availableFiles[comp.ValuesFile] {
t.Errorf("componentRef %q references non-existent valuesFile: %q", comp.Name, comp.ValuesFile)
t.Logf("available values files: %v", getKeys(availableFiles))
}
}
})
}
}
// TestAllDependencyReferencesExist verifies that all dependencyRefs
// reference components that are defined in the same file or base.yaml.
func TestAllDependencyReferencesExist(t *testing.T) {
// Load base components first
baseContent, err := GetEmbeddedFS().ReadFile(baseYAMLFile)
if err != nil {
t.Fatalf("failed to read %s: %v", baseYAMLFile, err)
}
var baseMetadata RecipeMetadata
if err := yaml.Unmarshal(baseContent, &baseMetadata); err != nil {
t.Fatalf("failed to parse %s: %v", baseYAMLFile, err)
}
baseComponents := make(map[string]bool)
for _, comp := range baseMetadata.Spec.ComponentRefs {
baseComponents[comp.Name] = true
}
files := collectMetadataFiles(t)
for _, path := range files {
filename := filepath.Base(path)
if filename == filepath.Base(baseYAMLFile) {
continue // Already validated by ValidateDependencies
}
t.Run(filename, func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
// Build set of components defined in this overlay
overlayComponents := make(map[string]bool)
for _, comp := range metadata.Spec.ComponentRefs {
overlayComponents[comp.Name] = true
}
// Check all dependency references
for _, comp := range metadata.Spec.ComponentRefs {
for _, dep := range comp.DependencyRefs {
if !baseComponents[dep] && !overlayComponents[dep] {
t.Errorf("componentRef %q references unknown dependency %q", comp.Name, dep)
}
}
}
})
}
}
// TestAllComponentNamesMatchKnownComponents verifies that all component names
// in recipes match known components from the component registry.
func TestAllComponentNamesMatchKnownComponents(t *testing.T) {
files := collectMetadataFiles(t)
// Get all supported component names from the registry
registry, err := GetComponentRegistry()
if err != nil {
t.Fatalf("failed to load component registry: %v", err)
}
supportedComponents := make(map[string]bool)
for _, name := range registry.Names() {
supportedComponents[name] = true
}
for _, path := range files {
t.Run(filepath.Base(path), func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
for _, comp := range metadata.Spec.ComponentRefs {
if !supportedComponents[comp.Name] {
t.Errorf("componentRef uses unknown component name %q; valid components: %v",
comp.Name, registry.Names())
}
}
})
}
}
// ============================================================================
// Constraint Syntax Tests
// ============================================================================
// TestAllConstraintsSyntaxValid verifies that all constraints use valid syntax:
// - Measurement path format: {type}.{subtype}.{key}
// - Valid operators: >=, <=, >, <, ==, !=, or exact match
func TestAllConstraintsSyntaxValid(t *testing.T) {
files := collectMetadataFiles(t)
// Pattern for measurement path: Type.subtype.key (at least 3 parts)
pathPattern := regexp.MustCompile(`^[A-Za-z0-9]+\.[A-Za-z0-9_/.-]+\.[A-Za-z0-9_/.-]+$`)
for _, path := range files {
t.Run(filepath.Base(path), func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
for _, constraint := range metadata.Spec.Constraints {
// Validate constraint name (measurement path)
if !pathPattern.MatchString(constraint.Name) {
t.Errorf("constraint %q has invalid path format; expected {Type}.{subtype}.{key}", constraint.Name)
}
// Validate measurement type
parts := strings.Split(constraint.Name, ".")
if len(parts) >= 1 {
measurementType := parts[0]
if !validMeasurementTypes[measurementType] {
t.Errorf("constraint %q uses unknown measurement type %q; valid types: %v",
constraint.Name, measurementType, getKeys(validMeasurementTypes))
}
}
// Validate constraint value (operator + value)
if err := validateConstraintValue(constraint.Value); err != nil {
t.Errorf("constraint %q has invalid value %q: %v", constraint.Name, constraint.Value, err)
}
}
})
}
}
// validateConstraintValue checks if a constraint value has valid syntax.
func validateConstraintValue(value string) error {
value = strings.TrimSpace(value)
if value == "" {
return errors.New(errors.ErrCodeInvalidRequest, "empty constraint value")
}
// Check for operator prefix
for _, op := range validConstraintOperators {
if strings.HasPrefix(value, op) {
remainder := strings.TrimSpace(strings.TrimPrefix(value, op))
if remainder == "" {
return errors.New(errors.ErrCodeInvalidRequest, fmt.Sprintf("operator %q without value", op))
}
return nil // Valid operator + value
}
}
// No operator - valid as exact match
return nil
}
// ============================================================================
// Inheritance Chain Validation Tests
// ============================================================================
// TestAllBaseReferencesPointToExistingRecipes verifies that all spec.base
// references in recipe files point to existing recipe files.
func TestAllBaseReferencesPointToExistingRecipes(t *testing.T) {
files := collectMetadataFiles(t)
// Build map of recipe names to files
recipeNames := make(map[string]string)
for _, path := range files {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
recipeNames[metadata.Metadata.Name] = path
}
// Check all base references
for _, path := range files {
filename := filepath.Base(path)
if filename == filepath.Base(baseYAMLFile) {
continue // base.yaml doesn't have a base reference
}
t.Run(filename, func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
// If spec.base is defined, verify it points to an existing recipe
if metadata.Spec.Base != "" {
if _, exists := recipeNames[metadata.Spec.Base]; !exists {
t.Errorf("spec.base references non-existent recipe %q; available recipes: %v",
metadata.Spec.Base, getKeys(recipeNames))
}
}
})
}
}
// TestNoCircularBaseReferences verifies that there are no circular references
// in the spec.base inheritance chain.
func TestNoCircularBaseReferences(t *testing.T) {
files := collectMetadataFiles(t)
// Build map of recipe name -> base reference
baseRefs := make(map[string]string)
for _, path := range files {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
if metadata.Spec.Base != "" {
baseRefs[metadata.Metadata.Name] = metadata.Spec.Base
}
}
// Check for cycles in each recipe's inheritance chain
for recipeName := range baseRefs {
t.Run(recipeName, func(t *testing.T) {
visited := make(map[string]bool)
current := recipeName
for current != "" {
if visited[current] {
t.Errorf("circular inheritance detected: recipe %q leads back to itself", recipeName)
return
}
visited[current] = true
current = baseRefs[current]
}
})
}
}
// TestInheritanceChainDepthReasonable verifies that inheritance chains
// don't exceed a reasonable depth (prevents accidental deep nesting).
func TestInheritanceChainDepthReasonable(t *testing.T) {
const maxDepth = 10 // Reasonable limit for inheritance depth
files := collectMetadataFiles(t)
// Build map of recipe name -> base reference
baseRefs := make(map[string]string)
for _, path := range files {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
if metadata.Spec.Base != "" {
baseRefs[metadata.Metadata.Name] = metadata.Spec.Base
}
}
// Check depth of each recipe's inheritance chain
for recipeName := range baseRefs {
t.Run(recipeName, func(t *testing.T) {
depth := 0
current := recipeName
for current != "" && depth <= maxDepth {
depth++
current = baseRefs[current]
}
if depth > maxDepth {
t.Errorf("inheritance chain for %q exceeds max depth of %d", recipeName, maxDepth)
}
})
}
}
// TestIntermediateRecipesHavePartialCriteria verifies that intermediate recipes
// (those with a spec.base but incomplete criteria) are properly structured.
// Intermediate recipes should have at least one criteria field set.
func TestIntermediateRecipesHavePartialCriteria(t *testing.T) {
files := collectMetadataFiles(t)
for _, path := range files {
filename := filepath.Base(path)
if filename == filepath.Base(baseYAMLFile) {
continue
}
t.Run(filename, func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
// If this recipe has a base reference, it's part of an inheritance chain
// Verify it has at least one criteria field to differentiate it
if metadata.Spec.Base != "" && metadata.Spec.Criteria != nil {
c := metadata.Spec.Criteria
hasSomeCriteria := c.Service != "" || c.Accelerator != "" || c.OS != "" || c.Intent != ""
if !hasSomeCriteria {
t.Errorf("recipe with spec.base should have at least one criteria field set")
}
}
})
}
}
// TestLeafRecipesHaveCompleteCriteria verifies that leaf recipes
// (those that are intended to be matched directly) have complete criteria.
// A leaf recipe is one where no other recipe references it as a base.
func TestLeafRecipesHaveCompleteCriteria(t *testing.T) {
files := collectMetadataFiles(t)
// Build set of recipes that are referenced as base by other recipes
referencedAsBases := make(map[string]bool)
for _, path := range files {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
if metadata.Spec.Base != "" {
referencedAsBases[metadata.Spec.Base] = true
}
}
// Check leaf recipes (not referenced by others) have complete criteria
for _, path := range files {
filename := filepath.Base(path)
if filename == filepath.Base(baseYAMLFile) {
continue
}
t.Run(filename, func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
// Skip if this recipe is referenced as a base by another recipe
// (it's an intermediate recipe, not a leaf)
if referencedAsBases[metadata.Metadata.Name] {
return
}
// Leaf recipes should have at least some criteria for matching.
// They don't need ALL fields - partial criteria are valid for recipes
// that should match multiple scenarios (e.g., a GKE recipe that works
// with any accelerator or intent).
c := metadata.Spec.Criteria
if c == nil {
t.Error("leaf recipe missing criteria")
return
}
// Leaf recipes should have at least one criteria field to distinguish them
// Empty/missing fields act as wildcards and match everything, which is valid
hasSomeCriteria := c.Service != "" || c.Accelerator != "" || c.OS != "" || c.Intent != ""
if !hasSomeCriteria {
t.Error("leaf recipe should have at least one criteria field set")
}
})
}
}
// ============================================================================
// Criteria Uniqueness Tests
// ============================================================================
// TestNoDuplicateCriteriaAcrossOverlays ensures no two overlays have
// identical criteria, which would cause non-deterministic matching.
func TestNoDuplicateCriteriaAcrossOverlays(t *testing.T) {
files := collectMetadataFiles(t)
// Map criteria string to file name
criteriaMap := make(map[string]string)
for _, path := range files {
filename := filepath.Base(path)
// Skip base.yaml - it doesn't have criteria
if filename == filepath.Base(baseYAMLFile) {
continue
}
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
// Create criteria key
c := metadata.Spec.Criteria
key := fmt.Sprintf("service=%s,accelerator=%s,os=%s,intent=%s,platform=%s",
c.Service, c.Accelerator, c.OS, c.Intent, c.Platform)
if existing, found := criteriaMap[key]; found {
t.Errorf("duplicate criteria found:\n %s: %s\n %s: %s",
existing, key, filename, key)
}
criteriaMap[key] = filename
}
}
// ============================================================================
// Merge Consistency Tests
// ============================================================================
// TestBaseAndOverlaysMergeWithoutConflict verifies that each overlay
// can be merged with base without errors.
func TestBaseAndOverlaysMergeWithoutConflict(t *testing.T) {
// Load base
baseContent, err := GetEmbeddedFS().ReadFile(baseYAMLFile)
if err != nil {
t.Fatalf("failed to read %s: %v", baseYAMLFile, err)
}
var baseMetadata RecipeMetadata
if err := yaml.Unmarshal(baseContent, &baseMetadata); err != nil {
t.Fatalf("failed to parse %s: %v", baseYAMLFile, err)
}
files := collectMetadataFiles(t)
for _, path := range files {
filename := filepath.Base(path)
if filename == filepath.Base(baseYAMLFile) {
continue
}
t.Run(filename, func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var overlayMetadata RecipeMetadata
if err := yaml.Unmarshal(content, &overlayMetadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
// Create a copy of base spec for merging
mergedSpec := baseMetadata.Spec
// Attempt merge (Merge doesn't return error, panics on nil)
mergedSpec.Merge(&overlayMetadata.Spec)
// Verify merge produced valid result
if len(mergedSpec.ComponentRefs) == 0 {
t.Error("merged spec has no component refs")
}
})
}
}
// TestMergedRecipesHaveNoCycles verifies that after merging base + overlay,
// the resulting recipe has no circular dependencies.
func TestMergedRecipesHaveNoCycles(t *testing.T) {
// Load base
baseContent, err := GetEmbeddedFS().ReadFile(baseYAMLFile)
if err != nil {
t.Fatalf("failed to read %s: %v", baseYAMLFile, err)
}
var baseMetadata RecipeMetadata
if err := yaml.Unmarshal(baseContent, &baseMetadata); err != nil {
t.Fatalf("failed to parse %s: %v", baseYAMLFile, err)
}
files := collectMetadataFiles(t)
for _, path := range files {
filename := filepath.Base(path)
if filename == filepath.Base(baseYAMLFile) {
continue
}
t.Run(filename, func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var overlayMetadata RecipeMetadata
if err := yaml.Unmarshal(content, &overlayMetadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
// Create a copy of base spec for merging
mergedSpec := baseMetadata.Spec
// Merge overlay
mergedSpec.Merge(&overlayMetadata.Spec)
// Validate no cycles in merged result
if err := mergedSpec.ValidateDependencies(); err != nil {
t.Errorf("merged recipe has dependency issues: %v", err)
}
})
}
}
// ============================================================================
// Values File Parsing Tests
// ============================================================================
// TestAllValuesFilesParseAsValidYAML ensures all component values files
// are valid YAML.
func TestAllValuesFilesParseAsValidYAML(t *testing.T) {
valuesFiles := collectValuesFiles(t)
for path := range valuesFiles {
t.Run(path, func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
// Parse as generic YAML to verify syntax
var parsed any
if err := yaml.Unmarshal(content, &parsed); err != nil {
t.Errorf("failed to parse values file as YAML: %v", err)
}
})
}
}
// ============================================================================
// Base Recipe Validation Tests
// ============================================================================
// TestBaseRecipeValidation verifies the base recipe passes all validations.
func TestBaseRecipeValidation(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(baseYAMLFile)
if err != nil {
t.Fatalf("failed to read %s: %v", baseYAMLFile, err)
}
var metadata RecipeMetadata
if parseErr := yaml.Unmarshal(content, &metadata); parseErr != nil {
t.Fatalf("failed to parse %s: %v", baseYAMLFile, parseErr)
}
// Validate dependencies
if depErr := metadata.Spec.ValidateDependencies(); depErr != nil {
t.Errorf("base recipe dependency validation failed: %v", depErr)
}
// Validate topological sort works
order, sortErr := metadata.Spec.TopologicalSort()
if sortErr != nil {
t.Errorf("base recipe topological sort failed: %v", sortErr)
}
if len(order) != len(metadata.Spec.ComponentRefs) {
t.Errorf("topological sort returned %d components, expected %d",
len(order), len(metadata.Spec.ComponentRefs))
}
}
// ============================================================================
// Component Type Validation Tests
// ============================================================================
// TestAllComponentTypesValid verifies that all componentRefs use valid types.
func TestAllComponentTypesValid(t *testing.T) {
files := collectMetadataFiles(t)
validTypes := map[ComponentType]bool{
ComponentTypeHelm: true,
ComponentTypeKustomize: true,
}
for _, path := range files {
t.Run(filepath.Base(path), func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
var metadata RecipeMetadata
if err := yaml.Unmarshal(content, &metadata); err != nil {
t.Fatalf("failed to parse %s: %v", path, err)
}
for _, comp := range metadata.Spec.ComponentRefs {
if comp.Type == "" {
t.Errorf("componentRef %q missing type field", comp.Name)
continue
}
if !validTypes[comp.Type] {
t.Errorf("componentRef %q has invalid type %q; valid types: Helm, Kustomize",
comp.Name, comp.Type)
}
}
})
}
}
// ============================================================================
// Manifest Helm Hooks Validation Tests
// ============================================================================
// standardK8sAPIVersions returns the set of Kubernetes API versions that don't require CRDs.
// Resources with these apiVersions don't need Helm hook annotations.
// The list is derived from k8s.io/client-go/kubernetes/scheme which contains all standard K8s types.
var standardK8sAPIVersions = func() map[string]bool {
versions := make(map[string]bool)
for gv := range scheme.Scheme.AllKnownTypes() {
// Format: "group/version" or just "version" for core API
var apiVersion string
if gv.Group == "" {
apiVersion = gv.Version // e.g., "v1"
} else {
apiVersion = gv.Group + "/" + gv.Version // e.g., "apps/v1"
}
versions[apiVersion] = true
}
return versions
}()
// TestManifestHelmHooksRequired validates that CRD-dependent manifests
// have the required Helm hook annotations for proper deployment ordering.
//
// Custom Resources (CRs) depend on CRDs installed by sub-charts. Without
// Helm hooks, the CR may be applied before its CRD exists, causing installation
// failures. This test ensures manifest authors add the required annotations.
//
// Required annotations for CRD-dependent resources:
//
// metadata:
// annotations:
// "helm.sh/hook": post-install,post-upgrade
// "helm.sh/hook-weight": "10"
// "helm.sh/hook-delete-policy": before-hook-creation
//
// To opt-out (not recommended), add:
//
// metadata:
// annotations:
// aicr/skip-hook-validation: "true"
func TestManifestHelmHooksRequired(t *testing.T) {
// Patterns to extract apiVersion and check for annotations
// Using regex to avoid YAML parsing issues with Helm template syntax
apiVersionPattern := regexp.MustCompile(`(?m)^apiVersion:\s*(\S+)`)
helmHookPattern := regexp.MustCompile(`(?m)["']?helm\.sh/hook["']?:\s*`)
skipValidationPattern := regexp.MustCompile(`(?m)["']?aicr/skip-hook-validation["']?:\s*["']?true["']?`)
manifestFiles := collectManifestFiles(t)
if len(manifestFiles) == 0 {
t.Log("no manifest files found in components/*/manifests/")
return
}
for _, path := range manifestFiles {
t.Run(filepath.Base(path), func(t *testing.T) {
content, err := GetEmbeddedFS().ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
contentStr := string(content)
// Extract apiVersion
matches := apiVersionPattern.FindStringSubmatch(contentStr)
if len(matches) < 2 {
t.Logf("no apiVersion found in %s, skipping", path)
return
}
apiVersion := matches[1]
// Check if this is a standard K8s API (no hooks needed)
if isStandardK8sAPI(apiVersion) {
return // Standard K8s resource, no hooks required
}
// This is a CRD-dependent resource - check for required annotations
// Check for opt-out annotation
if skipValidationPattern.MatchString(contentStr) {
t.Logf("%s has aicr/skip-hook-validation annotation, skipping validation", path)
return
}
// Check for helm.sh/hook annotation
if !helmHookPattern.MatchString(contentStr) {
t.Errorf(`manifest %q has custom apiVersion %q but is missing required Helm hook annotations.
CRD-dependent resources must include these annotations to ensure proper deployment ordering:
metadata:
annotations:
"helm.sh/hook": post-install,post-upgrade
"helm.sh/hook-weight": "10"
"helm.sh/hook-delete-policy": before-hook-creation
To skip this validation (not recommended), add:
metadata:
annotations:
aicr/skip-hook-validation: "true"
`, filepath.Base(path), apiVersion)
}
})
}
}
// TestManifestHelmHooksValidation tests the validation logic with controlled inputs
// to ensure missing annotations are caught and skip annotations work correctly.
func TestManifestHelmHooksValidation(t *testing.T) {
apiVersionPattern := regexp.MustCompile(`(?m)^apiVersion:\s*(\S+)`)
helmHookPattern := regexp.MustCompile(`(?m)["']?helm\.sh/hook["']?:\s*`)
skipValidationPattern := regexp.MustCompile(`(?m)["']?aicr/skip-hook-validation["']?:\s*["']?true["']?`)
tests := []struct {
name string
content string
expectError bool
}{
{
name: "custom_resource_missing_hooks_should_fail",
content: `apiVersion: skyhook.nvidia.com/v1alpha1
kind: Recipe