Skip to content

Commit

Permalink
test: use t.Setenv to set env vars (#180)
Browse files Browse the repository at this point in the history
This commit replaces `os.Setenv` with `t.Setenv` in tests. The
environment variable is automatically restored to its original value
when the test and all its subtests complete.

Reference: https://pkg.go.dev/testing#T.Setenv

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
  • Loading branch information
Juneezee committed Feb 27, 2023
1 parent 877a0b4 commit 6974692
Show file tree
Hide file tree
Showing 5 changed files with 18 additions and 65 deletions.
13 changes: 2 additions & 11 deletions core/authenticator_factory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,17 @@ package core
// limitations under the License.

import (
"os"
"testing"

"github.com/stretchr/testify/assert"
)

// Note: the following functions are used from the config_utils_test.go file:
// setTestEnvironment()
// clearTestEnvironment()
// setTestVCAP()
// clearTestVCAP()

func TestGetAuthenticatorFromEnvironment1(t *testing.T) {
os.Setenv("IBM_CREDENTIALS_FILE", "../resources/my-credentials.env")
t.Setenv("IBM_CREDENTIALS_FILE", "../resources/my-credentials.env")

authenticator, err := GetAuthenticatorFromEnvironment("service-1")
assert.Nil(t, err)
Expand Down Expand Up @@ -122,12 +119,10 @@ func TestGetAuthenticatorFromEnvironment1(t *testing.T) {
assert.Equal(t, "user1", iamAuth.ClientId)
assert.Equal(t, "secret1", iamAuth.ClientSecret)
assert.Equal(t, "https://iam.refresh-token.com", iamAuth.URL)

os.Unsetenv("IBM_CREDENTIALS_FILE")
}

func TestGetAuthenticatorFromEnvironment2(t *testing.T) {
setTestEnvironment()
setTestEnvironment(t)

authenticator, err := GetAuthenticatorFromEnvironment("service-1")
assert.Nil(t, err)
Expand Down Expand Up @@ -212,8 +207,6 @@ func TestGetAuthenticatorFromEnvironment2(t *testing.T) {
assert.True(t, ok)
assert.NotNil(t, containerAuth)
assert.Equal(t, "iam-user2", containerAuth.IAMProfileName)

clearTestEnvironment()
}

func TestGetAuthenticatorFromEnvironment3(t *testing.T) {
Expand All @@ -233,6 +226,4 @@ func TestGetAuthenticatorFromEnvironment3(t *testing.T) {
assert.Nil(t, err)
assert.NotNil(t, authenticator)
assert.Equal(t, AUTHTYPE_IAM, authenticator.AuthenticationType())

clearTestVCAP()
}
27 changes: 6 additions & 21 deletions core/base_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1825,7 +1825,7 @@ func TestSetEnableGzipCompression(t *testing.T) {
func TestExtConfigFromCredentialFile(t *testing.T) {
pwd, _ := os.Getwd()
credentialFilePath := path.Join(pwd, "/../resources/my-credentials.env")
os.Setenv("IBM_CREDENTIALS_FILE", credentialFilePath)
t.Setenv("IBM_CREDENTIALS_FILE", credentialFilePath)

service, _ := NewBaseService(
&ServiceOptions{
Expand Down Expand Up @@ -1889,14 +1889,12 @@ func TestExtConfigFromCredentialFile(t *testing.T) {
assert.NotNil(t, actualClient)
assert.Equal(t, int(5), actualClient.RetryMax)
assert.Equal(t, time.Duration(10)*time.Second, actualClient.RetryWaitMax)

os.Unsetenv("IBM_CREDENTIALS_FILE")
}

func TestExtConfigError(t *testing.T) {
pwd, _ := os.Getwd()
credentialFilePath := path.Join(pwd, "/../resources/my-credentials.env")
os.Setenv("IBM_CREDENTIALS_FILE", credentialFilePath)
t.Setenv("IBM_CREDENTIALS_FILE", credentialFilePath)

service, _ := NewBaseService(
&ServiceOptions{
Expand All @@ -1905,12 +1903,10 @@ func TestExtConfigError(t *testing.T) {
})
err := service.ConfigureService("error4")
assert.NotNil(t, err)

os.Unsetenv("IBM_CREDENTIALS_FILE")
}

func TestExtConfigFromEnvironment(t *testing.T) {
setTestEnvironment()
setTestEnvironment(t)

service, _ := NewBaseService(
&ServiceOptions{
Expand All @@ -1923,8 +1919,6 @@ func TestExtConfigFromEnvironment(t *testing.T) {
assert.Equal(t, "https://service3/api", service.Options.URL)
assert.False(t, service.IsSSLDisabled())
assert.False(t, service.GetEnableGzipCompression())

clearTestEnvironment()
}

func TestExtConfigFromVCAP(t *testing.T) {
Expand All @@ -1940,8 +1934,6 @@ func TestExtConfigFromVCAP(t *testing.T) {
assert.NotNil(t, service)
assert.Equal(t, "https://service2/api", service.Options.URL)
assert.False(t, service.IsSSLDisabled())

clearTestVCAP()
}

func TestConfigureServiceFromCredFile(t *testing.T) {
Expand All @@ -1957,16 +1949,14 @@ func TestConfigureServiceFromCredFile(t *testing.T) {

pwd, _ := os.Getwd()
credentialFilePath := path.Join(pwd, "/../resources/my-credentials.env")
os.Setenv("IBM_CREDENTIALS_FILE", credentialFilePath)
t.Setenv("IBM_CREDENTIALS_FILE", credentialFilePath)

err = service.ConfigureService("service5")
assert.Nil(t, err)
assert.NotNil(t, service)
assert.Equal(t, "https://service5/api", service.Options.URL)
assert.True(t, service.IsSSLDisabled())
assert.False(t, service.GetEnableGzipCompression())

os.Unsetenv("IBM_CREDENTIALS_FILE")
}

func TestConfigureServiceFromVCAP(t *testing.T) {
Expand All @@ -1985,8 +1975,6 @@ func TestConfigureServiceFromVCAP(t *testing.T) {
assert.NotNil(t, service)
assert.Equal(t, "https://service3/api", service.Options.URL)
assert.False(t, service.IsSSLDisabled())

clearTestVCAP()
}

func TestConfigureServiceFromEnv(t *testing.T) {
Expand All @@ -2000,20 +1988,18 @@ func TestConfigureServiceFromEnv(t *testing.T) {
assert.Equal(t, "bad url", service.Options.URL)
assert.False(t, service.IsSSLDisabled())

setTestEnvironment()
setTestEnvironment(t)
err = service.ConfigureService("service_1")
assert.Nil(t, err)
assert.NotNil(t, service)
assert.Equal(t, "https://service1/api", service.Options.URL)
assert.True(t, service.IsSSLDisabled())

clearTestEnvironment()
}

func TestConfigureServiceError(t *testing.T) {
pwd, _ := os.Getwd()
credentialFilePath := path.Join(pwd, "/../resources/my-credentials.env")
os.Setenv("IBM_CREDENTIALS_FILE", credentialFilePath)
t.Setenv("IBM_CREDENTIALS_FILE", credentialFilePath)

service, err := NewBaseService(
&ServiceOptions{
Expand All @@ -2023,7 +2009,6 @@ func TestConfigureServiceError(t *testing.T) {
assert.Nil(t, err)
err = service.ConfigureService("")
assert.NotNil(t, err)
os.Unsetenv("IBM_CREDENTIALS_FILE")
}

func TestAuthNotConfigured(t *testing.T) {
Expand Down
16 changes: 5 additions & 11 deletions core/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ package core
import (
"bytes"
"encoding/json"
"os"
"testing"
)

// (C) Copyright IBM Corp. 2020.
Expand Down Expand Up @@ -89,16 +89,10 @@ var testEnvironment = map[string]string{
"SERVICE13_IAM_PROFILE_NAME": "iam-user2",
}

// Set the environment variables described in our map.
func setTestEnvironment() {
// setTestEnvironment sets the environment variables described in our map.
// The environment variables are restored to its original value after the test.
func setTestEnvironment(t *testing.T) {
for key, value := range testEnvironment {
os.Setenv(key, value)
}
}

// Clear the test-related environment variables.
func clearTestEnvironment() {
for key := range testEnvironment {
os.Unsetenv(key)
t.Setenv(key, value)
}
}
24 changes: 4 additions & 20 deletions core/config_utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,10 @@ const vcapServicesKey = "VCAP_SERVICES"
func setTestVCAP(t *testing.T) {
data, err := os.ReadFile("../resources/vcap_services.json")
if assert.Nil(t, err) {
os.Setenv(vcapServicesKey, string(data))
t.Setenv(vcapServicesKey, string(data))
}
}

func clearTestVCAP() {
os.Unsetenv(vcapServicesKey)
}

func TestGetServicePropertiesError(t *testing.T) {
_, err := getServiceProperties("")
assert.NotNil(t, err)
Expand All @@ -54,7 +50,7 @@ func TestGetServicePropertiesNoConfig(t *testing.T) {
func TestGetServicePropertiesFromCredentialFile(t *testing.T) {
pwd, _ := os.Getwd()
credentialFilePath := path.Join(pwd, "/../resources/my-credentials.env")
os.Setenv("IBM_CREDENTIALS_FILE", credentialFilePath)
t.Setenv("IBM_CREDENTIALS_FILE", credentialFilePath)

props, err := GetServiceProperties("service-1")
assert.Nil(t, err)
Expand Down Expand Up @@ -108,12 +104,10 @@ func TestGetServicePropertiesFromCredentialFile(t *testing.T) {
assert.Equal(t, "my-api-key", props[PROPNAME_APIKEY])
assert.Equal(t, "https://iamhost/iam/api", props[PROPNAME_AUTH_URL])
assert.Equal(t, "scope1 scope2 scope3", props[PROPNAME_SCOPE])

os.Unsetenv("IBM_CREDENTIALS_FILE")
}

func TestGetServicePropertiesFromEnvironment(t *testing.T) {
setTestEnvironment()
setTestEnvironment(t)

props, err := GetServiceProperties("service-1")
assert.Nil(t, err)
Expand Down Expand Up @@ -166,9 +160,6 @@ func TestGetServicePropertiesFromEnvironment(t *testing.T) {
assert.Equal(t, "iam", props[PROPNAME_AUTH_TYPE])
assert.Equal(t, "my-api-key", props[PROPNAME_APIKEY])
assert.Equal(t, "A B C D", props[PROPNAME_SCOPE])

clearTestEnvironment()
assert.Equal(t, "", os.Getenv("SERVICE_1_URL"))
}

func TestGetServicePropertiesFromVCAP(t *testing.T) {
Expand Down Expand Up @@ -200,8 +191,6 @@ func TestGetServicePropertiesFromVCAP(t *testing.T) {
assert.Equal(t, "", props[PROPNAME_USERNAME])
assert.Equal(t, "", props[PROPNAME_PASSWORD])
assert.Equal(t, strings.ToUpper(AUTHTYPE_IAM), strings.ToUpper(props[PROPNAME_AUTH_TYPE]))

clearTestVCAP()
}

func TestLoadFromVCAPServicesWithServiceEntries(t *testing.T) {
Expand Down Expand Up @@ -231,27 +220,23 @@ func TestLoadFromVCAPServicesWithServiceEntries(t *testing.T) {
assert.Equal(t, "not-a-username-3", credential3.Username)
assert.Equal(t, "not-a-password-3", credential3.Password)
assert.Equal(t, "https://on.the.toolchainplatform.net/devops-insights-3/api", credential3.URL)
clearTestVCAP()
}

func TestLoadFromVCAPServicesEmptyService(t *testing.T) {
setTestVCAP(t)
// Verify we checked service entry names first
credential := loadFromVCAPServices("empty_service")
assert.Nil(t, credential, "Credentials should not be nil")
clearTestVCAP()
}

func TestLoadFromVCAPServicesNoCredentials(t *testing.T) {
setTestVCAP(t)
// Verify we checked service entry names first
credential := loadFromVCAPServices("no-creds-service")
assert.Nil(t, credential)
clearTestVCAP()
}

func TestLoadFromVCAPServicesWithEmptyString(t *testing.T) {
clearTestVCAP()
credential := loadFromVCAPServices("watson")
assert.Nil(t, credential, "Credentials should nil")
}
Expand All @@ -267,8 +252,7 @@ func TestLoadFromVCAPServicesWithInvalidJSON(t *testing.T) {
}
}]
}`
os.Setenv("VCAP_SERVICES", vcapServicesFail)
t.Setenv("VCAP_SERVICES", vcapServicesFail)
credential := loadFromVCAPServices("watson")
assert.Nil(t, credential, "Credentials should be nil")
os.Unsetenv("VCAP_SERVICES")
}
3 changes: 1 addition & 2 deletions core/iam_authenticator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -1136,7 +1135,7 @@ func TestIamLiveTokenServer(t *testing.T) {
var tokenServerResponse *IamTokenServerResponse

// Get an iam authenticator from the environment.
os.Setenv("IBM_CREDENTIALS_FILE", "../../iamtest.env")
t.Setenv("IBM_CREDENTIALS_FILE", "../../iamtest.env")

auth, err := GetAuthenticatorFromEnvironment("iamtest1")
assert.Nil(t, err)
Expand Down

0 comments on commit 6974692

Please sign in to comment.