github.com/mponton/terratest@v0.44.0/modules/environment/envvar_test.go (about) 1 package environment 2 3 import ( 4 "os" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 // MockT is used to test that the function under test will fail the test under certain circumstances. 11 type MockT struct { 12 Failed bool 13 } 14 15 func (t *MockT) Fail() { 16 t.Failed = true 17 } 18 19 func (t *MockT) FailNow() { 20 t.Failed = true 21 } 22 23 func (t *MockT) Error(args ...interface{}) { 24 t.Failed = true 25 } 26 27 func (t *MockT) Errorf(format string, args ...interface{}) { 28 t.Failed = true 29 } 30 31 func (t *MockT) Fatal(args ...interface{}) { 32 t.Failed = true 33 } 34 35 func (t *MockT) Fatalf(format string, args ...interface{}) { 36 t.Failed = true 37 } 38 39 func (t *MockT) Name() string { 40 return "mockT" 41 } 42 43 // End MockT 44 45 var envvarList = []string{ 46 "TERRATEST_TEST_ENVIRONMENT", 47 "TERRATESTTESTENVIRONMENT", 48 "TERRATESTENVIRONMENT", 49 } 50 51 func TestGetFirstNonEmptyEnvVarOrEmptyStringChecksInOrder(t *testing.T) { 52 // These tests can not run in parallel, since they manipulate env vars 53 // DO NOT ADD THIS: t.Parallel() 54 55 os.Setenv("TERRATESTTESTENVIRONMENT", "test") 56 os.Setenv("TERRATESTENVIRONMENT", "circleCI") 57 defer os.Setenv("TERRATESTTESTENVIRONMENT", "") 58 defer os.Setenv("TERRATESTENVIRONMENT", "") 59 value := GetFirstNonEmptyEnvVarOrEmptyString(t, envvarList) 60 assert.Equal(t, value, "test") 61 } 62 63 func TestGetFirstNonEmptyEnvVarOrEmptyStringReturnsEmpty(t *testing.T) { 64 // These tests can not run in parallel, since they manipulate env vars 65 // DO NOT ADD THIS: t.Parallel() 66 67 value := GetFirstNonEmptyEnvVarOrEmptyString(t, envvarList) 68 assert.Equal(t, value, "") 69 } 70 71 func TestRequireEnvVarFails(t *testing.T) { 72 // These tests can not run in parallel, since they manipulate env vars 73 // DO NOT ADD THIS: t.Parallel() 74 75 envVarName := "TERRATESTTESTENVIRONMENT" 76 mockT := new(MockT) 77 78 // Make sure the check fails when env var is not set 79 RequireEnvVar(mockT, envVarName) 80 assert.True(t, mockT.Failed) 81 } 82 83 func TestRequireEnvVarPasses(t *testing.T) { 84 // These tests can not run in parallel, since they manipulate env vars 85 // DO NOT ADD THIS: t.Parallel() 86 87 envVarName := "TERRATESTTESTENVIRONMENT" 88 89 // Make sure the check passes when env var is set 90 os.Setenv(envVarName, "test") 91 defer os.Setenv(envVarName, "") 92 RequireEnvVar(t, envVarName) 93 }