-
-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathterraform_utils_test.go
1636 lines (1409 loc) · 45.3 KB
/
terraform_utils_test.go
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 (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/charmbracelet/log"
"github.com/cloudposse/atmos/pkg/schema"
"github.com/stretchr/testify/assert"
)
const (
// Define constants for testing
testVarFileFlag = "-var-file"
testOutFlag = "-out"
)
// Helper function to create bool pointer for testing.
func boolPtr(b bool) *bool {
return &b
}
func TestIsWorkspacesEnabled(t *testing.T) {
// Test cases for isWorkspacesEnabled function.
tests := []struct {
name string
backendType string
workspacesEnabled *bool
expectedEnabled bool
expectWarning bool
}{
{
name: "Default behavior (no explicit setting, non-HTTP backend)",
backendType: "s3",
workspacesEnabled: nil,
expectedEnabled: true,
expectWarning: false,
},
{
name: "HTTP backend automatically disables workspaces",
backendType: "http",
workspacesEnabled: nil,
expectedEnabled: false,
expectWarning: false,
},
{
name: "Explicitly disabled workspaces",
backendType: "s3",
workspacesEnabled: boolPtr(false),
expectedEnabled: false,
expectWarning: false,
},
{
name: "Explicitly enabled workspaces",
backendType: "s3",
workspacesEnabled: boolPtr(true),
expectedEnabled: true,
expectWarning: false,
},
{
name: "HTTP backend ignores explicitly enabled workspaces with warning",
backendType: "http",
workspacesEnabled: boolPtr(true),
expectedEnabled: false,
expectWarning: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Setup test config.
atmosConfig := &schema.AtmosConfiguration{
Components: schema.Components{
Terraform: schema.Terraform{
WorkspacesEnabled: tc.workspacesEnabled,
},
},
}
info := &schema.ConfigAndStacksInfo{
ComponentBackendType: tc.backendType,
Component: "test-component",
}
// Test function.
result := isWorkspacesEnabled(atmosConfig, info)
// Assert results.
assert.Equal(t, tc.expectedEnabled, result, "Expected workspace enabled status to match")
})
}
}
func TestSortJSON(t *testing.T) {
tests := []struct {
name string
input interface{}
expected interface{}
}{
{
name: "sort map keys",
input: map[string]interface{}{
"c": 3,
"a": 1,
"b": 2,
},
expected: map[string]interface{}{
"a": 1,
"b": 2,
"c": 3,
},
},
{
name: "sort nested maps",
input: map[string]interface{}{
"z": map[string]interface{}{
"y": 2,
"x": 1,
},
"a": 1,
},
expected: map[string]interface{}{
"a": 1,
"z": map[string]interface{}{
"x": 1,
"y": 2,
},
},
},
{
name: "sort maps in arrays",
input: map[string]interface{}{
"array": []interface{}{
map[string]interface{}{
"b": 2,
"a": 1,
},
map[string]interface{}{
"d": 4,
"c": 3,
},
},
},
expected: map[string]interface{}{
"array": []interface{}{
map[string]interface{}{
"a": 1,
"b": 2,
},
map[string]interface{}{
"c": 3,
"d": 4,
},
},
},
},
{
name: "non-map value",
input: "string value",
expected: "string value",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := sortJSON(tt.input)
// Convert to JSON for comparison
expectedJSON, err := json.Marshal(tt.expected)
if err != nil {
t.Fatalf("Failed to marshal expected JSON: %v", err)
}
resultJSON, err := json.Marshal(result)
if err != nil {
t.Fatalf("Failed to marshal result JSON: %v", err)
}
if string(resultJSON) != string(expectedJSON) {
t.Errorf("sortJSON() = %v, want %v", string(resultJSON), string(expectedJSON))
}
})
}
}
// MockExecutor is a mock implementation of shell command execution
type MockExecutor struct {
commands [][]string
outputs map[string]string
}
// ExecuteCommand records the command and simulates the behavior we need for testing
func (m *MockExecutor) ExecuteCommand(command string, args []string, componentPath string) error {
m.commands = append(m.commands, append([]string{command}, args...))
// If it's a terraform show command, simulate writing JSON output
if command == "terraform" && len(args) >= 1 && args[0] == "show" && len(args) >= 3 {
planFile := args[2]
outputFile := args[len(args)-1]
// Return appropriate mock plan data based on the plan file
if strings.Contains(planFile, "orig") {
return os.WriteFile(outputFile, []byte(m.outputs["orig"]), 0o600)
} else if strings.Contains(planFile, "new") {
return os.WriteFile(outputFile, []byte(m.outputs["new"]), 0o600)
}
}
// If it's a terraform plan command, simulate creating a plan
if command == "terraform" && len(args) >= 1 && args[0] == "plan" {
// Find the output plan file (should be after -out flag)
for i, arg := range args {
if (arg == "-out" || arg == outFlag) && i+1 < len(args) {
return os.WriteFile(args[i+1], []byte("mock plan content"), 0o600)
}
}
}
return nil
}
// prettyDiffTest is a version of prettyDiff that captures output for testing
func prettyDiffTest(a, b map[string]interface{}, path string, output *strings.Builder) bool {
hasDifferences := false
// Compare keys in map a to map b
hasDifferences = compareMapAtoBTest(a, b, path, output) || hasDifferences
// Compare keys in map b to map a (for keys only in b)
hasDifferences = compareMapBtoATest(a, b, path, output) || hasDifferences
return hasDifferences
}
// Helper function to compare keys from map a to map b for testing
func compareMapAtoBTest(a, b map[string]interface{}, path string, output *strings.Builder) bool {
hasDifferences := false
for k, v1 := range a {
currentPath := buildPathTest(path, k)
v2, exists := b[k]
if !exists {
// Key exists in a but not in b
printRemovedValueTest(currentPath, v1, output)
hasDifferences = true
continue
}
// Types are different
if reflect.TypeOf(v1) != reflect.TypeOf(v2) {
printTypeDifferenceTest(currentPath, v1, v2, output)
hasDifferences = true
continue
}
// Handle based on value type
switch val := v1.(type) {
case map[string]interface{}:
if prettyDiffTest(val, v2.(map[string]interface{}), currentPath, output) {
hasDifferences = true
}
case []interface{}:
if !reflect.DeepEqual(val, v2) {
if diffArraysTest(currentPath, val, v2.([]interface{}), output) {
hasDifferences = true
}
}
default:
if !reflect.DeepEqual(v1, v2) {
fmt.Fprintf(output, "~ %s: %v => %v\n", currentPath, v1, v2)
hasDifferences = true
}
}
}
return hasDifferences
}
// Helper function to compare keys from map b to map a for testing
func compareMapBtoATest(a, b map[string]interface{}, path string, output *strings.Builder) bool {
hasDifferences := false
for k, v2 := range b {
currentPath := buildPathTest(path, k)
_, exists := a[k]
if !exists {
// Key exists in b but not in a
printAddedValueTest(currentPath, v2, output)
hasDifferences = true
}
}
return hasDifferences
}
// Helper function to build the path string for testing
func buildPathTest(path, key string) string {
if path == "" {
return key
}
return path + "." + key
}
// Helper function to print a value that was removed for testing
func printRemovedValueTest(path string, value interface{}, output *strings.Builder) {
switch v := value.(type) {
case map[string]interface{}, []interface{}:
jsonBytes, err := json.MarshalIndent(v, "", " ")
if err != nil {
// If marshaling fails, fall back to simple format
fmt.Fprintf(output, "- %s: %v\n", path, v)
} else {
fmt.Fprintf(output, "- %s:\n%s\n", path, string(jsonBytes))
}
default:
fmt.Fprintf(output, "- %s: %v\n", path, v)
}
}
// Helper function to print a value that was added for testing
func printAddedValueTest(path string, value interface{}, output *strings.Builder) {
switch v := value.(type) {
case map[string]interface{}, []interface{}:
jsonBytes, err := json.MarshalIndent(v, "", " ")
if err != nil {
// If marshaling fails, fall back to simple format
fmt.Fprintf(output, "+ %s: %v\n", path, v)
} else {
fmt.Fprintf(output, "+ %s:\n%s\n", path, string(jsonBytes))
}
default:
fmt.Fprintf(output, "+ %s: %v\n", path, v)
}
}
// Helper function to print a type difference for testing
func printTypeDifferenceTest(path string, v1, v2 interface{}, output *strings.Builder) {
fmt.Fprintf(output, "~ %s:\n", path)
fmt.Fprintf(output, " - %v\n", v1)
fmt.Fprintf(output, " + %v\n", v2)
}
// Helper function to diff arrays for testing
func diffArraysTest(path string, arr1, arr2 []interface{}, output *strings.Builder) bool {
// For terraform plans, resources arrays are especially important to show clearly
if path == "resources" || strings.HasSuffix(path, ".resources") {
return diffResourceArraysTest(path, arr1, arr2, output)
} else {
return diffGenericArraysTest(path, arr1, arr2, output)
}
}
// Helper function to diff resource arrays for testing
func diffResourceArraysTest(path string, arr1, arr2 []interface{}, output *strings.Builder) bool {
fmt.Fprintf(output, "~ %s: (resource changes)\n", path)
fmt.Fprintf(output, " Resources:\n")
// Process only if there's content in both arrays
if len(arr1) > 0 && len(arr2) > 0 {
// Find resources that changed or were removed
processRemovedOrChangedResourcesTest(arr1, arr2, output)
// Find added resources
processAddedResourcesTest(arr1, arr2, output)
} else {
// Simple fallback for empty arrays
if len(arr1) == 0 {
fmt.Fprintf(output, " - No resources in original plan\n")
}
if len(arr2) == 0 {
fmt.Fprintf(output, " + No resources in new plan\n")
}
}
return true // Always return true since we printed something
}
// Helper function to process resources that were removed or changed for testing
func processRemovedOrChangedResourcesTest(arr1, arr2 []interface{}, output *strings.Builder) {
for _, origRes := range arr1 {
origMap, ok1 := origRes.(map[string]interface{})
if !ok1 {
continue
}
matchingResource := findMatchingResourceTest(origMap, arr2)
if matchingResource != nil {
// Resource exists in both - compare them
fmt.Fprintf(output, " Resource: %s\n", getResourceNameTest(origMap))
resourceDiffTest(origMap, matchingResource, " ", output)
} else {
// Resource was removed
printRemovedResourceTest(origMap, output)
}
}
}
// Helper function to find a matching resource in the array for testing
func findMatchingResourceTest(resource map[string]interface{}, resources []interface{}) map[string]interface{} {
if address, hasAddr := resource["address"]; hasAddr {
for _, res := range resources {
resMap, ok := res.(map[string]interface{})
if !ok {
continue
}
if newAddr, hasNewAddr := resMap["address"]; hasNewAddr && address == newAddr {
return resMap
}
}
}
return nil
}
// Helper function to process resources that were added for testing
func processAddedResourcesTest(arr1, arr2 []interface{}, output *strings.Builder) {
for _, newRes := range arr2 {
newMap, ok := newRes.(map[string]interface{})
if !ok {
continue
}
// Check if this resource exists in the original array
if findMatchingResourceTest(newMap, arr1) == nil {
// This is a new resource
printAddedResourceTest(newMap, output)
}
}
}
// Helper function to print a removed resource for testing
func printRemovedResourceTest(resource map[string]interface{}, output *strings.Builder) {
fmt.Fprintf(output, " - Resource removed: %v\n", getResourceNameTest(resource))
resourceBytes, err := json.MarshalIndent(resource, " ", " ")
if err != nil {
// If marshaling fails, just print the map
fmt.Fprintf(output, " %v\n", resource)
} else {
fmt.Fprintf(output, " %s\n", strings.ReplaceAll(string(resourceBytes), "\n", "\n "))
}
}
// Helper function to print an added resource for testing
func printAddedResourceTest(resource map[string]interface{}, output *strings.Builder) {
fmt.Fprintf(output, " + Resource added: %v\n", getResourceNameTest(resource))
resourceBytes, err := json.MarshalIndent(resource, " ", " ")
if err != nil {
// If marshaling fails, just print the map
fmt.Fprintf(output, " %v\n", resource)
} else {
fmt.Fprintf(output, " %s\n", strings.ReplaceAll(string(resourceBytes), "\n", "\n "))
}
}
// Helper function to diff generic (non-resource) arrays for testing
func diffGenericArraysTest(path string, arr1, arr2 []interface{}, output *strings.Builder) bool {
fmt.Fprintf(output, "~ %s:\n", path)
// Print the first array
if len(arr1) > 0 {
jsonBytes, err := json.MarshalIndent(arr1, " - ", " ")
if err != nil {
fmt.Fprintf(output, " - [Array marshaling error: %v]\n", err)
} else {
fmt.Fprintf(output, " - %s\n", string(jsonBytes))
}
} else {
fmt.Fprintf(output, " - []\n")
}
// Print the second array
if len(arr2) > 0 {
jsonBytes, err := json.MarshalIndent(arr2, " + ", " ")
if err != nil {
fmt.Fprintf(output, " + [Array marshaling error: %v]\n", err)
} else {
fmt.Fprintf(output, " + %s\n", string(jsonBytes))
}
} else {
fmt.Fprintf(output, " + []\n")
}
return true
}
// Helper function to get a readable resource name for the test
func getResourceNameTest(resource map[string]interface{}) string {
if address, hasAddr := resource["address"]; hasAddr {
return fmt.Sprintf("%v", address)
}
var parts []string
if t, hasType := resource["type"]; hasType {
parts = append(parts, fmt.Sprintf("%v", t))
}
if name, hasName := resource["name"]; hasName {
parts = append(parts, fmt.Sprintf("%v", name))
}
if len(parts) > 0 {
return strings.Join(parts, ".")
}
return "<unknown resource>"
}
// Helper function to diff individual resources for the test
func resourceDiffTest(a, b map[string]interface{}, indent string, output *strings.Builder) {
// Focus on the values part of the resource if present
if values1, hasValues1 := a["values"].(map[string]interface{}); hasValues1 {
if values2, hasValues2 := b["values"].(map[string]interface{}); hasValues2 {
diffResourceValuesTest(values1, values2, indent, output)
return
}
}
// Fallback if no values field
diffResourceFallbackTest(a, b, indent, output)
}
// Helper function to diff resource values for testing
func diffResourceValuesTest(values1, values2 map[string]interface{}, indent string, output *strings.Builder) {
// Compare values in first map
for k, v1 := range values1 {
v2, exists := values2[k]
if !exists {
fmt.Fprintf(output, "%s- %s: %v\n", indent, k, v1)
continue
}
if !reflect.DeepEqual(v1, v2) {
fmt.Fprintf(output, "%s~ %s: %v => %v\n", indent, k, v1, v2)
}
}
// Check for added values
for k, v2 := range values2 {
_, exists := values1[k]
if !exists {
fmt.Fprintf(output, "%s+ %s: %v\n", indent, k, v2)
}
}
}
// Helper function for resource diff fallback method for testing
func diffResourceFallbackTest(a, b map[string]interface{}, indent string, output *strings.Builder) {
// Skip these common metadata fields
skipFields := map[string]bool{
"address": true,
"type": true,
"name": true,
"mode": true,
"provider_name": true,
}
// Compare fields in first resource
for k, v1 := range a {
if skipFields[k] {
continue
}
v2, exists := b[k]
if !exists {
fmt.Fprintf(output, "%s- %s: %v\n", indent, k, v1)
continue
}
if !reflect.DeepEqual(v1, v2) {
fmt.Fprintf(output, "%s~ %s: %v => %v\n", indent, k, v1, v2)
}
}
// Check for added fields
for k, v2 := range b {
if skipFields[k] {
continue
}
_, exists := a[k]
if !exists {
fmt.Fprintf(output, "%s+ %s: %v\n", indent, k, v2)
}
}
}
// testExecuteTerraformPlanDiff is a testable version of executeTerraformPlanDiff that uses the MockExecutor
func testExecuteTerraformPlanDiff(executor *MockExecutor, info schema.ConfigAndStacksInfo, componentPath, varFile, planFile string) error {
// Step 1: Extract args and validate original plan file
origPlanFlag := ""
newPlanFlag := ""
var skipNext bool
var additionalPlanArgs []string
// Extract the orig and new plan file paths from the flags and collect other arguments
for i, arg := range info.AdditionalArgsAndFlags {
if skipNext {
skipNext = false
continue
}
if arg == "--orig" && i+1 < len(info.AdditionalArgsAndFlags) {
origPlanFlag = info.AdditionalArgsAndFlags[i+1]
skipNext = true
} else if arg == "--new" && i+1 < len(info.AdditionalArgsAndFlags) {
newPlanFlag = info.AdditionalArgsAndFlags[i+1]
skipNext = true
} else {
// Add any other arguments to be passed to the terraform plan command
additionalPlanArgs = append(additionalPlanArgs, arg)
}
}
// Check if orig flag is provided
if origPlanFlag == "" {
return errors.New("--orig flag must be provided with the path to the original plan file")
}
// Validate original plan file
origPlanPath := origPlanFlag
if !filepath.IsAbs(origPlanPath) {
origPlanPath = filepath.Join(componentPath, origPlanPath)
}
// Check if orig plan file exists
if _, err := os.Stat(origPlanPath); os.IsNotExist(err) {
return fmt.Errorf("original plan file does not exist at path: %s", origPlanPath)
}
// Step 2: Process new plan file
var newPlanPath string
if newPlanFlag == "" {
// Generate a new plan
log.Info("Generating new plan...")
// Create a temporary plan file
newPlanPath = filepath.Join(componentPath, "new-"+filepath.Base(planFile))
// Simulate terraform plan execution with all additional arguments
planCmd := []string{"plan", testVarFileFlag, varFile, testOutFlag, newPlanPath}
planCmd = append(planCmd, additionalPlanArgs...)
err := executor.ExecuteCommand("terraform", planCmd, componentPath)
if err != nil {
return err
}
} else {
newPlanPath = newPlanFlag
if !filepath.IsAbs(newPlanPath) {
newPlanPath = filepath.Join(componentPath, newPlanPath)
}
// Check if new plan file exists
if _, err := os.Stat(newPlanPath); os.IsNotExist(err) {
return fmt.Errorf("new plan file does not exist at path: %s", newPlanPath)
}
}
// Step 3: Set up temp files and convert plans to JSON
// Create temporary files for the human-readable versions of the plans
origPlanHumanReadable, err := os.CreateTemp("", "orig-plan-*.json")
if err != nil {
return fmt.Errorf("error creating temporary file for original plan: %w", err)
}
defer os.Remove(origPlanHumanReadable.Name())
origPlanHumanReadable.Close()
newPlanHumanReadable, err := os.CreateTemp("", "new-plan-*.json")
if err != nil {
return fmt.Errorf("error creating temporary file for new plan: %w", err)
}
defer os.Remove(newPlanHumanReadable.Name())
newPlanHumanReadable.Close()
// Simulate terraform show to get human-readable JSON versions of the plans
log.Info("Converting plan files to JSON...")
err = executor.ExecuteCommand("terraform", []string{"show", "-json", origPlanPath}, componentPath)
if err != nil {
return fmt.Errorf("error showing original plan: %w", err)
}
err = executor.ExecuteCommand("terraform", []string{"show", "-json", newPlanPath}, componentPath)
if err != nil {
return fmt.Errorf("error showing new plan: %w", err)
}
// Step 4: Parse and compare the plans
// Parse JSON
var origPlan, newPlan map[string]interface{}
if err := json.Unmarshal([]byte(executor.outputs["orig"]), &origPlan); err != nil {
return fmt.Errorf("error parsing original plan JSON: %w", err)
}
if err := json.Unmarshal([]byte(executor.outputs["new"]), &newPlan); err != nil {
return fmt.Errorf("error parsing new plan JSON: %w", err)
}
// Remove or normalize timestamp to avoid showing it in the diff
if _, ok := origPlan["timestamp"]; ok {
origPlan["timestamp"] = "TIMESTAMP_IGNORED"
}
if _, ok := newPlan["timestamp"]; ok {
newPlan["timestamp"] = "TIMESTAMP_IGNORED"
}
// Generate a hierarchical diff between the two plans
log.Info("Comparing plans...")
fmt.Println("Plan differences:")
fmt.Println("----------------")
var diffOutput strings.Builder
hasDifferences := prettyDiffTest(origPlan, newPlan, "", &diffOutput)
// Step 5: Display the results
if !hasDifferences {
fmt.Println("No differences found between the plans.")
} else {
fmt.Println(diffOutput.String())
}
return nil
}
func TestExecuteTerraformPlanDiffBasic(t *testing.T) {
// Create test environment
tempDir, origPlanFile, newPlanFile := setupTestPlanDiffEnvironment(t)
defer os.RemoveAll(tempDir)
// Get test plan data
origPlanData, newPlanData := getTestPlanData()
// Create test cases
tests := createPlanDiffTestCases(origPlanFile, newPlanFile, origPlanData, newPlanData)
// Run test cases
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a mock executor
executor := createMockExecutor(tt.origPlanJSON, tt.newPlanJSON)
// Create test info
info := schema.ConfigAndStacksInfo{
AdditionalArgsAndFlags: tt.additionalArgs,
}
// Special handling for "with_both_plans" test case
if tt.name == "with_both_plans" {
runWithBothPlansTest(t, tt, executor, info, tempDir)
return
}
// Run the standard test
runStandardPlanDiffTest(t, tt, executor, info, tempDir)
})
}
}
// Helper function to set up the test environment
func setupTestPlanDiffEnvironment(t *testing.T) (string, string, string) {
// Create a temporary directory for test files
tempDir, err := os.MkdirTemp("", "terraform-plan-diff-test")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
// Create test plan files
origPlanFile := filepath.Join(tempDir, "orig-plan.tfplan")
newPlanFile := filepath.Join(tempDir, "new-plan.tfplan")
// Write dummy content to plan files so they exist
err = os.WriteFile(origPlanFile, []byte("dummy content"), 0o600)
if err != nil {
t.Fatalf("Failed to write orig plan file: %v", err)
}
err = os.WriteFile(newPlanFile, []byte("dummy content"), 0o600)
if err != nil {
t.Fatalf("Failed to write new plan file: %v", err)
}
return tempDir, origPlanFile, newPlanFile
}
// Helper function to get test plan data
func getTestPlanData() (string, string) {
// Mock plan data with more visible differences
origPlanData := `{
"format_version": "1.0",
"terraform_version": "1.5.7",
"variables": {
"location": {"value": "Stockholm"},
"instance_type": {"value": "t3.micro"},
"environment": {"value": "development"}
},
"planned_values": {
"root_module": {
"resources": [
{
"address": "aws_instance.example",
"mode": "managed",
"type": "aws_instance",
"name": "example",
"provider_name": "registry.terraform.io/hashicorp/aws",
"schema_version": 1,
"values": {
"ami": "ami-12345",
"instance_type": "t3.micro",
"tags": {
"Name": "example-stockholm",
"Environment": "development"
}
}
}
]
}
},
"timestamp": "2025-03-10T23:07:52Z"
}`
newPlanData := `{
"format_version": "1.0",
"terraform_version": "1.5.7",
"variables": {
"location": {"value": "New Jersey"},
"instance_type": {"value": "t3.large"},
"environment": {"value": "production"}
},
"planned_values": {
"root_module": {
"resources": [
{
"address": "aws_instance.example",
"mode": "managed",
"type": "aws_instance",
"name": "example",
"provider_name": "registry.terraform.io/hashicorp/aws",
"schema_version": 1,
"values": {
"ami": "ami-67890",
"instance_type": "t3.large",
"tags": {
"Name": "example-newjersey",
"Environment": "production"
}
}
}
]
}
},
"timestamp": "2025-03-10T23:07:57Z"
}`
return origPlanData, newPlanData
}
// Test case definition
type planDiffTestCase struct {
name string
additionalArgs []string
expectedDifference bool
origPlanJSON string
newPlanJSON string
}
// Helper function to create test cases
func createPlanDiffTestCases(origPlanFile, newPlanFile, origPlanData, newPlanData string) []planDiffTestCase {
return []planDiffTestCase{
{
name: "no_arguments",
additionalArgs: []string{"--orig", origPlanFile},
expectedDifference: false,
origPlanJSON: origPlanData,
newPlanJSON: origPlanData,
},
{
name: "orig_only",
additionalArgs: []string{"--orig", origPlanFile},
expectedDifference: false,
origPlanJSON: origPlanData,
newPlanJSON: origPlanData,
},
{
name: "with_both_plans",
additionalArgs: []string{"--orig", origPlanFile, "--new", newPlanFile},
expectedDifference: true,
origPlanJSON: origPlanData,
newPlanJSON: newPlanData,
},
{
name: "with_additional_var_args",
additionalArgs: []string{"--orig", origPlanFile, "-var", "location=New Jersey"},
expectedDifference: true,
origPlanJSON: origPlanData,
newPlanJSON: newPlanData,
},
}
}
// Helper function to create a mock executor
func createMockExecutor(origPlanJSON, newPlanJSON string) *MockExecutor {
return &MockExecutor{
outputs: map[string]string{
"orig": origPlanJSON,
"new": newPlanJSON,
},
}
}
// Helper function to run the "with_both_plans" test case
func runWithBothPlansTest(t *testing.T, tt planDiffTestCase, executor *MockExecutor, info schema.ConfigAndStacksInfo, tempDir string) {
// Redirect stdout to capture output
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
// Run the function
err := testExecuteTerraformPlanDiff(executor, info, tempDir, "test-vars.tfvars", "test-plan.tfplan")
// Restore stdout and capture the output
w.Close()
os.Stdout = oldStdout
var buf bytes.Buffer
_, err = io.Copy(&buf, r)
if err != nil {
t.Errorf("Failed to read output: %v", err)
}
output := buf.String()
// Log the diff output
t.Logf("Diff output:\n%s", output)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
verifyPlanDiffOutput(t, tt.expectedDifference, output)
}
// Helper function to run the standard test cases
func runStandardPlanDiffTest(t *testing.T, tt planDiffTestCase, executor *MockExecutor, info schema.ConfigAndStacksInfo, tempDir string) {
// Redirect stdout to capture output
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
// Run the function
err := testExecuteTerraformPlanDiff(executor, info, tempDir, "test-vars.tfvars", "test-plan.tfplan")
// Restore stdout
w.Close()
os.Stdout = oldStdout
// Check if additional arguments were properly passed for the var args test
if tt.name == "with_additional_var_args" {
verifyAdditionalVarArgs(t, executor)
}
// Read the captured output
var buf bytes.Buffer
_, err = io.Copy(&buf, r)
if err != nil {
t.Errorf("Failed to read output: %v", err)
}
output := buf.String()
// Verify expected behavior
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
verifyPlanDiffOutput(t, tt.expectedDifference, output)
}
// Helper function to verify additional var arguments
func verifyAdditionalVarArgs(t *testing.T, executor *MockExecutor) {
foundVarArg := false
for _, cmd := range executor.commands {
if len(cmd) > 2 && cmd[0] == "terraform" && cmd[1] == "plan" {
for i := 0; i < len(cmd)-1; i++ {
if cmd[i] == "-var" && cmd[i+1] == "location=New Jersey" {
foundVarArg = true
break
}