-
Notifications
You must be signed in to change notification settings - Fork 44
/
terratag_test.go
506 lines (401 loc) · 13.2 KB
/
terratag_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
package terratag
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/bmatcuk/doublestar"
"github.com/env0/terratag/cli"
"github.com/env0/terratag/internal/common"
. "github.com/onsi/gomega"
"github.com/otiai10/copy"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var cleanArgs = append([]string(nil), os.Args...)
var programName = os.Args[0]
var args = []string{
programName,
"-tags={\"env0_environment_id\":\"40907eff-cf7c-419a-8694-e1c6bf1d1168\",\"env0_project_id\":\"43fd4ff1-8d37-4d9d-ac97-295bd850bf94\"}",
}
var testsDir = "test/tests"
var fixtureDir = "test/fixture"
var osArgsLock sync.Mutex
type TestCase struct {
suite string
suiteDir string
entryDir string
}
type TestCaseConfig struct {
Suites []string
}
func TestTerraform12(t *testing.T) {
testTerraform(t, "12")
}
func TestTerraform13(t *testing.T) {
testTerraform(t, "13_14")
}
func TestTerraform14(t *testing.T) {
testTerraform(t, "13_14")
}
func TestTerraform15(t *testing.T) {
testTerraform(t, "15")
}
func TestTerraformlatestWithFilter(t *testing.T) {
testTerraformWithFilter(t, "latest_filter", "azurerm_resource_group|aws_s3_bucket", "")
}
func TestTerraformlatestWithSkip(t *testing.T) {
testTerraformWithFilter(t, "latest_skip", ".*", "azurerm_resource_group")
}
func TestTerraformlatest(t *testing.T) {
testTerraform(t, "latest")
}
func TestOpenTofu(t *testing.T) {
if _, skip := os.LookupEnv("SKIP_INTEGRATION_TESTS"); skip {
t.Skip("skipping integration test")
}
version := "latest"
entries := getEntries(t, version)
if len(entries) == 0 {
t.Fatalf("test entries not found for version %s", version)
}
for _, tt := range entries {
tt := tt // NOTE: https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables
t.Run(tt.suite, func(t *testing.T) {
t.Parallel() // marks each test case as capable of running in parallel with each other
g := NewWithT(t)
itShouldOpenTofuInit(tt.entryDir, g)
itShouldRunTerratag(tt.entryDir, "", "", g)
itShouldRunOpenTofuValidate(tt.entryDir, g)
itShouldGenerateExpectedTerratagFiles(tt.suiteDir, g)
})
}
}
func TestTerragruntWithCache(t *testing.T) {
if _, skip := os.LookupEnv("SKIP_INTEGRATION_TESTS"); skip {
t.Skip("skipping integration test")
}
g := NewWithT(t)
entryDir := "./test/tests/terragrunt_with_cache"
in := entryDir + "/in"
out := entryDir + "/out"
if err := os.RemoveAll(out); err != nil {
t.Fatalf("failed to remove out directory: %s %s", out, err.Error())
}
if err := copy.Copy(in, out); err != nil {
t.Fatalf("failed to in directory to out directory: %s", err.Error())
}
itShouldRunTerragruntInit(out, g)
itShouldRunTerratagTerragruntMode(out, g)
itShouldRunTerragruntValidate(out, g)
itShouldGenerateExpectedTerragruntTerratagFiles(entryDir, g)
}
func testTerraform(t *testing.T, version string) {
if _, skip := os.LookupEnv("SKIP_INTEGRATION_TESTS"); skip {
t.Skip("skipping integration test")
}
entries := getEntries(t, version)
if len(entries) == 0 {
t.Fatalf("test entries not found for version %s", version)
}
for _, tt := range entries {
tt := tt // NOTE: https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables
t.Run(tt.suite, func(t *testing.T) {
t.Parallel() // marks each test case as capable of running in parallel with each other
g := NewWithT(t)
itShouldTerraformInit(tt.entryDir, g)
itShouldRunTerratag(tt.entryDir, "", "", g)
itShouldRunTerraformValidate(tt.entryDir, g)
itShouldGenerateExpectedTerratagFiles(tt.suiteDir, g)
})
}
}
func testTerraformWithFilter(t *testing.T, version string, filter string, skip string) {
if _, skip := os.LookupEnv("SKIP_INTEGRATION_TESTS"); skip {
t.Skip("skipping integration test")
}
for _, tt := range getEntries(t, version) {
tt := tt // NOTE: https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables
t.Run(tt.suite, func(t *testing.T) {
t.Parallel() // marks each test case as capable of running in parallel with each other
g := NewWithT(t)
itShouldTerraformInit(tt.entryDir, g)
itShouldRunTerratag(tt.entryDir, filter, skip, g)
itShouldRunTerraformValidate(tt.entryDir, g)
itShouldGenerateExpectedTerratagFiles(tt.suiteDir, g)
})
}
}
func itShouldGenerateExpectedTerratagFiles(entryDir string, g *GomegaWithT) {
expectedPattern := strings.Split(entryDir, "/out/")[0] + "/expected/*.tf"
var expectedTerratag []string
var actualTerratag []string
expectedTerratag, _ = doublestar.Glob(expectedPattern)
if len(expectedTerratag) == 0 {
expectedPattern = strings.Split(entryDir, "/out/")[0] + "/expected/**/*.tf"
expectedTerratag, _ = doublestar.Glob(expectedPattern)
}
actualTerratag, _ = doublestar.Glob(entryDir + "/*.tf")
if len(actualTerratag) == 0 {
actualTerratag, _ = doublestar.Glob(entryDir + "/**/*.tf")
}
actualTerratag = filterSymlink(actualTerratag)
g.Expect(len(actualTerratag)).Should(BeNumerically(">", 0))
g.Expect(len(expectedTerratag)).Should(BeNumerically(">", 0))
g.Expect(len(actualTerratag)).To(BeEquivalentTo(len(expectedTerratag)), "it should generate the same number of terratag files as expected")
for i, expectedTerratagFile := range expectedTerratag {
expectedFile, _ := os.Open(expectedTerratagFile)
expectedContent, _ := io.ReadAll(expectedFile)
actualTerratagFile := actualTerratag[i]
actualFile, _ := os.Open(actualTerratagFile)
actualContent, _ := io.ReadAll(actualFile)
g.Expect(string(expectedContent)).To(BeEquivalentTo(string(actualContent)), actualTerratagFile+" does not match "+expectedTerratagFile)
}
}
func getFileSha256(filename string, g *GomegaWithT) string {
f, err := os.Open(filename)
g.Expect(err).To(BeNil())
defer f.Close()
h := sha256.New()
_, err = io.Copy(h, f)
g.Expect(err).To(BeNil())
return string(h.Sum(nil))
}
func itShouldGenerateExpectedTerragruntTerratagFiles(entryDir string, g *GomegaWithT) {
expectedPattern := entryDir + "/expected/**/*.tf"
expectedTerratag, _ := doublestar.Glob(expectedPattern)
actualTerratag, _ := doublestar.Glob(entryDir + "/out/**/.terragrunt-cache/**/*.tf")
actualTerratag = filterSymlink(actualTerratag)
hashmap := make(map[string]string)
for _, acctualTerratagFile := range actualTerratag {
hashmap[getFileSha256(acctualTerratagFile, g)] = acctualTerratagFile
}
for _, expectedTerratagFile := range expectedTerratag {
hash := getFileSha256(expectedTerratagFile, g)
_, ok := hashmap[hash]
g.Expect(ok).To(BeTrue())
}
}
func itShouldRunOpenTofuValidate(entryDir string, g *GomegaWithT) {
err := run_opentofu(entryDir, "validate")
g.Expect(err).To(BeNil(), "opentofu validate failed")
}
func itShouldRunTerraformValidate(entryDir string, g *GomegaWithT) {
err := run_terraform(entryDir, "validate")
g.Expect(err).To(BeNil(), "terraform validate failed")
}
func itShouldRunTerratag(entryDir string, filter string, skip string, g *GomegaWithT) {
err := run_terratag(entryDir, filter, skip, false)
g.Expect(err).To(BeNil(), "terratag failed")
}
func itShouldRunTerratagTerragruntMode(entryDir string, g *GomegaWithT) {
err := run_terratag(entryDir, "", "", true)
g.Expect(err).To(BeNil(), "terratag terragrunt mode failed")
}
func itShouldOpenTofuInit(entryDir string, g *GomegaWithT) {
err := run_opentofu(entryDir, "init")
g.Expect(err).To(BeNil(), "opentofu init failed")
}
func itShouldTerraformInit(entryDir string, g *GomegaWithT) {
err := run_terraform(entryDir, "init")
g.Expect(err).To(BeNil(), "terraform init failed")
}
func itShouldRunTerragruntValidate(entryDir string, g *GomegaWithT) {
err := run_terragrunt(entryDir, "validate")
g.Expect(err).To(BeNil(), "terragrunt validate failed")
}
func itShouldRunTerragruntInit(entryDir string, g *GomegaWithT) {
err := run_terragrunt(entryDir, "init")
g.Expect(err).To(BeNil(), "terragrunt init failed")
}
func getConfig(terraformDir string) (*TestCaseConfig, error) {
var config TestCaseConfig
viper.SetConfigType("yaml")
viper.SetConfigFile(fixtureDir + terraformDir + "/config.yaml")
if err := viper.ReadInConfig(); err != nil {
return nil, err
}
if err := viper.Unmarshal(&config); err != nil {
return nil, err
}
return &config, nil
}
func getEntries(t *testing.T, version string) []TestCase {
terraformDir := "/terraform_" + version
config, err := getConfig(terraformDir)
if err != nil {
t.Fatalf("failed to load test case config for version %s: %v", version, err)
}
suitesMap := make(map[string]interface{})
for _, suite := range config.Suites {
suitesMap[suite] = nil
}
const inputDirsMatcher = "/**/input/"
inputDirs, _ := doublestar.Glob(testsDir + inputDirsMatcher)
cloneOutput(inputDirs, terraformDir)
entryFilesMatcher := "/**/out" + terraformDir + "/**/main.tf"
entryFiles, _ := doublestar.Glob(testsDir + entryFilesMatcher)
testEntries := []TestCase{}
for _, entryFile := range entryFiles {
// convert windows paths to use forward slashes
slashed := filepath.ToSlash(entryFile)
entryDir := strings.TrimSuffix(slashed, "/main.tf")
terraformPathSplit := strings.Split(slashed, terraformDir)
pathBeforeTerraformDir := terraformPathSplit[0]
suiteDir := pathBeforeTerraformDir + terraformDir
suite := strings.Split(pathBeforeTerraformDir, "/")[2]
if _, ok := suitesMap[suite]; !ok {
// Not in configuration file. Skip test.
continue
}
testEntries = append(testEntries, TestCase{
suite: suite,
suiteDir: suiteDir,
entryDir: entryDir,
})
}
return testEntries
}
func cloneOutput(inputDirs []string, terraformDir string) {
for _, inputDir := range inputDirs {
outputDir := strings.TrimSuffix(inputDir, "input") + "out" + terraformDir
os.RemoveAll(outputDir)
copy.Copy(inputDir, outputDir)
}
}
func run_terratag(entryDir string, filter string, skip string, terragrunt bool) (err interface{}) {
defer func() {
if innerErr := recover(); innerErr != nil {
fmt.Println(innerErr)
err = innerErr
}
}()
osArgsLock.Lock()
os.Args = append(args, "-dir="+entryDir)
if filter != "" {
os.Args = append(os.Args, "-filter="+filter)
}
if skip != "" {
os.Args = append(os.Args, "-skip="+skip)
}
if terragrunt {
os.Args = append(os.Args, "-type=terragrunt", "-rename=false")
}
args, err := cli.InitArgs()
os.Args = cleanArgs
osArgsLock.Unlock()
if err != nil {
return err
}
return Terratag(args)
}
func run(prog string, entryDir string, cmd string) error {
println(prog, cmd)
var stdout bytes.Buffer
var stderr bytes.Buffer
command := exec.Command(prog, cmd)
command.Dir = entryDir
command.Stdout = &stdout
command.Stderr = &stderr
if err := command.Run(); err != nil {
log.Println(stderr.String())
return err
}
println(stdout.String())
return nil
}
func run_terraform(entryDir string, cmd string) error {
return run("terraform", entryDir, cmd)
}
func run_opentofu(entryDir string, cmd string) error {
return run("tofu", entryDir, cmd)
}
func run_terragrunt(entryDir string, cmd string) error {
return run("terragrunt", entryDir, cmd)
}
func filterSymlink(ss []string) (ret []string) {
for _, s := range ss {
resolvedSymlink, _ := filepath.EvalSymlinks(s)
if resolvedSymlink == s {
ret = append(ret, s)
}
}
return ret
}
func TestToHclMap(t *testing.T) {
validCases := map[string]string{
`{"a":"b","c":"d"}`: `{"a"="b","c"="d"}`,
`a=b,c=d`: `{"a"="b","c"="d"}`,
`a-key=b-value`: `{"a-key"="b-value"}`,
"{}": "{}",
}
for input, output := range validCases {
input, expectedOutput := input, output
t.Run("valid input "+input, func(t *testing.T) {
output, err := toHclMap(input)
require.NoError(t, err)
assert.Equal(t, expectedOutput, output)
})
}
invalidCases := []string{
"a$#$=b",
`{"a": {"b": "c"}}`,
"_a=b",
"5a=b",
"a=b!",
}
for i := range invalidCases {
input := invalidCases[i]
t.Run("invalid input "+input, func(t *testing.T) {
_, err := toHclMap(input)
assert.Error(t, err)
})
}
}
func TestEnvVariables(t *testing.T) {
os.Setenv("TERRATAG_TAGS", `{"a":"b"}`)
os.Setenv("TERRATAG_DIR", "./dir")
os.Setenv("TERRATAG_SKIPTERRATAGFILES", "true")
os.Setenv("TERRATAG_FILTER", "filter")
os.Setenv("TERRATAG_SKIP", "skip")
os.Setenv("TERRATAG_VERBOSE", "true")
os.Setenv("TERRATAG_RENAME", "false")
os.Setenv("TERRATAG_TYPE", string(common.Terragrunt))
defer func() {
os.Unsetenv("TERRATAG_TAGS")
os.Unsetenv("TERRATAG_DIR")
os.Unsetenv("TERRATAG_SKIPTERRATAGFILES")
os.Unsetenv("TERRATAG_FILTER")
os.Unsetenv("TERRATAG_SKIP")
os.Unsetenv("TERRATAG_VERBOSE")
os.Unsetenv("TERRATAG_RENAME")
os.Unsetenv("TERRATAG_TYPE")
}()
osArgsLock.Lock()
defer osArgsLock.Unlock()
os.Args = []string{programName}
args, err := cli.InitArgs()
os.Args = cleanArgs
require.NoError(t, err)
assert.Equal(t, `{"a":"b"}`, args.Tags)
assert.Equal(t, "./dir", args.Dir)
assert.True(t, args.IsSkipTerratagFiles)
assert.Equal(t, "filter", args.Filter)
assert.True(t, args.Verbose)
assert.False(t, args.Rename)
assert.Equal(t, string(common.Terragrunt), args.Type)
// The command line flags have precedence over environment variables.
os.Args = []string{programName, `-tags={"c":"d"}`}
args, err = cli.InitArgs()
os.Args = cleanArgs
require.NoError(t, err)
assert.Equal(t, `{"c":"d"}`, args.Tags)
}