-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathbase_test.go
More file actions
654 lines (567 loc) · 15.8 KB
/
base_test.go
File metadata and controls
654 lines (567 loc) · 15.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
// 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"
"strings"
"testing"
"time"
"github.com/NVIDIA/aicr/pkg/bundler/config"
"github.com/NVIDIA/aicr/pkg/bundler/types"
)
func TestNewBaseBundler(t *testing.T) {
tests := []struct {
name string
config *config.Config
bundlerType types.BundleType
wantNilCfg bool
}{
{
name: "with config",
config: config.NewConfig(),
bundlerType: types.BundleType("gpu-operator"),
wantNilCfg: false,
},
{
name: "nil config creates default",
config: nil,
bundlerType: types.BundleType("gpu-operator"),
wantNilCfg: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := NewBaseBundler(tt.config, tt.bundlerType)
if b == nil {
t.Fatal("NewBaseBundler() returned nil")
}
if b.Config == nil {
t.Error("NewBaseBundler() Config is nil")
}
if b.Result == nil {
t.Error("NewBaseBundler() Result is nil")
}
if b.Result.Type != tt.bundlerType {
t.Errorf("Result.Type = %v, want %v", b.Result.Type, tt.bundlerType)
}
})
}
}
func TestBaseBundler_CreateBundleDir(t *testing.T) {
tmpDir := t.TempDir()
b := NewBaseBundler(nil, types.BundleType("gpu-operator"))
dirs, err := b.CreateBundleDir(tmpDir, "test-bundle")
if err != nil {
t.Fatalf("CreateBundleDir() error = %v", err)
}
// Verify only the root directory is created (subdirectories created on-demand)
if _, err := os.Stat(dirs.Root); os.IsNotExist(err) {
t.Errorf("Root directory %s was not created", dirs.Root)
}
// Verify subdirectories are NOT created yet (created on-demand when writing files)
for _, dir := range []string{dirs.Scripts, dirs.Manifests} {
if _, err := os.Stat(dir); !os.IsNotExist(err) {
t.Errorf("Subdirectory %s should not exist yet (created on-demand)", dir)
}
}
// Verify directory paths are correct
if dirs.Root != filepath.Join(tmpDir, "test-bundle") {
t.Errorf("Root dir = %s, want %s", dirs.Root, filepath.Join(tmpDir, "test-bundle"))
}
if dirs.Scripts != filepath.Join(dirs.Root, "scripts") {
t.Errorf("Scripts dir = %s, want %s", dirs.Scripts, filepath.Join(dirs.Root, "scripts"))
}
if dirs.Manifests != filepath.Join(dirs.Root, "manifests") {
t.Errorf("Manifests dir = %s, want %s", dirs.Manifests, filepath.Join(dirs.Root, "manifests"))
}
}
func TestBaseBundler_WriteFile(t *testing.T) {
tmpDir := t.TempDir()
b := NewBaseBundler(nil, types.BundleType("gpu-operator"))
testFile := filepath.Join(tmpDir, "test.txt")
content := []byte("test content")
err := b.WriteFile(testFile, content, 0644)
if err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
// Verify file was created
if _, statErr := os.Stat(testFile); os.IsNotExist(statErr) {
t.Error("File was not created")
}
// Verify content
readContent, err := os.ReadFile(testFile)
if err != nil {
t.Fatalf("Failed to read file: %v", err)
}
if string(readContent) != string(content) {
t.Errorf("File content = %s, want %s", readContent, content)
}
// Verify result was updated
if len(b.Result.Files) != 1 {
t.Errorf("Result.Files length = %d, want 1", len(b.Result.Files))
}
if b.Result.Size != int64(len(content)) {
t.Errorf("Result.Size = %d, want %d", b.Result.Size, len(content))
}
}
func TestBaseBundler_WriteFileString(t *testing.T) {
tmpDir := t.TempDir()
b := NewBaseBundler(nil, types.BundleType("gpu-operator"))
testFile := filepath.Join(tmpDir, "test.txt")
content := "test string content"
err := b.WriteFileString(testFile, content, 0644)
if err != nil {
t.Fatalf("WriteFileString() error = %v", err)
}
// Verify file was created with correct content
readContent, err := os.ReadFile(testFile)
if err != nil {
t.Fatalf("Failed to read file: %v", err)
}
if string(readContent) != content {
t.Errorf("File content = %s, want %s", readContent, content)
}
}
func TestBaseBundler_RenderTemplate(t *testing.T) {
b := NewBaseBundler(nil, types.BundleType("gpu-operator"))
tests := []struct {
name string
tmpl string
data any
want string
wantErr bool
}{
{
name: "simple template",
tmpl: "Hello, {{.Name}}!",
data: map[string]string{"Name": "World"},
want: "Hello, World!",
},
{
name: "template with iteration",
tmpl: "{{range .Items}}{{.}} {{end}}",
data: map[string][]string{"Items": {"a", "b", "c"}},
want: "a b c ",
},
{
name: "invalid template",
tmpl: "{{.Invalid",
data: map[string]string{},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := b.RenderTemplate(tt.tmpl, tt.name, tt.data)
if (err != nil) != tt.wantErr {
t.Errorf("RenderTemplate() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && got != tt.want {
t.Errorf("RenderTemplate() = %q, want %q", got, tt.want)
}
})
}
}
func TestBaseBundler_RenderAndWriteTemplate(t *testing.T) {
tmpDir := t.TempDir()
b := NewBaseBundler(nil, types.BundleType("gpu-operator"))
tmpl := "Hello, {{.Name}}!"
data := map[string]string{"Name": "World"}
outputPath := filepath.Join(tmpDir, "output.txt")
err := b.RenderAndWriteTemplate(tmpl, "test", outputPath, data, 0644)
if err != nil {
t.Fatalf("RenderAndWriteTemplate() error = %v", err)
}
// Verify file content
content, err := os.ReadFile(outputPath)
if err != nil {
t.Fatalf("Failed to read file: %v", err)
}
want := "Hello, World!"
if string(content) != want {
t.Errorf("File content = %s, want %s", content, want)
}
}
func TestBaseBundler_GenerateChecksums(t *testing.T) {
tmpDir := t.TempDir()
b := NewBaseBundler(nil, types.BundleType("gpu-operator"))
ctx := context.Background()
// Create bundle directory
bundleDir := filepath.Join(tmpDir, "test-bundle")
if err := os.MkdirAll(bundleDir, 0755); err != nil {
t.Fatalf("Failed to create bundle dir: %v", err)
}
// Write some test files
testFiles := []struct {
name string
content string
}{
{"file1.txt", "content1"},
{"file2.txt", "content2"},
}
for _, tf := range testFiles {
path := filepath.Join(bundleDir, tf.name)
if err := b.WriteFileString(path, tf.content, 0644); err != nil {
t.Fatalf("Failed to write test file: %v", err)
}
}
// Generate checksums
err := b.GenerateChecksums(ctx, bundleDir)
if err != nil {
t.Fatalf("GenerateChecksums() error = %v", err)
}
// Verify checksums file exists
checksumPath := filepath.Join(bundleDir, "checksums.txt")
if _, statErr := os.Stat(checksumPath); os.IsNotExist(statErr) {
t.Error("Checksums file was not created")
}
// Verify checksums content
content, err := os.ReadFile(checksumPath)
if err != nil {
t.Fatalf("Failed to read checksums: %v", err)
}
contentStr := string(content)
for _, tf := range testFiles {
if !filepath.IsAbs(tf.name) && !strings.Contains(contentStr, tf.name) {
t.Errorf("Checksums file does not contain %s", tf.name)
}
}
}
func TestBaseBundler_GenerateChecksums_ContextCancelled(t *testing.T) {
tmpDir := t.TempDir()
b := NewBaseBundler(nil, types.BundleType("gpu-operator"))
ctx, cancel := context.WithCancel(context.Background())
cancel() // Cancel immediately
err := b.GenerateChecksums(ctx, tmpDir)
if err == nil {
t.Error("GenerateChecksums() should return error for cancelled context")
}
}
func TestBaseBundler_MakeExecutable(t *testing.T) {
tests := []struct {
name string
setup func(t *testing.T) string
wantErr bool
wantExec bool
wantResEr bool
}{
{
name: "valid file",
setup: func(t *testing.T) string {
t.Helper()
f := filepath.Join(t.TempDir(), "script.sh")
if err := os.WriteFile(f, []byte("#!/bin/bash\necho test"), 0644); err != nil {
t.Fatalf("setup: %v", err)
}
return f
},
wantExec: true,
},
{
name: "nonexistent file",
setup: func(t *testing.T) string {
t.Helper()
return filepath.Join(t.TempDir(), "does-not-exist.sh")
},
wantErr: true,
wantResEr: true,
},
{
name: "nonexistent directory",
setup: func(t *testing.T) string {
t.Helper()
return filepath.Join(t.TempDir(), "no-such-dir", "script.sh")
},
wantErr: true,
wantResEr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := NewBaseBundler(nil, types.BundleType("gpu-operator"))
path := tt.setup(t)
err := b.MakeExecutable(path)
if (err != nil) != tt.wantErr {
t.Errorf("MakeExecutable() error = %v, wantErr %v", err, tt.wantErr)
return
}
if tt.wantResEr && len(b.Result.Errors) == 0 {
t.Error("expected error in Result.Errors")
}
if tt.wantExec {
info, statErr := os.Stat(path)
if statErr != nil {
t.Fatalf("stat: %v", statErr)
}
if info.Mode()&0111 == 0 {
t.Error("file is not executable")
}
}
})
}
}
func TestBaseBundler_Finalize(t *testing.T) {
b := NewBaseBundler(nil, types.BundleType("gpu-operator"))
// Add some files to result
b.Result.AddFile("/tmp/file1.txt", 100)
b.Result.AddFile("/tmp/file2.txt", 200)
start := time.Now()
time.Sleep(10 * time.Millisecond) // Ensure some duration
b.Finalize(start)
if !b.Result.Success {
t.Error("Result.Success should be true after Finalize()")
}
if b.Result.Duration == 0 {
t.Error("Result.Duration should be set after Finalize()")
}
if b.Result.Duration < 10*time.Millisecond {
t.Error("Result.Duration should be at least 10ms")
}
}
func TestBaseBundler_CheckContext(t *testing.T) {
b := NewBaseBundler(nil, types.BundleType("gpu-operator"))
tests := []struct {
name string
ctx context.Context
wantErr bool
}{
{
name: "active context",
ctx: context.Background(),
wantErr: false,
},
{
name: "cancelled context",
ctx: func() context.Context {
ctx, cancel := context.WithCancel(context.Background())
cancel()
return ctx
}(),
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := b.CheckContext(tt.ctx)
if (err != nil) != tt.wantErr {
t.Errorf("CheckContext() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestBaseBundler_AddError(t *testing.T) {
b := NewBaseBundler(nil, types.BundleType("gpu-operator"))
// Add nil error - should not panic
b.AddError(nil)
if len(b.Result.Errors) != 0 {
t.Error("AddError(nil) should not add to errors")
}
// Add real error
testErr := os.ErrNotExist
b.AddError(testErr)
if len(b.Result.Errors) != 1 {
t.Errorf("Result.Errors length = %d, want 1", len(b.Result.Errors))
}
if b.Result.Errors[0] != testErr.Error() {
t.Errorf("Result.Errors[0] = %s, want %s", b.Result.Errors[0], testErr.Error())
}
}
func TestBaseBundler_buildBaseConfigMap(t *testing.T) {
cfg := config.NewConfig(
config.WithVersion("v1.2.3"),
)
b := NewBaseBundler(cfg, types.BundleType("gpu-operator"))
configMap := b.buildBaseConfigMap()
// Test bundler version is set
if configMap["bundler_version"] != "v1.2.3" {
t.Errorf("bundler_version = %s, want v1.2.3", configMap["bundler_version"])
}
}
func TestBaseBundler_GenerateFileFromTemplate(t *testing.T) {
templates := map[string]string{
"test.yaml": "name: {{.Name}}\nvalue: {{.Value}}",
}
getTemplate := func(name string) (string, bool) {
tmpl, ok := templates[name]
return tmpl, ok
}
tmpDir := t.TempDir()
b := NewBaseBundler(nil, types.BundleType("gpu-operator"))
tests := []struct {
name string
ctx context.Context
templateName string
outputPath string
data any
wantErr bool
wantContent string
}{
{
name: "successful generation",
ctx: context.Background(),
templateName: "test.yaml",
outputPath: filepath.Join(tmpDir, "test1.yaml"),
data: map[string]any{
"Name": "TestName",
"Value": "TestValue",
},
wantErr: false,
wantContent: "name: TestName\nvalue: TestValue",
},
{
name: "template not found",
ctx: context.Background(),
templateName: "missing.yaml",
outputPath: filepath.Join(tmpDir, "test2.yaml"),
data: map[string]any{},
wantErr: true,
},
{
name: "cancelled context",
ctx: func() context.Context {
ctx, cancel := context.WithCancel(context.Background())
cancel()
return ctx
}(),
templateName: "test.yaml",
outputPath: filepath.Join(tmpDir, "test3.yaml"),
data: map[string]any{},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := b.GenerateFileFromTemplate(tt.ctx, getTemplate, tt.templateName,
tt.outputPath, tt.data, 0644)
if (err != nil) != tt.wantErr {
t.Errorf("GenerateFileFromTemplate() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && tt.wantContent != "" {
content, err := os.ReadFile(tt.outputPath)
if err != nil {
t.Fatalf("Failed to read generated file: %v", err)
}
if string(content) != tt.wantContent {
t.Errorf("Generated content = %s, want %s", string(content), tt.wantContent)
}
}
})
}
}
func TestGetBundlerVersion(t *testing.T) {
tests := []struct {
name string
config map[string]string
want string
}{
{
name: "version exists",
config: map[string]string{bundlerVersionKey: "v1.2.3"},
want: "v1.2.3",
},
{
name: "version missing",
config: map[string]string{},
want: "unknown",
},
{
name: "empty version",
config: map[string]string{bundlerVersionKey: ""},
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := GetBundlerVersion(tt.config)
if got != tt.want {
t.Errorf("GetBundlerVersion() = %v, want %v", got, tt.want)
}
})
}
}
func TestGetRecipeBundlerVersion(t *testing.T) {
tests := []struct {
name string
config map[string]string
want string
}{
{
name: "version exists",
config: map[string]string{recipeBundlerVersionKey: "v2.0.0"},
want: "v2.0.0",
},
{
name: "version missing",
config: map[string]string{},
want: "unknown",
},
{
name: "with other keys",
config: map[string]string{"other": "value", recipeBundlerVersionKey: "v1.0.0"},
want: "v1.0.0",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := GetRecipeBundlerVersion(tt.config)
if got != tt.want {
t.Errorf("GetRecipeBundlerVersion() = %v, want %v", got, tt.want)
}
})
}
}
// mockRecipeInput implements the interface for BuildConfigMapFromInput.
type mockRecipeInput struct {
version string
}
func (m *mockRecipeInput) GetVersion() string {
return m.version
}
func TestBaseBundler_BuildConfigMapFromInput(t *testing.T) {
cfg := config.NewConfig(
config.WithVersion("bundler-v1.2.3"),
)
b := NewBaseBundler(cfg, types.BundleType("gpu-operator"))
tests := []struct {
name string
input *mockRecipeInput
wantKey string
wantVal string
}{
{
name: "includes recipe version",
input: &mockRecipeInput{version: "recipe-v1.0.0"},
wantKey: recipeBundlerVersionKey,
wantVal: "recipe-v1.0.0",
},
{
name: "includes bundler version",
input: &mockRecipeInput{version: "v1.0.0"},
wantKey: bundlerVersionKey,
wantVal: "bundler-v1.2.3",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := b.BuildConfigMapFromInput(tt.input)
if got[tt.wantKey] != tt.wantVal {
t.Errorf("BuildConfigMapFromInput()[%s] = %v, want %v", tt.wantKey, got[tt.wantKey], tt.wantVal)
}
})
}
}