Skip to content

Commit

Permalink
test: use t.Setenv to set env vars
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 <[email protected]>
  • Loading branch information
Juneezee authored and ale-linux committed May 17, 2023
1 parent 553ad62 commit aede199
Show file tree
Hide file tree
Showing 18 changed files with 74 additions and 201 deletions.
23 changes: 6 additions & 17 deletions bccsp/pkcs11/pkcs11_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"crypto/rand"
"crypto/sha256"
"encoding/asn1"
"os"
"strconv"
"strings"
"testing"
Expand Down Expand Up @@ -149,16 +148,10 @@ func TestFindPKCS11LibEnvVars(t *testing.T) {
dummy_PKCS11_LABEL = "testing"
)

// Set environment variables used for test and preserve
// original values for restoration after test completion
orig_PKCS11_LIB := os.Getenv("PKCS11_LIB")
orig_PKCS11_PIN := os.Getenv("PKCS11_PIN")
orig_PKCS11_LABEL := os.Getenv("PKCS11_LABEL")

t.Run("ExplicitEnvironment", func(t *testing.T) {
os.Setenv("PKCS11_LIB", dummy_PKCS11_LIB)
os.Setenv("PKCS11_PIN", dummy_PKCS11_PIN)
os.Setenv("PKCS11_LABEL", dummy_PKCS11_LABEL)
t.Setenv("PKCS11_LIB", dummy_PKCS11_LIB)
t.Setenv("PKCS11_PIN", dummy_PKCS11_PIN)
t.Setenv("PKCS11_LABEL", dummy_PKCS11_LABEL)

lib, pin, label := FindPKCS11Lib()
require.EqualValues(t, dummy_PKCS11_LIB, lib, "FindPKCS11Lib did not return expected library")
Expand All @@ -167,18 +160,14 @@ func TestFindPKCS11LibEnvVars(t *testing.T) {
})

t.Run("MissingEnvironment", func(t *testing.T) {
os.Unsetenv("PKCS11_LIB")
os.Unsetenv("PKCS11_PIN")
os.Unsetenv("PKCS11_LABEL")
t.Setenv("PKCS11_LIB", "")
t.Setenv("PKCS11_PIN", "")
t.Setenv("PKCS11_LABEL", "")

_, pin, label := FindPKCS11Lib()
require.EqualValues(t, "98765432", pin, "FindPKCS11Lib did not return expected pin")
require.EqualValues(t, "ForFabric", label, "FindPKCS11Lib did not return expected label")
})

os.Setenv("PKCS11_LIB", orig_PKCS11_LIB)
os.Setenv("PKCS11_PIN", orig_PKCS11_PIN)
os.Setenv("PKCS11_LABEL", orig_PKCS11_LABEL)
}

