Skip to content

Commit

Permalink
Add function to require an env var is defined in test (#1061)
Browse files Browse the repository at this point in the history
  • Loading branch information
yorinasub17 authored Feb 12, 2022
1 parent 6047680 commit 08558f5
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
6 changes: 6 additions & 0 deletions modules/environment/envvar.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}
59 changes: 59 additions & 0 deletions modules/environment/envvar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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)
}

0 comments on commit 08558f5

Please sign in to comment.