-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtesting.go
More file actions
505 lines (449 loc) · 13.6 KB
/
testing.go
File metadata and controls
505 lines (449 loc) · 13.6 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
// Copyright (c) 2026, 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.
package component
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/NVIDIA/aicr/pkg/bundler/config"
"github.com/NVIDIA/aicr/pkg/bundler/result"
"github.com/NVIDIA/aicr/pkg/header"
"github.com/NVIDIA/aicr/pkg/measurement"
"github.com/NVIDIA/aicr/pkg/recipe"
)
// BundlerInterface defines the interface that bundlers must implement for testing.
type BundlerInterface interface {
Make(ctx context.Context, input recipe.RecipeInput, outputDir string) (*result.Result, error)
}
// TestHarness provides common testing utilities for bundlers.
type TestHarness struct {
t *testing.T
bundlerName string
expectedFiles []string
recipeBuilder func() *RecipeBuilder
}
// NewTestHarness creates a new test harness for a bundler.
func NewTestHarness(t *testing.T, bundlerName string) *TestHarness {
return &TestHarness{
t: t,
bundlerName: bundlerName,
expectedFiles: []string{},
}
}
// WithExpectedFiles sets the list of files expected to be generated.
func (h *TestHarness) WithExpectedFiles(files []string) *TestHarness {
h.expectedFiles = files
return h
}
// WithRecipeBuilder sets a custom recipe builder function.
func (h *TestHarness) WithRecipeBuilder(builder func() *RecipeBuilder) *TestHarness {
h.recipeBuilder = builder
return h
}
// TestMake tests the Make method of a bundler with standard assertions.
func (h *TestHarness) TestMake(bundler BundlerInterface) {
ctx := context.Background()
tmpDir := h.t.TempDir()
rec := h.getRecipe()
result, err := bundler.Make(ctx, rec, tmpDir)
if err != nil {
h.t.Fatalf("Make() error = %v", err)
}
h.AssertResult(result, tmpDir)
}
// AssertResult performs standard assertions on a bundler result.
func (h *TestHarness) AssertResult(result *result.Result, outputDir string) {
if result == nil {
h.t.Fatal("Make() returned nil result")
return
}
if !result.Success {
h.t.Error("Make() should succeed")
}
if len(result.Files) == 0 {
h.t.Error("Make() produced no files")
}
// Verify bundle directory structure
bundleDir := filepath.Join(outputDir, h.bundlerName)
if _, err := os.Stat(bundleDir); os.IsNotExist(err) {
h.t.Errorf("Make() did not create %s directory", h.bundlerName)
}
// Verify expected files exist
for _, file := range h.expectedFiles {
path := filepath.Join(bundleDir, file)
if _, err := os.Stat(path); os.IsNotExist(err) {
h.t.Errorf("Expected file %s not found", file)
}
}
}
// AssertFileExists checks if a file exists in the bundle directory.
func (h *TestHarness) AssertFileExists(outputDir, filename string) {
bundleDir := filepath.Join(outputDir, h.bundlerName)
path := filepath.Join(bundleDir, filename)
if _, err := os.Stat(path); os.IsNotExist(err) {
h.t.Errorf("Expected file %s not found", filename)
}
}
// getRecipe returns a test recipe, using custom builder if set.
func (h *TestHarness) getRecipe() *recipe.Recipe {
if h.recipeBuilder != nil {
return h.recipeBuilder().Build()
}
return h.createDefaultRecipe()
}
// createDefaultRecipe creates a basic recipe for testing.
func (h *TestHarness) createDefaultRecipe() *recipe.Recipe {
r := &recipe.Recipe{
Measurements: []*measurement.Measurement{
{
Type: measurement.TypeK8s,
Subtypes: []measurement.Subtype{
{
Name: "config",
Data: map[string]measurement.Reading{
"version": measurement.Str("1.28.0"),
},
},
},
},
},
}
r.Init(header.KindRecipe, recipe.RecipeAPIVersion, "test")
return r
}
// TestTemplateGetter tests a template getter function.
func TestTemplateGetter(t *testing.T, getTemplate func(string) (string, bool), expectedTemplates []string) {
for _, name := range expectedTemplates {
t.Run(name, func(t *testing.T) {
tmpl, ok := getTemplate(name)
if !ok {
t.Errorf("GetTemplate(%s) not found", name)
}
if tmpl == "" {
t.Errorf("GetTemplate(%s) returned empty template", name)
}
})
}
// Test non-existent template
t.Run("nonexistent", func(t *testing.T) {
_, ok := getTemplate("nonexistent")
if ok {
t.Error("GetTemplate() should return false for non-existent template")
}
})
}
// RecipeBuilder helps build test recipes with fluent API.
type RecipeBuilder struct {
measurements []*measurement.Measurement
}
// NewRecipeBuilder creates a new recipe builder.
func NewRecipeBuilder() *RecipeBuilder {
return &RecipeBuilder{
measurements: []*measurement.Measurement{},
}
}
// WithK8sMeasurement adds a K8s measurement with the given subtypes.
func (rb *RecipeBuilder) WithK8sMeasurement(subtypes ...measurement.Subtype) *RecipeBuilder {
rb.measurements = append(rb.measurements, &measurement.Measurement{
Type: measurement.TypeK8s,
Subtypes: subtypes,
})
return rb
}
// WithGPUMeasurement adds a GPU measurement with the given subtypes.
func (rb *RecipeBuilder) WithGPUMeasurement(subtypes ...measurement.Subtype) *RecipeBuilder {
rb.measurements = append(rb.measurements, &measurement.Measurement{
Type: measurement.TypeGPU,
Subtypes: subtypes,
})
return rb
}
// WithOSMeasurement adds an OS measurement with the given subtypes.
func (rb *RecipeBuilder) WithOSMeasurement(subtypes ...measurement.Subtype) *RecipeBuilder {
rb.measurements = append(rb.measurements, &measurement.Measurement{
Type: measurement.TypeOS,
Subtypes: subtypes,
})
return rb
}
// WithSystemDMeasurement adds a SystemD measurement with the given subtypes.
func (rb *RecipeBuilder) WithSystemDMeasurement(subtypes ...measurement.Subtype) *RecipeBuilder {
rb.measurements = append(rb.measurements, &measurement.Measurement{
Type: measurement.TypeSystemD,
Subtypes: subtypes,
})
return rb
}
// Build creates the recipe.
func (rb *RecipeBuilder) Build() *recipe.Recipe {
r := &recipe.Recipe{
Measurements: rb.measurements,
}
r.Init(header.KindRecipe, recipe.RecipeAPIVersion, "test")
return r
}
// ImageSubtype creates an image subtype with common image data.
func ImageSubtype(images map[string]string) measurement.Subtype {
data := make(map[string]measurement.Reading)
for k, v := range images {
data[k] = measurement.Str(v)
}
return measurement.Subtype{
Name: "image",
Data: data,
}
}
// ConfigSubtype creates a config subtype with common config data.
func ConfigSubtype(configs map[string]any) measurement.Subtype {
data := make(map[string]measurement.Reading)
for k, v := range configs {
switch val := v.(type) {
case string:
data[k] = measurement.Str(val)
case bool:
data[k] = measurement.Bool(val)
case int:
data[k] = measurement.Int(val)
case float64:
data[k] = measurement.Float64(val)
}
}
return measurement.Subtype{
Name: "config",
Data: data,
}
}
// SMISubtype creates an SMI subtype for GPU measurements.
func SMISubtype(data map[string]string) measurement.Subtype {
readings := make(map[string]measurement.Reading)
for k, v := range data {
readings[k] = measurement.Str(v)
}
return measurement.Subtype{
Name: "smi",
Data: readings,
}
}
// TestValidateRecipe is a reusable test for recipe validation.
func TestValidateRecipe(t *testing.T, validateFunc func(*recipe.Recipe) error) {
tests := []struct {
name string
recipe *recipe.Recipe
wantErr bool
}{
{
name: "nil recipe",
recipe: nil,
wantErr: true,
},
{
name: "empty measurements",
recipe: &recipe.Recipe{
Measurements: []*measurement.Measurement{},
},
wantErr: true,
},
{
name: "valid recipe",
recipe: NewRecipeBuilder().
WithK8sMeasurement(ConfigSubtype(map[string]any{
"version": "1.28.0",
})).
Build(),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateFunc(tt.recipe)
if (err != nil) != tt.wantErr {
t.Errorf("validateRecipe() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
// AssertConfigValue checks if a config value matches the expected value.
func AssertConfigValue(t *testing.T, config map[string]string, key, expected string) {
t.Helper()
if val, ok := config[key]; !ok {
t.Errorf("Config missing key %s", key)
} else if val != expected {
t.Errorf("Config[%s] = %s, want %s", key, val, expected)
}
}
// BundlerFactory is a function that creates a new bundler instance.
type BundlerFactory func(*config.Config) BundlerInterface
// StandardBundlerTestConfig holds configuration for running standard bundler tests.
type StandardBundlerTestConfig struct {
// ComponentName is the name of the component (e.g., "cert-manager").
ComponentName string
// NewBundler creates a new bundler instance.
NewBundler BundlerFactory
// GetTemplate is the template getter function.
GetTemplate TemplateFunc
// ExpectedTemplates lists templates that should be available (e.g., ["README.md"]).
ExpectedTemplates []string
// ExpectedFiles lists files that should be generated (e.g., ["values.yaml", "README.md"]).
ExpectedFiles []string
// DefaultOverrides are the default values to use in test recipes.
DefaultOverrides map[string]any
}
// RunStandardBundlerTests runs all standard tests for a bundler.
// This includes TestNewBundler, TestBundler_Make, and TestGetTemplate.
// Use this to reduce test boilerplate in bundler packages.
//
// Example usage:
//
// func TestBundler(t *testing.T) {
// internal.RunStandardBundlerTests(t, internal.StandardBundlerTestConfig{
// ComponentName: "cert-manager",
// NewBundler: func(cfg *config.Config) internal.BundlerInterface { return NewBundler(cfg) },
// GetTemplate: GetTemplate,
// ExpectedTemplates: []string{"README.md"},
// ExpectedFiles: []string{"values.yaml", "README.md", "checksums.txt"},
// })
// }
func RunStandardBundlerTests(t *testing.T, cfg StandardBundlerTestConfig) {
t.Run("NewBundler", func(t *testing.T) {
runNewBundlerTests(t, cfg)
})
t.Run("Make", func(t *testing.T) {
runMakeTests(t, cfg)
})
if cfg.GetTemplate != nil && len(cfg.ExpectedTemplates) > 0 {
t.Run("GetTemplate", func(t *testing.T) {
TestTemplateGetter(t, cfg.GetTemplate, cfg.ExpectedTemplates)
})
}
}
// runNewBundlerTests tests bundler creation.
func runNewBundlerTests(t *testing.T, cfg StandardBundlerTestConfig) {
tests := []struct {
name string
cfg *config.Config
}{
{
name: "with nil config",
cfg: nil,
},
{
name: "with valid config",
cfg: config.NewConfig(),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := cfg.NewBundler(tt.cfg)
if b == nil {
t.Fatal("NewBundler() returned nil")
}
})
}
}
// runMakeTests tests the Make method with various inputs.
func runMakeTests(t *testing.T, cfg StandardBundlerTestConfig) {
tests := []struct {
name string
recipe *recipe.RecipeResult
wantErr bool
verifyFunc func(t *testing.T, outputDir string)
}{
{
name: "valid recipe with component",
recipe: createStandardTestRecipeResult(cfg.ComponentName, cfg.DefaultOverrides),
wantErr: false,
verifyFunc: func(t *testing.T, outputDir string) {
bundleDir := filepath.Join(outputDir, cfg.ComponentName)
for _, file := range cfg.ExpectedFiles {
path := filepath.Join(bundleDir, file)
if _, err := os.Stat(path); os.IsNotExist(err) {
t.Errorf("Expected file %s not found", file)
}
}
},
},
{
name: "missing component",
recipe: createRecipeResultWithoutComponent(cfg.ComponentName),
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpDir := t.TempDir()
b := cfg.NewBundler(nil)
ctx := context.Background()
result, err := b.Make(ctx, tt.recipe, tmpDir)
if (err != nil) != tt.wantErr {
t.Errorf("Make() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr {
if result == nil {
t.Error("Make() returned nil result")
return
}
if len(result.Files) == 0 {
t.Error("Make() returned no files")
}
if tt.verifyFunc != nil {
tt.verifyFunc(t, tmpDir)
}
}
})
}
}
// createStandardTestRecipeResult creates a test RecipeResult with the given component.
func createStandardTestRecipeResult(componentName string, overrides map[string]any) *recipe.RecipeResult {
if overrides == nil {
overrides = map[string]any{
"operator": map[string]any{
"version": "v25.3.4",
},
}
}
return &recipe.RecipeResult{
Kind: "RecipeResult",
APIVersion: recipe.RecipeAPIVersion,
ComponentRefs: []recipe.ComponentRef{
{
Name: componentName,
Type: "Helm",
Source: "https://helm.ngc.nvidia.com/nvidia",
Version: "v25.3.4",
Overrides: overrides,
},
},
}
}
// createRecipeResultWithoutComponent creates a RecipeResult without the specified component.
func createRecipeResultWithoutComponent(componentName string) *recipe.RecipeResult {
// Use a different component name to simulate missing component
otherName := "other-component"
if componentName == otherName {
otherName = "different-component"
}
return &recipe.RecipeResult{
Kind: "RecipeResult",
APIVersion: recipe.RecipeAPIVersion,
ComponentRefs: []recipe.ComponentRef{
{
Name: otherName,
Type: "Helm",
Version: "v1.0.0",
},
},
}
}