func TestInvalidSKI(t *testing.T) {
Expand Down
6 changes: 2 additions & 4 deletions cmd/configtxgen/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,7 @@ func TestConfigTxFlags(t *testing.T) {
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
}()

cleanup := configtest.SetDevFabricConfigPath(t)
defer cleanup()
configtest.SetDevFabricConfigPath(t)
devConfigDir := configtest.GetDevConfigDir()

os.Args = []string{
Expand Down Expand Up @@ -193,8 +192,7 @@ func TestBlockFlags(t *testing.T) {
"-outputBlock=" + blockDest,
"-inspectBlock=" + blockDest,
}
cleanup := configtest.SetDevFabricConfigPath(t)
defer cleanup()
configtest.SetDevFabricConfigPath(t)

main()

Expand Down
7 changes: 1 addition & 6 deletions common/flogging/logging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,7 @@ func TestNew(t *testing.T) {
}

func TestNewWithEnvironment(t *testing.T) {
oldSpec, set := os.LookupEnv("FABRIC_LOGGING_SPEC")
if set {
defer os.Setenv("FABRIC_LOGGING_SPEC", oldSpec)
}

os.Setenv("FABRIC_LOGGING_SPEC", "fatal")
t.Setenv("FABRIC_LOGGING_SPEC", "fatal")
logging, err := flogging.New(flogging.Config{})
require.NoError(t, err)
require.Equal(t, zapcore.FatalLevel, logging.DefaultLevel())
Expand Down
12 changes: 4 additions & 8 deletions common/viperutil/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ func TestEnvSlice(t *testing.T) {
}

envVar := testEnvPrefix + "_INNER_SLICE"
os.Setenv(envVar, "[a, b, c]")
defer os.Unsetenv(envVar)
t.Setenv(envVar, "[a, b, c]")

data := "---\nInner:\n Slice: [d,e,f]"

Expand Down Expand Up @@ -196,8 +195,7 @@ func TestPEMBlocksFromFileEnv(t *testing.T) {
require.NoError(t, err, "failed to write temp file")

envVar := testEnvPrefix + "_INNER_MULTIPLE_FILE"
defer os.Unsetenv(envVar)
os.Setenv(envVar, file.Name())
t.Setenv(envVar, file.Name())

testCases := []struct {
name string
Expand Down Expand Up @@ -246,8 +244,7 @@ func TestStringFromFileEnv(t *testing.T) {
require.NoError(t, err, "failed to write temp file")

envVar := testEnvPrefix + "_INNER_SINGLE_FILE"
defer os.Unsetenv(envVar)
os.Setenv(envVar, file.Name())
t.Setenv(envVar, file.Name())

testCases := []struct {
name string
Expand Down Expand Up @@ -294,8 +291,7 @@ func TestBCCSPDecodeHookOverride(t *testing.T) {
yaml := "---\nBCCSP:\n Default: default-provider\n SW:\n Security: 999\n"

overrideVar := testEnvPrefix + "_BCCSP_SW_SECURITY"
os.Setenv(overrideVar, "1111")
defer os.Unsetenv(overrideVar)
t.Setenv(overrideVar, "1111")

config := New()
config.SetConfigName(testConfigName)
Expand Down
43 changes: 7 additions & 36 deletions core/chaincode/platforms/golang/platform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ func TestName(t *testing.T) {
}

func TestValidatePath(t *testing.T) {
reset := setupGopath(t, "testdata")
defer reset()
setupGopath(t, "testdata")

tests := []struct {
path string
Expand Down Expand Up @@ -222,8 +221,7 @@ func tarContents(t *testing.T, payload []byte) []string {
}

func TestGopathDeploymentPayload(t *testing.T) {
reset := setupGopath(t, "testdata")
defer reset()
setupGopath(t, "testdata")

platform := &Platform{}

Expand Down Expand Up @@ -295,33 +293,15 @@ func TestModuleDeploymentPayload(t *testing.T) {
})
}

func setupGopath(t *testing.T, path string) func() {
initialGopath, gopathSet := os.LookupEnv("GOPATH")
initialGo111Module, go111ModuleSet := os.LookupEnv("GO111MODULE")

func setupGopath(t *testing.T, path string) {
if path == "" {
err := os.Unsetenv("GOPATH")
require.NoError(t, err)
} else {
absPath, err := filepath.Abs(path)
require.NoErrorf(t, err, "expected to calculate absolute path from %s", path)
err = os.Setenv("GOPATH", absPath)
require.NoError(t, err, "failed to set GOPATH")
err = os.Setenv("GO111MODULE", "off")
require.NoError(t, err, "failed set GO111MODULE")
}

return func() {
if !gopathSet {
os.Unsetenv("GOPATH")
} else {
os.Setenv("GOPATH", initialGopath)
}
if !go111ModuleSet {
os.Unsetenv("GO111MODULE")
} else {
os.Setenv("GO111MODULE", initialGo111Module)
}
t.Setenv("GOPATH", absPath)
t.Setenv("GO111MODULE", "off")
}
}

Expand Down Expand Up @@ -385,17 +365,8 @@ echo Done!
})

t.Run("GOPROXY and GOSUMDB set", func(t *testing.T) {
oldGoproxy, set := os.LookupEnv("GOPROXY")
if set {
defer os.Setenv("GOPROXY", oldGoproxy)
}
os.Setenv("GOPROXY", "the-goproxy")

oldGosumdb, set := os.LookupEnv("GOSUMDB")
if set {
defer os.Setenv("GOSUMDB", oldGosumdb)
}
os.Setenv("GOSUMDB", "the-gosumdb")
t.Setenv("GOPROXY", "the-goproxy")
t.Setenv("GOSUMDB", "the-gosumdb")

opts, err := platform.DockerBuildOptions("the-path")
require.NoError(t, err, "unexpected error from DockerBuildOptions")
Expand Down
21 changes: 2 additions & 19 deletions core/config/configtest/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
"testing"

"github.com/spf13/viper"
"github.com/stretchr/testify/require"
)

// AddDevConfigPath adds the DevConfigDir to the viper path.
Expand Down Expand Up @@ -101,23 +100,7 @@ func GetDevMspDir() string {
return filepath.Join(devDir, "msp")
}

func SetDevFabricConfigPath(t *testing.T) (cleanup func()) {
func SetDevFabricConfigPath(t *testing.T) {
t.Helper()

oldFabricCfgPath, resetFabricCfgPath := os.LookupEnv("FABRIC_CFG_PATH")
devConfigDir := GetDevConfigDir()

err := os.Setenv("FABRIC_CFG_PATH", devConfigDir)
require.NoError(t, err, "failed to set FABRIC_CFG_PATH")
if resetFabricCfgPath {
return func() {
err := os.Setenv("FABRIC_CFG_PATH", oldFabricCfgPath)
require.NoError(t, err)
}
}

return func() {
err := os.Unsetenv("FABRIC_CFG_PATH")
require.NoError(t, err)
}
t.Setenv("FABRIC_CFG_PATH", GetDevConfigDir())
}
4 changes: 1 addition & 3 deletions core/handlers/library/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ package library

import (
"bytes"
"os"
"strings"
"testing"

Expand Down Expand Up @@ -80,8 +79,7 @@ peer:
library:
`

os.Setenv("LIBTEST_PEER_HANDLERS_ENDORSERS_ESCC_LIBRARY", "/path/to/foo")
defer os.Unsetenv("LIBTEST_PEER_HANDLERS_ENDORSERS_ESCC_LIBRARY")
t.Setenv("LIBTEST_PEER_HANDLERS_ENDORSERS_ESCC_LIBRARY", "/path/to/foo")

defer viper.Reset()
viper.SetConfigType("yaml")
Expand Down
12 changes: 4 additions & 8 deletions internal/configtxgen/genesisconfig/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ import (
)

func TestLoadProfile(t *testing.T) {
cleanup := configtest.SetDevFabricConfigPath(t)
defer cleanup()
configtest.SetDevFabricConfigPath(t)

pNames := []string{
SampleDevModeSoloProfile,
Expand Down Expand Up @@ -53,8 +52,7 @@ func TestLoadProfileWithPath(t *testing.T) {
}

func TestLoadTopLevel(t *testing.T) {
cleanup := configtest.SetDevFabricConfigPath(t)
defer cleanup()
configtest.SetDevFabricConfigPath(t)

topLevel := LoadTopLevel()
require.NotNil(t, topLevel.Application, "application should not be nil")
Expand All @@ -76,8 +74,7 @@ func TestLoadTopLevelWithPath(t *testing.T) {
}

func TestConsensusSpecificInit(t *testing.T) {
cleanup := configtest.SetDevFabricConfigPath(t)
defer cleanup()
configtest.SetDevFabricConfigPath(t)

devConfigDir := configtest.GetDevConfigDir()

Expand Down Expand Up @@ -260,8 +257,7 @@ func TestConsensusSpecificInit(t *testing.T) {
}

func TestLoadConfigCache(t *testing.T) {
cleanup := configtest.SetDevFabricConfigPath(t)
defer cleanup()
configtest.SetDevFabricConfigPath(t)

cfg := viperutil.New()
devConfigDir := configtest.GetDevConfigDir()
Expand Down
3 changes: 1 addition & 2 deletions internal/peer/chaincode/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,8 +344,7 @@ func TestValidatePeerConnectionParams(t *testing.T) {
defer resetFlags()
defer viper.Reset()
require := require.New(t)
cleanup := configtest.SetDevFabricConfigPath(t)
defer cleanup()
configtest.SetDevFabricConfigPath(t)

// TLS disabled
viper.Set("peer.tls.enabled", false)
Expand Down
Loading

0 comments on commit aede199

Please sign in to comment.