-
-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathworkflow_utils_test.go
More file actions
1702 lines (1515 loc) · 51.6 KB
/
workflow_utils_test.go
File metadata and controls
1702 lines (1515 loc) · 51.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
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 exec
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"mvdan.cc/sh/v3/shell"
errUtils "github.com/cloudposse/atmos/errors"
cfg "github.com/cloudposse/atmos/pkg/config"
"github.com/cloudposse/atmos/pkg/schema"
)
// TestIsKnownWorkflowError tests the IsKnownWorkflowError function.
func TestIsKnownWorkflowError(t *testing.T) {
tests := []struct {
name string
err error
expected bool
}{
{
name: "nil error",
err: nil,
expected: false,
},
{
name: "ErrWorkflowNoSteps",
err: errUtils.ErrWorkflowNoSteps,
expected: true,
},
{
name: "ErrInvalidWorkflowStepType",
err: errUtils.ErrInvalidWorkflowStepType,
expected: true,
},
{
name: "ErrInvalidFromStep",
err: errUtils.ErrInvalidFromStep,
expected: true,
},
{
name: "ErrWorkflowStepFailed",
err: errUtils.ErrWorkflowStepFailed,
expected: true,
},
{
name: "ErrWorkflowNoWorkflow",
err: errUtils.ErrWorkflowNoWorkflow,
expected: true,
},
{
name: "ErrWorkflowFileNotFound",
err: errUtils.ErrWorkflowFileNotFound,
expected: true,
},
{
name: "ErrInvalidWorkflowManifest",
err: errUtils.ErrInvalidWorkflowManifest,
expected: true,
},
{
name: "wrapped known error",
err: errors.Join(errUtils.ErrWorkflowNoSteps, errors.New("additional context")),
expected: true,
},
{
name: "unknown error",
err: errors.New("some random error"),
expected: false,
},
{
name: "wrapped unknown error",
err: errors.Join(errors.New("unknown"), errors.New("more context")),
expected: false,
},
{
name: "ExitCodeError is known",
err: errUtils.ExitCodeError{Code: 1},
expected: true,
},
{
name: "wrapped ExitCodeError is known",
err: errors.Join(errors.New("wrapper"), errUtils.ExitCodeError{Code: 2}),
expected: true,
},
{
name: "ErrorBuilder wrapped error is known",
err: errUtils.Build(errUtils.ErrWorkflowNoSteps).
WithExplanationf("Workflow %s is empty", "test").
Err(),
expected: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := IsKnownWorkflowError(tt.err)
assert.Equal(t, tt.expected, result)
})
}
}
// TestCheckAndMergeDefaultIdentity tests the checkAndMergeDefaultIdentity function.
func TestCheckAndMergeDefaultIdentity(t *testing.T) {
tests := []struct {
name string
atmosConfig *schema.AtmosConfiguration
expectedResult bool
}{
{
name: "no identities configured",
atmosConfig: &schema.AtmosConfiguration{
Auth: schema.AuthConfig{
Identities: map[string]schema.Identity{},
},
},
expectedResult: false,
},
{
name: "identities without default",
atmosConfig: &schema.AtmosConfiguration{
Auth: schema.AuthConfig{
Identities: map[string]schema.Identity{
"test-identity": {
Kind: "aws/assume-role",
Default: false,
},
},
},
},
expectedResult: false,
},
{
name: "identity with default true",
atmosConfig: &schema.AtmosConfiguration{
Auth: schema.AuthConfig{
Identities: map[string]schema.Identity{
"test-identity": {
Kind: "aws/assume-role",
Default: true,
},
},
},
},
expectedResult: true,
},
{
name: "multiple identities one with default",
atmosConfig: &schema.AtmosConfiguration{
Auth: schema.AuthConfig{
Identities: map[string]schema.Identity{
"identity-1": {
Kind: "aws/assume-role",
Default: false,
},
"identity-2": {
Kind: "aws/assume-role",
Default: true,
},
},
},
},
expectedResult: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := checkAndMergeDefaultIdentity(tt.atmosConfig)
assert.Equal(t, tt.expectedResult, result)
})
}
}
// TestCheckAndMergeDefaultIdentity_WithStackLoading tests checkAndMergeDefaultIdentity with stack file loading.
func TestCheckAndMergeDefaultIdentity_WithStackLoading(t *testing.T) {
// Create a temporary directory with stack files.
tmpDir := t.TempDir()
// Create a stack file with default identity.
stacksDir := filepath.Join(tmpDir, "stacks")
err := os.MkdirAll(stacksDir, 0o755)
assert.NoError(t, err)
stackContent := `auth:
identities:
stack-default-identity:
default: true
`
err = os.WriteFile(filepath.Join(stacksDir, "_defaults.yaml"), []byte(stackContent), 0o644)
assert.NoError(t, err)
// Create atmos config with identity but no default.
atmosConfig := &schema.AtmosConfiguration{
BasePath: tmpDir,
Auth: schema.AuthConfig{
Identities: map[string]schema.Identity{
"stack-default-identity": {
Kind: "aws/assume-role",
Default: false, // Not default in atmos.yaml.
},
},
},
IncludeStackAbsolutePaths: []string{filepath.Join(stacksDir, "*.yaml")},
}
// checkAndMergeDefaultIdentity should load stack files and find the default.
result := checkAndMergeDefaultIdentity(atmosConfig)
assert.True(t, result)
// Verify that the identity was updated to have default=true.
identity, exists := atmosConfig.Auth.Identities["stack-default-identity"]
assert.True(t, exists)
assert.True(t, identity.Default)
}
// TestCheckAndMergeDefaultIdentity_LoadError tests behavior when stack loading fails.
func TestCheckAndMergeDefaultIdentity_LoadError(t *testing.T) {
// Use a platform-neutral malformed glob pattern that will cause glob to return error.
tmpDir := t.TempDir()
invalidGlobPath := filepath.Join(tmpDir, "does-not-exist", "[invalid")
// Create config with invalid include paths (will cause load to return error).
atmosConfig := &schema.AtmosConfiguration{
Auth: schema.AuthConfig{
Identities: map[string]schema.Identity{
"test-identity": {
Kind: "aws/assume-role",
Default: true, // Has default in atmos.yaml.
},
},
},
// Invalid glob pattern that will cause glob to return error.
IncludeStackAbsolutePaths: []string{invalidGlobPath},
}
// Should still return true because atmos.yaml has a default.
result := checkAndMergeDefaultIdentity(atmosConfig)
assert.True(t, result)
}
// TestCheckAndMergeDefaultIdentity_LoadErrorNoDefault tests behavior when stack loading fails and no default in atmos.yaml.
func TestCheckAndMergeDefaultIdentity_LoadErrorNoDefault(t *testing.T) {
// Use a platform-neutral malformed glob pattern that will cause glob to return error.
tmpDir := t.TempDir()
invalidGlobPath := filepath.Join(tmpDir, "does-not-exist", "[invalid")
// Create config with invalid include paths and no default in atmos.yaml.
atmosConfig := &schema.AtmosConfiguration{
Auth: schema.AuthConfig{
Identities: map[string]schema.Identity{
"test-identity": {
Kind: "aws/assume-role",
Default: false, // No default in atmos.yaml.
},
},
},
// Invalid glob pattern that will cause glob to return error.
IncludeStackAbsolutePaths: []string{invalidGlobPath},
}
// Should return false because no default anywhere.
result := checkAndMergeDefaultIdentity(atmosConfig)
assert.False(t, result)
}
// TestCheckAndMergeDefaultIdentity_StackNoDefaults tests with stack files that have no defaults.
func TestCheckAndMergeDefaultIdentity_StackNoDefaults(t *testing.T) {
// Create a temporary directory with stack files that have no defaults.
tmpDir := t.TempDir()
// Create a stack file without default identity.
stacksDir := filepath.Join(tmpDir, "stacks")
err := os.MkdirAll(stacksDir, 0o755)
assert.NoError(t, err)
stackContent := `auth:
identities:
some-identity:
kind: aws/assume-role
`
err = os.WriteFile(filepath.Join(stacksDir, "_defaults.yaml"), []byte(stackContent), 0o644)
assert.NoError(t, err)
// Create atmos config with identity but no default.
atmosConfig := &schema.AtmosConfiguration{
BasePath: tmpDir,
Auth: schema.AuthConfig{
Identities: map[string]schema.Identity{
"test-identity": {
Kind: "aws/assume-role",
Default: false,
},
},
},
IncludeStackAbsolutePaths: []string{filepath.Join(stacksDir, "*.yaml")},
}
// Should return false because no default in either atmos.yaml or stack configs.
result := checkAndMergeDefaultIdentity(atmosConfig)
assert.False(t, result)
}
// TestCheckAndMergeDefaultIdentity_EmptyStackDefaults tests with empty stack defaults.
func TestCheckAndMergeDefaultIdentity_EmptyStackDefaults(t *testing.T) {
// Create a temporary directory with empty stack files.
tmpDir := t.TempDir()
// Create an empty stack file.
stacksDir := filepath.Join(tmpDir, "stacks")
err := os.MkdirAll(stacksDir, 0o755)
assert.NoError(t, err)
stackContent := `# Empty stack file
`
err = os.WriteFile(filepath.Join(stacksDir, "_defaults.yaml"), []byte(stackContent), 0o644)
assert.NoError(t, err)
// Create atmos config with identity but no default.
atmosConfig := &schema.AtmosConfiguration{
BasePath: tmpDir,
Auth: schema.AuthConfig{
Identities: map[string]schema.Identity{
"test-identity": {
Kind: "aws/assume-role",
Default: false,
},
},
},
IncludeStackAbsolutePaths: []string{filepath.Join(stacksDir, "*.yaml")},
}
// Should return false because no default anywhere.
result := checkAndMergeDefaultIdentity(atmosConfig)
assert.False(t, result)
}
// TestKnownWorkflowErrorsSlice tests that the KnownWorkflowErrors slice is properly defined.
func TestKnownWorkflowErrorsSlice(t *testing.T) {
// Verify all expected errors are in the slice.
expectedErrors := []error{
errUtils.ErrWorkflowNoSteps,
errUtils.ErrInvalidWorkflowStepType,
errUtils.ErrInvalidFromStep,
errUtils.ErrWorkflowStepFailed,
errUtils.ErrWorkflowNoWorkflow,
errUtils.ErrWorkflowFileNotFound,
errUtils.ErrInvalidWorkflowManifest,
}
assert.Equal(t, len(expectedErrors), len(KnownWorkflowErrors))
for _, expected := range expectedErrors {
found := false
for _, actual := range KnownWorkflowErrors {
if errors.Is(expected, actual) {
found = true
break
}
}
assert.True(t, found, "Expected error %v to be in KnownWorkflowErrors", expected)
}
}
// TestWorkflowErrTitle tests the error title constant.
func TestWorkflowErrTitle(t *testing.T) {
assert.Equal(t, "Workflow Error", WorkflowErrTitle)
}
// TestStringsFieldsQuotedArguments documents the historical issue with strings.Fields().
// It demonstrates why shell.Fields() from mvdan.cc/sh is used instead for workflow commands.
// Multi-component flags like --query with quoted expressions were incorrectly split.
func TestStringsFieldsQuotedArguments(t *testing.T) {
// This test documents why strings.Fields() is NOT used for workflow command parsing.
// The production code in pkg/workflow/executor.go uses shell.Fields() instead.
command := "terraform plan --query '.metadata.component == \"gcp/compute/v0.2.0\"' -s dev"
// strings.Fields incorrectly splits quoted expressions.
stringsFieldsResult := strings.Fields(command)
// The quoted expression is broken into multiple parts (incorrect).
assert.Contains(t, stringsFieldsResult, "'.metadata.component")
assert.Contains(t, stringsFieldsResult, "==")
assert.Contains(t, stringsFieldsResult, "\"gcp/compute/v0.2.0\"'")
// shell.Fields correctly preserves quoted expressions.
shellFieldsResult, err := shell.Fields(command, nil)
assert.NoError(t, err)
// The quoted expression is preserved as a single argument (correct).
assert.Contains(t, shellFieldsResult, ".metadata.component == \"gcp/compute/v0.2.0\"")
}
// TestShellFieldsCorrectParsing verifies that shell.Fields() from mvdan.cc/sh correctly parses.
// It tests workflow commands with quoted arguments that would break with strings.Fields().
// This is the fix for the multi-component operation issue.
func TestShellFieldsCorrectParsing(t *testing.T) {
tests := []struct {
name string
command string
expectedArgs []string
}{
{
name: "query with single-quoted expression containing spaces",
command: "terraform plan --query '.metadata.component == \"gcp/compute/v0.2.0\"' -s dev",
expectedArgs: []string{
"terraform", "plan",
"--query", ".metadata.component == \"gcp/compute/v0.2.0\"",
"-s", "dev",
},
},
{
name: "query with double-quoted expression containing spaces",
command: `terraform plan --query ".settings.enabled == true" -s nonprod`,
expectedArgs: []string{
"terraform", "plan",
"--query", ".settings.enabled == true",
"-s", "nonprod",
},
},
{
name: "components with comma-separated values (no spaces)",
command: "terraform plan --components gcp/compute/001,gcp/compute/101 -s dev",
expectedArgs: []string{
"terraform", "plan",
"--components", "gcp/compute/001,gcp/compute/101",
"-s", "dev",
},
},
{
name: "components with spaces after commas (quoted)",
command: `terraform plan --components "gcp/compute/001, gcp/compute/101" -s dev`,
expectedArgs: []string{
"terraform", "plan",
"--components", "gcp/compute/001, gcp/compute/101",
"-s", "dev",
},
},
{
name: "simple command without quotes",
command: "terraform plan vpc -s dev",
expectedArgs: []string{
"terraform", "plan", "vpc", "-s", "dev",
},
},
{
name: "all flag (no arguments)",
command: "terraform plan --all -s dev",
expectedArgs: []string{
"terraform", "plan", "--all", "-s", "dev",
},
},
{
name: "complex query with nested quotes",
command: `terraform plan --query '.metadata.component == "mock" and .settings.enabled == true' -s nonprod`,
expectedArgs: []string{
"terraform", "plan",
"--query", ".metadata.component == \"mock\" and .settings.enabled == true",
"-s", "nonprod",
},
},
{
name: "command with double-dash separator",
command: "terraform plan vpc -s dev -- -var foo=bar",
expectedArgs: []string{
"terraform", "plan", "vpc", "-s", "dev", "--", "-var", "foo=bar",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Use shell.Fields() - the same function now used in workflow_utils.go
actualArgs, err := shell.Fields(tt.command, nil)
assert.NoError(t, err, "shell.Fields should not return an error")
assert.Equal(t, tt.expectedArgs, actualArgs,
"shell.Fields should correctly parse quoted arguments")
})
}
}
// TestBuildWorkflowStepError tests the buildWorkflowStepError function.
func TestBuildWorkflowStepError(t *testing.T) {
tests := []struct {
name string
err error
ctx *workflowStepErrorContext
expectContains []string
expectSentinel error
expectExitCode int
}{
{
name: "shell command failure with stack",
err: errors.New("command failed"),
ctx: &workflowStepErrorContext{
WorkflowPath: "/path/to/stacks/workflows/deploy.yaml",
WorkflowBasePath: "/path/to/stacks/workflows",
Workflow: "deploy-all",
StepName: "step1",
Command: "echo hello",
CommandType: "shell",
FinalStack: "dev-us-east-1",
},
expectContains: []string{"deploy-all", "step1", "echo hello", "dev-us-east-1"},
expectSentinel: errUtils.ErrWorkflowStepFailed,
},
{
name: "atmos command failure without stack",
err: errors.New("terraform failed"),
ctx: &workflowStepErrorContext{
WorkflowPath: "/base/stacks/workflows/infra.yaml",
WorkflowBasePath: "/base/stacks/workflows",
Workflow: "provision",
StepName: "terraform-step",
Command: "terraform plan vpc",
CommandType: "atmos",
FinalStack: "",
},
expectContains: []string{"provision", "terraform-step", "atmos terraform plan vpc"},
expectSentinel: errUtils.ErrWorkflowStepFailed,
},
{
name: "atmos command failure with stack",
err: errors.New("plan failed"),
ctx: &workflowStepErrorContext{
WorkflowPath: "/workflows/deploy.yaml",
WorkflowBasePath: "/workflows",
Workflow: "deploy",
StepName: "plan-step",
Command: "terraform plan mycomponent",
CommandType: "atmos",
FinalStack: "prod",
},
expectContains: []string{"deploy", "plan-step", "atmos", "prod"},
expectSentinel: errUtils.ErrWorkflowStepFailed,
},
{
name: "error with exit code",
err: errUtils.WithExitCode(errors.New("exit error"), 2),
ctx: &workflowStepErrorContext{
WorkflowPath: "/workflows/test.yaml",
WorkflowBasePath: "/workflows",
Workflow: "test-wf",
StepName: "failing-step",
Command: "exit 2",
CommandType: "shell",
FinalStack: "",
},
expectContains: []string{"test-wf", "failing-step"},
expectSentinel: errUtils.ErrWorkflowStepFailed,
expectExitCode: 2,
},
{
name: "workflow file in nested directory",
err: errors.New("nested failure"),
ctx: &workflowStepErrorContext{
WorkflowPath: "/base/stacks/workflows/team/project/deploy.yaml",
WorkflowBasePath: "/base/stacks/workflows",
Workflow: "deploy",
StepName: "step1",
Command: "echo test",
CommandType: "shell",
FinalStack: "",
},
expectContains: []string{"deploy", "step1", "team/project/deploy"},
expectSentinel: errUtils.ErrWorkflowStepFailed,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := buildWorkflowStepError(tt.err, tt.ctx)
assert.Error(t, result)
assert.ErrorIs(t, result, tt.expectSentinel)
// Use Format to get the full formatted error including hints.
formattedErr := errUtils.Format(result, errUtils.DefaultFormatterConfig())
for _, expected := range tt.expectContains {
assert.Contains(t, formattedErr, expected)
}
if tt.expectExitCode > 0 {
exitCode := errUtils.GetExitCode(result)
assert.Equal(t, tt.expectExitCode, exitCode)
}
})
}
}
// TestPromptForWorkflowFile_EmptyMatches tests promptForWorkflowFile with no matches.
func TestPromptForWorkflowFile_EmptyMatches(t *testing.T) {
result, err := promptForWorkflowFile([]WorkflowMatch{})
assert.ErrorIs(t, err, ErrNoWorkflowFilesToSelect)
assert.Empty(t, result)
}
// TestPromptForWorkflowFile_NonTTY tests promptForWorkflowFile in non-TTY environment.
func TestPromptForWorkflowFile_NonTTY(t *testing.T) {
// Force CI mode to ensure non-TTY behavior even when running from interactive terminal.
// This prevents the test from hanging if stdin is a TTY.
t.Setenv("CI", "true")
matches := []WorkflowMatch{
{File: "deploy.yaml", Name: "deploy", Description: "Deploy workflow"},
{File: "test.yaml", Name: "deploy", Description: "Test workflow"},
}
result, err := promptForWorkflowFile(matches)
// Should get non-TTY error since CI mode forces non-interactive behavior.
assert.ErrorIs(t, err, ErrNonTTYWorkflowSelection)
assert.Empty(t, result)
}
// TestFindWorkflowAcrossFiles_Coverage tests the findWorkflowAcrossFiles function with additional coverage.
func TestFindWorkflowAcrossFiles_Coverage(t *testing.T) {
// Set up test fixture.
stacksPath := "../../tests/fixtures/scenarios/workflows"
t.Setenv("ATMOS_CLI_CONFIG_PATH", stacksPath)
t.Setenv("ATMOS_BASE_PATH", stacksPath)
configInfo := schema.ConfigAndStacksInfo{}
atmosConfig, err := cfg.InitCliConfig(configInfo, false)
require.NoError(t, err)
tests := []struct {
name string
workflowName string
expectMatches int
expectError bool
}{
{
name: "find existing workflow",
workflowName: "shell-pass",
expectMatches: 1,
expectError: false,
},
{
name: "workflow not found",
workflowName: "nonexistent-workflow",
expectMatches: 0,
expectError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
matches, err := findWorkflowAcrossFiles(tt.workflowName, &atmosConfig)
if tt.expectError {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Len(t, matches, tt.expectMatches)
}
})
}
}
// TestExecuteDescribeWorkflows_Coverage tests the ExecuteDescribeWorkflows function with additional coverage.
func TestExecuteDescribeWorkflows_Coverage(t *testing.T) {
t.Run("with valid workflow directory", func(t *testing.T) {
stacksPath := "../../tests/fixtures/scenarios/workflows"
t.Setenv("ATMOS_CLI_CONFIG_PATH", stacksPath)
t.Setenv("ATMOS_BASE_PATH", stacksPath)
configInfo := schema.ConfigAndStacksInfo{}
atmosConfig, err := cfg.InitCliConfig(configInfo, false)
require.NoError(t, err)
listResult, mapResult, allResult, err := ExecuteDescribeWorkflows(atmosConfig)
assert.NoError(t, err)
assert.NotEmpty(t, listResult)
assert.NotEmpty(t, mapResult)
assert.NotEmpty(t, allResult)
})
t.Run("with empty workflows base path", func(t *testing.T) {
atmosConfig := schema.AtmosConfiguration{
Workflows: schema.Workflows{
BasePath: "",
},
}
_, _, _, err := ExecuteDescribeWorkflows(atmosConfig)
assert.ErrorIs(t, err, errUtils.ErrWorkflowBasePathNotConfigured)
})
t.Run("with nonexistent workflow directory", func(t *testing.T) {
// Use a platform-neutral path to a guaranteed-missing directory.
tmpDir := t.TempDir()
nonexistentPath := filepath.Join(tmpDir, "does-not-exist")
atmosConfig := schema.AtmosConfiguration{
BasePath: nonexistentPath,
Workflows: schema.Workflows{
BasePath: "workflows",
},
}
_, _, _, err := ExecuteDescribeWorkflows(atmosConfig)
assert.Error(t, err)
assert.Contains(t, err.Error(), "does not exist")
})
t.Run("with absolute workflow path", func(t *testing.T) {
tmpDir := t.TempDir()
workflowsDir := filepath.Join(tmpDir, "workflows")
err := os.MkdirAll(workflowsDir, 0o755)
require.NoError(t, err)
// Create a valid workflow file.
workflowContent := `workflows:
test-workflow:
description: Test workflow
steps:
- name: step1
command: echo hello
type: shell
`
err = os.WriteFile(filepath.Join(workflowsDir, "test.yaml"), []byte(workflowContent), 0o644)
require.NoError(t, err)
atmosConfig := schema.AtmosConfiguration{
Workflows: schema.Workflows{
BasePath: workflowsDir,
},
}
listResult, mapResult, allResult, err := ExecuteDescribeWorkflows(atmosConfig)
assert.NoError(t, err)
assert.NotEmpty(t, listResult)
assert.NotEmpty(t, mapResult)
assert.NotEmpty(t, allResult)
// Verify the workflow was found.
found := false
for _, item := range listResult {
if item.Workflow == "test-workflow" {
found = true
break
}
}
assert.True(t, found, "Expected test-workflow to be found")
})
}
// TestCheckAndGenerateWorkflowStepNames_Coverage tests the checkAndGenerateWorkflowStepNames function with additional coverage.
func TestCheckAndGenerateWorkflowStepNames_Coverage(t *testing.T) {
tests := []struct {
name string
input *schema.WorkflowDefinition
expectedNames []string
}{
{
name: "nil steps",
input: &schema.WorkflowDefinition{
Steps: nil,
},
expectedNames: nil,
},
{
name: "empty steps",
input: &schema.WorkflowDefinition{
Steps: []schema.WorkflowStep{},
},
expectedNames: []string{},
},
{
name: "steps with existing names",
input: &schema.WorkflowDefinition{
Steps: []schema.WorkflowStep{
{Name: "my-step-1", Command: "echo 1"},
{Name: "my-step-2", Command: "echo 2"},
},
},
expectedNames: []string{"my-step-1", "my-step-2"},
},
{
name: "steps without names",
input: &schema.WorkflowDefinition{
Steps: []schema.WorkflowStep{
{Command: "echo 1"},
{Command: "echo 2"},
{Command: "echo 3"},
},
},
expectedNames: []string{"step1", "step2", "step3"},
},
{
name: "mixed steps",
input: &schema.WorkflowDefinition{
Steps: []schema.WorkflowStep{
{Name: "custom", Command: "echo 1"},
{Command: "echo 2"},
{Name: "another-custom", Command: "echo 3"},
{Command: "echo 4"},
},
},
expectedNames: []string{"custom", "step2", "another-custom", "step4"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
checkAndGenerateWorkflowStepNames(tt.input)
if tt.expectedNames == nil {
assert.Nil(t, tt.input.Steps)
} else {
assert.Len(t, tt.input.Steps, len(tt.expectedNames))
for i, expectedName := range tt.expectedNames {
assert.Equal(t, expectedName, tt.input.Steps[i].Name)
}
}
})
}
}
// TestPrepareStepEnvironment tests the prepareStepEnvironment function.
func TestPrepareStepEnvironment_NoIdentity(t *testing.T) {
// When no identity is specified, should return base environment (system + global env).
env, err := prepareStepEnvironment("", "step1", nil, nil)
assert.NoError(t, err)
// Should return at least the system environment variables.
assert.NotEmpty(t, env)
}
// TestPrepareStepEnvironment_NilAuthManager tests prepareStepEnvironment with nil auth manager.
func TestPrepareStepEnvironment_NilAuthManager(t *testing.T) {
env, err := prepareStepEnvironment("some-identity", "step1", nil, nil)
assert.ErrorIs(t, err, errUtils.ErrAuthManager)
assert.Nil(t, env)
}
// TestWorkflowMatch tests the WorkflowMatch struct.
func TestWorkflowMatch(t *testing.T) {
match := WorkflowMatch{
File: "deploy.yaml",
Name: "deploy-all",
Description: "Deploy all components",
}
assert.Equal(t, "deploy.yaml", match.File)
assert.Equal(t, "deploy-all", match.Name)
assert.Equal(t, "Deploy all components", match.Description)
}
// TestExecuteDescribeWorkflows_SkipsInvalidFiles tests that invalid workflow files are skipped.
func TestExecuteDescribeWorkflows_SkipsInvalidFiles(t *testing.T) {
tmpDir := t.TempDir()
workflowsDir := filepath.Join(tmpDir, "workflows")
err := os.MkdirAll(workflowsDir, 0o755)
require.NoError(t, err)
// Create a valid workflow file.
validContent := `workflows:
valid-workflow:
steps:
- name: step1
command: echo hello
`
err = os.WriteFile(filepath.Join(workflowsDir, "valid.yaml"), []byte(validContent), 0o644)
require.NoError(t, err)
// Create an invalid YAML file.
invalidContent := `not: valid: yaml: content`
err = os.WriteFile(filepath.Join(workflowsDir, "invalid.yaml"), []byte(invalidContent), 0o644)
require.NoError(t, err)
// Create a file without workflows key.
noWorkflowsContent := `something_else:
key: value
`
err = os.WriteFile(filepath.Join(workflowsDir, "no-workflows.yaml"), []byte(noWorkflowsContent), 0o644)
require.NoError(t, err)
atmosConfig := schema.AtmosConfiguration{
Workflows: schema.Workflows{
BasePath: workflowsDir,
},
}
listResult, _, _, err := ExecuteDescribeWorkflows(atmosConfig)
// Should succeed but only have the valid workflow.
assert.NoError(t, err)
assert.Len(t, listResult, 1)
assert.Equal(t, "valid-workflow", listResult[0].Workflow)
}
// TestWorkflowStepErrorContext_Fields tests the workflowStepErrorContext struct.
func TestWorkflowStepErrorContext_Fields(t *testing.T) {
ctx := workflowStepErrorContext{
WorkflowPath: "/path/to/workflow.yaml",
WorkflowBasePath: "/path/to",
Workflow: "my-workflow",
StepName: "step-1",
Command: "echo test",
CommandType: "shell",
FinalStack: "dev",
}
assert.Equal(t, "/path/to/workflow.yaml", ctx.WorkflowPath)
assert.Equal(t, "/path/to", ctx.WorkflowBasePath)
assert.Equal(t, "my-workflow", ctx.Workflow)
assert.Equal(t, "step-1", ctx.StepName)
assert.Equal(t, "echo test", ctx.Command)
assert.Equal(t, "shell", ctx.CommandType)
assert.Equal(t, "dev", ctx.FinalStack)
}
// TestErrNoWorkflowFilesToSelect tests the error sentinel.
func TestErrNoWorkflowFilesToSelect(t *testing.T) {
assert.Error(t, ErrNoWorkflowFilesToSelect)
assert.Contains(t, ErrNoWorkflowFilesToSelect.Error(), "no workflow files")
}
// TestErrNonTTYWorkflowSelection tests the error sentinel.
func TestErrNonTTYWorkflowSelection(t *testing.T) {
assert.Error(t, ErrNonTTYWorkflowSelection)
assert.Contains(t, ErrNonTTYWorkflowSelection.Error(), "TTY")
}
// TestPrepareStepEnvironment_WithGlobalEnv tests prepareStepEnvironment with global env variables.
func TestPrepareStepEnvironment_WithGlobalEnv(t *testing.T) {
globalEnv := map[string]string{
"GLOBAL_VAR_1": "value1",
"GLOBAL_VAR_2": "value2",
}
// When no identity is specified, should return base environment including global env.
env, err := prepareStepEnvironment("", "step1", nil, globalEnv)
assert.NoError(t, err)
assert.NotEmpty(t, env)
// Check that global env vars are included.
foundVar1 := false
foundVar2 := false
for _, e := range env {
if e == "GLOBAL_VAR_1=value1" {
foundVar1 = true
}
if e == "GLOBAL_VAR_2=value2" {
foundVar2 = true
}
}
assert.True(t, foundVar1, "GLOBAL_VAR_1 should be in environment")
assert.True(t, foundVar2, "GLOBAL_VAR_2 should be in environment")
}
// TestPrepareStepEnvironment_EmptyGlobalEnv tests prepareStepEnvironment with empty global env.
func TestPrepareStepEnvironment_EmptyGlobalEnv(t *testing.T) {
globalEnv := map[string]string{}
env, err := prepareStepEnvironment("", "step1", nil, globalEnv)
assert.NoError(t, err)
// Should return system environment at minimum.
assert.NotEmpty(t, env)
}
// TestShellFieldsParsing tests that shell.Fields correctly parses various command patterns.
func TestShellFieldsParsing(t *testing.T) {
tests := []struct {
name string
command string
expectedArgs int
}{
{
name: "simple command",
command: "terraform plan vpc",
expectedArgs: 3,
},
{
name: "command with flags",
command: "terraform plan vpc -auto-approve",
expectedArgs: 4,
},
{
name: "command with quoted arg",
command: `terraform plan -var="foo=bar"`,
expectedArgs: 3, // ["terraform", "plan", "-var=foo=bar"]
},
{
name: "command with single quoted arg",