From aede199a7b92ab95c4f983b24d6acab9b7b93e2a Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Wed, 10 May 2023 18:40:04 +0800 Subject: [PATCH] test: use `t.Setenv` to set env vars 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 --- bccsp/pkcs11/pkcs11_test.go | 23 ++------ cmd/configtxgen/main_test.go | 6 +- common/flogging/logging_test.go | 7 +-- common/viperutil/config_test.go | 12 ++-- .../platforms/golang/platform_test.go | 43 +++------------ core/config/configtest/config.go | 21 +------ core/handlers/library/config_test.go | 4 +- .../configtxgen/genesisconfig/config_test.go | 12 ++-- internal/peer/chaincode/common_test.go | 3 +- internal/peer/channel/create_test.go | 30 ++++------ internal/peer/channel/fetch_test.go | 6 +- internal/peer/common/common_test.go | 18 ++---- internal/peer/common/deliverclient_test.go | 6 +- internal/peer/common/ordererclient_test.go | 4 +- internal/peer/common/peerclient_test.go | 4 +- orderer/common/localconfig/config_test.go | 55 ++++++------------- orderer/common/server/main_test.go | 17 ++---- orderer/common/server/util_test.go | 4 +- 18 files changed, 74 insertions(+), 201 deletions(-) diff --git a/bccsp/pkcs11/pkcs11_test.go b/bccsp/pkcs11/pkcs11_test.go index 2aa96ccee60..a8bdafacd1f 100644 --- a/bccsp/pkcs11/pkcs11_test.go +++ b/bccsp/pkcs11/pkcs11_test.go @@ -14,7 +14,6 @@ import ( "crypto/rand" "crypto/sha256" "encoding/asn1" - "os" "strconv" "strings" "testing" @@ -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") @@ -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) { diff --git a/cmd/configtxgen/main_test.go b/cmd/configtxgen/main_test.go index 24afa3ca37c..dd8d8cd26ce 100644 --- a/cmd/configtxgen/main_test.go +++ b/cmd/configtxgen/main_test.go @@ -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{ @@ -193,8 +192,7 @@ func TestBlockFlags(t *testing.T) { "-outputBlock=" + blockDest, "-inspectBlock=" + blockDest, } - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) main() diff --git a/common/flogging/logging_test.go b/common/flogging/logging_test.go index 8a5eb8620db..e836fadbabd 100644 --- a/common/flogging/logging_test.go +++ b/common/flogging/logging_test.go @@ -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()) diff --git a/common/viperutil/config_test.go b/common/viperutil/config_test.go index f50aae4237b..52708d4bc5c 100644 --- a/common/viperutil/config_test.go +++ b/common/viperutil/config_test.go @@ -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]" @@ -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 @@ -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 @@ -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) diff --git a/core/chaincode/platforms/golang/platform_test.go b/core/chaincode/platforms/golang/platform_test.go index 32565b4dbe4..41769cc2ea7 100644 --- a/core/chaincode/platforms/golang/platform_test.go +++ b/core/chaincode/platforms/golang/platform_test.go @@ -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 @@ -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{} @@ -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") } } @@ -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") diff --git a/core/config/configtest/config.go b/core/config/configtest/config.go index c7fc9cfdd48..0042b362354 100644 --- a/core/config/configtest/config.go +++ b/core/config/configtest/config.go @@ -17,7 +17,6 @@ import ( "testing" "github.com/spf13/viper" - "github.com/stretchr/testify/require" ) // AddDevConfigPath adds the DevConfigDir to the viper path. @@ -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()) } diff --git a/core/handlers/library/config_test.go b/core/handlers/library/config_test.go index 26ae76046ab..ff36983dbe4 100644 --- a/core/handlers/library/config_test.go +++ b/core/handlers/library/config_test.go @@ -8,7 +8,6 @@ package library import ( "bytes" - "os" "strings" "testing" @@ -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") diff --git a/internal/configtxgen/genesisconfig/config_test.go b/internal/configtxgen/genesisconfig/config_test.go index a5b1e894669..0c2e64d8981 100644 --- a/internal/configtxgen/genesisconfig/config_test.go +++ b/internal/configtxgen/genesisconfig/config_test.go @@ -16,8 +16,7 @@ import ( ) func TestLoadProfile(t *testing.T) { - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) pNames := []string{ SampleDevModeSoloProfile, @@ -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") @@ -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() @@ -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() diff --git a/internal/peer/chaincode/common_test.go b/internal/peer/chaincode/common_test.go index dbda4455bc7..885779a6337 100644 --- a/internal/peer/chaincode/common_test.go +++ b/internal/peer/chaincode/common_test.go @@ -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) diff --git a/internal/peer/channel/create_test.go b/internal/peer/channel/create_test.go index e044c227652..89b556fba64 100644 --- a/internal/peer/channel/create_test.go +++ b/internal/peer/channel/create_test.go @@ -153,8 +153,7 @@ func TestCreateChain(t *testing.T) { defer resetFlags() InitMSP() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) mockchain := "mockchain" @@ -194,8 +193,7 @@ func TestCreateChainWithOutputBlock(t *testing.T) { defer resetFlags() InitMSP() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) mockchain := "mockchain" @@ -231,8 +229,7 @@ func TestCreateChainWithDefaultAnchorPeers(t *testing.T) { defer resetFlags() InitMSP() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) mockchain := "mockchain" @@ -264,8 +261,7 @@ func TestCreateChainWithWaitSuccess(t *testing.T) { defer resetFlags() InitMSP() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) mockchain := "mockchain" @@ -298,8 +294,7 @@ func TestCreateChainWithTimeoutErr(t *testing.T) { defer resetFlags() InitMSP() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) mockchain := "mockchain" @@ -345,8 +340,7 @@ func TestCreateChainBCFail(t *testing.T) { defer resetFlags() InitMSP() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) mockchain := "mockchain" @@ -385,8 +379,7 @@ func TestCreateChainDeliverFail(t *testing.T) { defer resetFlags() InitMSP() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) mockchain := "mockchain" @@ -449,8 +442,7 @@ func createTxFile(filename string, typ cb.HeaderType, channelID string) (*cb.Env func TestCreateChainFromTx(t *testing.T) { defer resetFlags() InitMSP() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) mockchannel := "mockchannel" dir := t.TempDir() @@ -507,8 +499,7 @@ func TestCreateChainInvalidTx(t *testing.T) { defer resetFlags() InitMSP() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) mockchannel := "mockchannel" @@ -578,8 +569,7 @@ func TestCreateChainNilCF(t *testing.T) { defer resetFlags() InitMSP() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) mockchannel := "mockchannel" dir := t.TempDir() diff --git a/internal/peer/channel/fetch_test.go b/internal/peer/channel/fetch_test.go index 8aaa68934c5..91230690d4e 100644 --- a/internal/peer/channel/fetch_test.go +++ b/internal/peer/channel/fetch_test.go @@ -27,8 +27,7 @@ func TestFetch(t *testing.T) { defer resetFlags() InitMSP() resetFlags() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) mockchain := "mockchain" @@ -111,8 +110,7 @@ func TestFetchNilCF(t *testing.T) { InitMSP() resetFlags() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) mockchain := "mockchain" viper.Set("peer.client.connTimeout", 10*time.Millisecond) diff --git a/internal/peer/common/common_test.go b/internal/peer/common/common_test.go index dd2a568d311..b1f52faea7a 100644 --- a/internal/peer/common/common_test.go +++ b/internal/peer/common/common_test.go @@ -39,8 +39,7 @@ import ( ) func TestInitConfig(t *testing.T) { - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) type args struct { cmdRoot string @@ -109,9 +108,8 @@ func TestSetBCCSPKeystorePath(t *testing.T) { require.NoError(t, err) keystorePath := "/msp/keystore" - defer os.Unsetenv("FABRIC_CFG_PATH") - os.Setenv("FABRIC_CFG_PATH", cfgPath) + t.Setenv("FABRIC_CFG_PATH", cfgPath) viper.Reset() err = common.InitConfig("notset") require.NoError(t, err) @@ -205,8 +203,7 @@ func TestGetDefaultSigner(t *testing.T) { } func TestInitCmd(t *testing.T) { - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) defer viper.Reset() // test that InitCmd doesn't remove existing loggers from the logger levels map @@ -219,19 +216,16 @@ func TestInitCmd(t *testing.T) { flogging.ActivateSpec("test.test2=warn") require.Equal(t, "warn", flogging.LoggerLevel("test.test2")) - origEnvValue := os.Getenv("FABRIC_LOGGING_SPEC") - os.Setenv("FABRIC_LOGGING_SPEC", "chaincode=debug:test.test2=fatal:abc=error") + t.Setenv("FABRIC_LOGGING_SPEC", "chaincode=debug:test.test2=fatal:abc=error") common.InitCmd(&cobra.Command{}, nil) require.Equal(t, "debug", flogging.LoggerLevel("chaincode")) require.Equal(t, "info", flogging.LoggerLevel("test")) require.Equal(t, "fatal", flogging.LoggerLevel("test.test2")) require.Equal(t, "error", flogging.LoggerLevel("abc")) - os.Setenv("FABRIC_LOGGING_SPEC", origEnvValue) } func TestInitCmdWithoutInitCrypto(t *testing.T) { - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) defer viper.Reset() peerCmd := &cobra.Command{ @@ -261,7 +255,7 @@ func TestInitCmdWithoutInitCrypto(t *testing.T) { replacer := strings.NewReplacer(".", "_") viper.SetEnvKeyReplacer(replacer) dir := os.TempDir() + "/" + util.GenerateUUID() - os.Setenv("CORE_PEER_MSPCONFIGPATH", dir) + t.Setenv("CORE_PEER_MSPCONFIGPATH", dir) common.InitCmd(packageCmd, nil) } diff --git a/internal/peer/common/deliverclient_test.go b/internal/peer/common/deliverclient_test.go index 5810d53aacb..cad5ca914ef 100644 --- a/internal/peer/common/deliverclient_test.go +++ b/internal/peer/common/deliverclient_test.go @@ -125,8 +125,7 @@ func TestSeekHelper(t *testing.T) { func TestNewOrdererDeliverClient(t *testing.T) { defer viper.Reset() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) InitMSP() // failure - rootcert file doesn't exist @@ -140,8 +139,7 @@ func TestNewOrdererDeliverClient(t *testing.T) { func TestNewDeliverClientForPeer(t *testing.T) { defer viper.Reset() - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) InitMSP() // failure - rootcert file doesn't exist diff --git a/internal/peer/common/ordererclient_test.go b/internal/peer/common/ordererclient_test.go index 4530d12e7c1..1b889ec9f56 100644 --- a/internal/peer/common/ordererclient_test.go +++ b/internal/peer/common/ordererclient_test.go @@ -58,7 +58,7 @@ orderer: _, err = configFile.WriteString(configStr) require.NoError(t, err) - os.Setenv("FABRIC_CFG_PATH", cfgPath) + t.Setenv("FABRIC_CFG_PATH", cfgPath) viper.Reset() _ = common.InitConfig("test") ca, err := tlsgen.NewCA() @@ -100,8 +100,6 @@ QjUeWEu3crkxMvjq4vYh3LaDREuhRANCAAR+FujNKcGQW/CEpMU6Yp45ye2cbOwJ require.NoError(t, err) return func() { - err := os.Unsetenv("FABRIC_CFG_PATH") - require.NoError(t, err) viper.Reset() } } diff --git a/internal/peer/common/peerclient_test.go b/internal/peer/common/peerclient_test.go index 8ced6a98c25..fe6b62d2d85 100644 --- a/internal/peer/common/peerclient_test.go +++ b/internal/peer/common/peerclient_test.go @@ -60,7 +60,7 @@ orderer: _, err = configFile.WriteString(configStr) require.NoError(t, err) - os.Setenv("FABRIC_CFG_PATH", cfgPath) + t.Setenv("FABRIC_CFG_PATH", cfgPath) viper.Reset() _ = common.InitConfig("test") ca, err := tlsgen.NewCA() @@ -102,8 +102,6 @@ QjUeWEu3crkxMvjq4vYh3LaDREuhRANCAAR+FujNKcGQW/CEpMU6Yp45ye2cbOwJ require.NoError(t, err) return cfgPath, func() { - err := os.Unsetenv("FABRIC_CFG_PATH") - require.NoError(t, err) viper.Reset() } } diff --git a/orderer/common/localconfig/config_test.go b/orderer/common/localconfig/config_test.go index b3e690c2a90..62d924dc8f9 100644 --- a/orderer/common/localconfig/config_test.go +++ b/orderer/common/localconfig/config_test.go @@ -16,8 +16,7 @@ import ( ) func TestLoadGoodConfig(t *testing.T) { - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) cc := &configCache{} cfg, err := cc.load() require.NoError(t, err) @@ -27,8 +26,7 @@ func TestLoadGoodConfig(t *testing.T) { func TestMissingConfigValueOverridden(t *testing.T) { t.Run("when the value is missing and not overridden", func(t *testing.T) { - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) cc := &configCache{} cfg, err := cc.load() require.NotNil(t, cfg, "Could not load config") @@ -37,9 +35,8 @@ func TestMissingConfigValueOverridden(t *testing.T) { }) t.Run("when the value is missing and is overridden", func(t *testing.T) { - os.Setenv("ORDERER_GENERAL_TLS_CLIENTROOTCAS", "msp/tlscacerts/tlsroot.pem") - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + t.Setenv("ORDERER_GENERAL_TLS_CLIENTROOTCAS", "msp/tlscacerts/tlsroot.pem") + configtest.SetDevFabricConfigPath(t) cache := &configCache{} cfg, err := cache.load() require.NotNil(t, cfg, "Could not load config") @@ -49,14 +46,13 @@ func TestMissingConfigValueOverridden(t *testing.T) { } func TestLoadCached(t *testing.T) { - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) // Load the initial config, update the environment, and load again. // With the caching behavior, the update should not be reflected initial, err := Load() require.NoError(t, err) - os.Setenv("ORDERER_GENERAL_KEEPALIVE_SERVERTIMEOUT", "120s") + t.Setenv("ORDERER_GENERAL_KEEPALIVE_SERVERTIMEOUT", "120s") updated, err := Load() require.NoError(t, err) require.Equal(t, initial, updated, "expected %#v to equal %#v", updated, initial) @@ -70,10 +66,7 @@ func TestLoadCached(t *testing.T) { } func TestLoadMissingConfigFile(t *testing.T) { - envVar1 := "FABRIC_CFG_PATH" - envVal1 := "invalid fabric cfg path" - os.Setenv(envVar1, envVal1) - defer os.Unsetenv(envVar1) + t.Setenv("FABRIC_CFG_PATH", "invalid fabric cfg path") cc := &configCache{} cfg, err := cc.load() @@ -90,10 +83,7 @@ func TestLoadMalformedConfigFile(t *testing.T) { f.WriteString("General: 42") require.NoError(t, f.Close(), "Error closing file") - envVar1 := "FABRIC_CFG_PATH" - envVal1 := name - os.Setenv(envVar1, envVal1) - defer os.Unsetenv(envVar1) + t.Setenv("FABRIC_CFG_PATH", name) cc := &configCache{} cfg, err := cc.load() @@ -110,12 +100,9 @@ func TestEnvInnerVar(t *testing.T) { envVal1 := uint16(80) envVar2 := "ORDERER_GENERAL_KEEPALIVE_SERVERTIMEOUT" envVal2 := "42s" - os.Setenv(envVar1, fmt.Sprintf("%d", envVal1)) - os.Setenv(envVar2, envVal2) - defer os.Unsetenv(envVar1) - defer os.Unsetenv(envVar2) - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + t.Setenv(envVar1, fmt.Sprintf("%d", envVal1)) + t.Setenv(envVar2, envVal2) + configtest.SetDevFabricConfigPath(t) cc := &configCache{} config, err := cc.load() @@ -172,8 +159,7 @@ func TestAdminTLSConfig(t *testing.T) { } func TestClusterDefaults(t *testing.T) { - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) cc := &configCache{} cfg, err := cc.load() @@ -196,10 +182,7 @@ Consensus: f.WriteString(content) require.NoError(t, f.Close(), "Error closing file") - envVar1 := "FABRIC_CFG_PATH" - envVal1 := name - os.Setenv(envVar1, envVal1) - defer os.Unsetenv(envVar1) + t.Setenv("FABRIC_CFG_PATH", name) cc := &configCache{} conf, err := cc.load() @@ -223,8 +206,7 @@ Consensus: func TestConnectionTimeout(t *testing.T) { t.Run("without connection timeout overridden", func(t *testing.T) { - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) cc := &configCache{} cfg, err := cc.load() require.NotNil(t, cfg, "Could not load config") @@ -233,10 +215,8 @@ func TestConnectionTimeout(t *testing.T) { }) t.Run("with connection timeout overridden", func(t *testing.T) { - os.Setenv("ORDERER_GENERAL_CONNECTIONTIMEOUT", "10s") - defer os.Unsetenv("ORDERER_GENERAL_CONNECTIONTIMEOUT") - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + t.Setenv("ORDERER_GENERAL_CONNECTIONTIMEOUT", "10s") + configtest.SetDevFabricConfigPath(t) cc := &configCache{} cfg, err := cc.load() @@ -247,8 +227,7 @@ func TestConnectionTimeout(t *testing.T) { } func TestChannelParticipationDefaults(t *testing.T) { - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) cc := &configCache{} cfg, err := cc.load() diff --git a/orderer/common/server/main_test.go b/orderer/common/server/main_test.go index 1b39a86a714..09fbc59201c 100644 --- a/orderer/common/server/main_test.go +++ b/orderer/common/server/main_test.go @@ -87,17 +87,13 @@ func copyYamlFiles(src, dst string) { } func TestInitializeLogging(t *testing.T) { - origEnvValue := os.Getenv("FABRIC_LOGGING_SPEC") - os.Setenv("FABRIC_LOGGING_SPEC", "foo=debug") + t.Setenv("FABRIC_LOGGING_SPEC", "foo=debug") initializeLogging() require.Equal(t, "debug", flogging.LoggerLevel("foo")) - os.Setenv("FABRIC_LOGGING_SPEC", origEnvValue) } func TestInitializeProfilingService(t *testing.T) { - origEnvValue := os.Getenv("FABRIC_LOGGING_SPEC") - defer os.Setenv("FABRIC_LOGGING_SPEC", origEnvValue) - os.Setenv("FABRIC_LOGGING_SPEC", "debug") + t.Setenv("FABRIC_LOGGING_SPEC", "debug") // get a free random port listenAddr := func() string { l, _ := net.Listen("tcp", "localhost:0") @@ -327,8 +323,7 @@ func TestInitializeServerConfig(t *testing.T) { } func TestVerifyNoSystemChannelJoinBlock(t *testing.T) { - configPathCleanup := configtest.SetDevFabricConfigPath(t) - defer configPathCleanup() + configtest.SetDevFabricConfigPath(t) tmpDir := t.TempDir() copyYamlFiles("testdata", tmpDir) @@ -491,8 +486,7 @@ func TestLoadLocalMSP(t *testing.T) { } func TestInitializeMultichannelRegistrar(t *testing.T) { - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) tmpDir := t.TempDir() copyYamlFiles("testdata", tmpDir) @@ -562,8 +556,7 @@ func generateCryptoMaterials(t *testing.T, cryptogen, tmpDir string) string { } func TestUpdateTrustedRoots(t *testing.T) { - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) tmpDir := t.TempDir() copyYamlFiles("testdata", tmpDir) diff --git a/orderer/common/server/util_test.go b/orderer/common/server/util_test.go index a66f2e578d5..f5db0791ed2 100644 --- a/orderer/common/server/util_test.go +++ b/orderer/common/server/util_test.go @@ -22,8 +22,8 @@ import ( ) func TestCreateLedgerFactory(t *testing.T) { - cleanup := configtest.SetDevFabricConfigPath(t) - defer cleanup() + configtest.SetDevFabricConfigPath(t) + testCases := []struct { name string ledgerDir string