forked from gruntwork-io/terratest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_structure.go
60 lines (52 loc) · 2.59 KB
/
test_structure.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
package test_structure
import (
"os"
"testing"
"path/filepath"
"fmt"
"strings"
"github.com/gruntwork-io/terratest/modules/logger"
"github.com/gruntwork-io/terratest/modules/files"
)
const SKIP_STAGE_ENV_VAR_PREFIX = "SKIP_"
// Execute the given test stage (e.g., setup, teardown, validation) if an environment variable of the name
// `SKIP_<stageName>` (e.g., SKIP_teardown) is not set.
func RunTestStage(t *testing.T, stageName string, stage func()) {
envVarName := fmt.Sprintf("%s%s", SKIP_STAGE_ENV_VAR_PREFIX, stageName)
if os.Getenv(envVarName) == "" {
logger.Logf(t, "The '%s' environment variable is not set, so executing stage '%s'.", envVarName, stageName)
stage()
} else {
logger.Logf(t, "The '%s' environment variable is set, so skipping stage '%s'.", envVarName, stageName)
}
}
// Returns true if an environment variable is set instructing Terratest to skip a test stage. This can be an easy way
// to tell if the tests are running in a local dev environment vs a CI server.
func SkipStageEnvVarSet() bool {
for _, environmentVariable := range os.Environ() {
if strings.HasPrefix(environmentVariable, SKIP_STAGE_ENV_VAR_PREFIX) {
return true
}
}
return false
}
// Copy the given root folder to a randomly-named temp folder and return the path to the given examples folder within
// the new temp root folder. This is useful when running multiple tests in parallel against the same set of Terraform
// files to ensure the tests don't overwrite each other's .terraform working directory and terraform.tfstate files. To
// ensure relative paths work, we copy over the entire root folder to a temp folder, and then return the path within
// that temp folder to the given example dir, which is where the actual test will be running.
//
// Note that if any of the SKIP_<stage> environment variables is set, we assume this is a test in the local dev where
// there are no other concurrent tests running and we want to be able to cache test data between test stages, so in
// that case, we do NOT copy anything to a temp folder, and return the path to the original examples folder instead.
func CopyTerraformFolderToTemp(t *testing.T, rootFolder string, examplesFolder string) string {
if SkipStageEnvVarSet() {
logger.Logf(t, "A SKIP_XXX environment variable is set. Using original examples folder rather than a temp folder so we can cache data between stages for faster local testing.")
return filepath.Join(rootFolder, examplesFolder)
}
tmpRootFolder, err := files.CopyTerraformFolderToTemp(rootFolder, t.Name())
if err != nil {
t.Fatal(err)
}
return filepath.Join(tmpRootFolder, examplesFolder)
}