diff --git a/modules/environment/envvar.go b/modules/environment/envvar.go index cfcbe075a..7a91dd415 100644 --- a/modules/environment/envvar.go +++ b/modules/environment/envvar.go @@ -4,6 +4,7 @@ import ( "os" "github.com/gruntwork-io/terratest/modules/testing" + "github.com/stretchr/testify/require" ) // GetFirstNonEmptyEnvVarOrFatal returns the first non-empty environment variable from envVarNames, or throws a fatal @@ -27,3 +28,8 @@ func GetFirstNonEmptyEnvVarOrEmptyString(t testing.TestingT, envVarNames []strin return "" } + +// RequireEnvVar fails the test if the specified environment variable is not defined or is blank. +func RequireEnvVar(t testing.TestingT, envVarName string) { + require.NotEmptyf(t, os.Getenv(envVarName), "Environment variable %s must be set for this test.", envVarName) +} diff --git a/modules/environment/envvar_test.go b/modules/environment/envvar_test.go index 707ec8d4a..11e3743d2 100644 --- a/modules/environment/envvar_test.go +++ b/modules/environment/envvar_test.go @@ -7,6 +7,41 @@ import ( "github.com/stretchr/testify/assert" ) +// MockT is used to test that the function under test will fail the test under certain circumstances. +type MockT struct { + Failed bool +} + +func (t *MockT) Fail() { + t.Failed = true +} + +func (t *MockT) FailNow() { + t.Failed = true +} + +func (t *MockT) Error(args ...interface{}) { + t.Failed = true +} + +func (t *MockT) Errorf(format string, args ...interface{}) { + t.Failed = true +} + +func (t *MockT) Fatal(args ...interface{}) { + t.Failed = true +} + +func (t *MockT) Fatalf(format string, args ...interface{}) { + t.Failed = true +} + +func (t *MockT) Name() string { + return "mockT" +} + +// End MockT + var envvarList = []string{ "TERRATEST_TEST_ENVIRONMENT", "TERRATESTTESTENVIRONMENT", @@ -32,3 +67,27 @@ func TestGetFirstNonEmptyEnvVarOrEmptyStringReturnsEmpty(t *testing.T) { value := GetFirstNonEmptyEnvVarOrEmptyString(t, envvarList) assert.Equal(t, value, "") } + +func TestRequireEnvVarFails(t *testing.T) { + // These tests can not run in parallel, since they manipulate env vars + // DO NOT ADD THIS: t.Parallel() + + envVarName := "TERRATESTTESTENVIRONMENT" + mockT := new(MockT) + + // Make sure the check fails when env var is not set + RequireEnvVar(mockT, envVarName) + assert.True(t, mockT.Failed) +} + +func TestRequireEnvVarPasses(t *testing.T) { + // These tests can not run in parallel, since they manipulate env vars + // DO NOT ADD THIS: t.Parallel() + + envVarName := "TERRATESTTESTENVIRONMENT" + + // Make sure the check passes when env var is set + os.Setenv(envVarName, "test") + defer os.Setenv(envVarName, "") + RequireEnvVar(t, envVarName) +}