github.com/ahlemtn/fabric@v2.1.1+incompatible/core/config/configtest/config.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package configtest 8 9 import ( 10 "os" 11 "path/filepath" 12 "testing" 13 14 "github.com/spf13/viper" 15 "github.com/stretchr/testify/assert" 16 "github.com/stretchr/testify/require" 17 ) 18 19 // AddDevConfigPath adds the DevConfigDir to the viper path. 20 func AddDevConfigPath(v *viper.Viper) { 21 devPath := GetDevConfigDir() 22 if v != nil { 23 v.AddConfigPath(devPath) 24 } else { 25 viper.AddConfigPath(devPath) 26 } 27 } 28 29 func dirExists(path string) bool { 30 fi, err := os.Stat(path) 31 if err != nil { 32 return false 33 } 34 return fi.IsDir() 35 } 36 37 // GetDevConfigDir gets the path to the default configuration that is 38 // maintained with the source tree. This should only be used in a 39 // test/development context. 40 func GetDevConfigDir() string { 41 gopath := os.Getenv("GOPATH") 42 for _, p := range filepath.SplitList(gopath) { 43 devPath := filepath.Join(p, "src/github.com/hyperledger/fabric/sampleconfig") 44 if dirExists(devPath) { 45 return devPath 46 } 47 } 48 49 panic("unable to find sampleconfig directory on gopath") 50 } 51 52 // GetDevMspDir gets the path to the sampleconfig/msp tree that is maintained 53 // with the source tree. This should only be used in a test/development 54 // context. 55 func GetDevMspDir() string { 56 devDir := GetDevConfigDir() 57 return filepath.Join(devDir, "msp") 58 } 59 60 func SetDevFabricConfigPath(t *testing.T) (cleanup func()) { 61 t.Helper() 62 63 oldFabricCfgPath, resetFabricCfgPath := os.LookupEnv("FABRIC_CFG_PATH") 64 devConfigDir := GetDevConfigDir() 65 66 err := os.Setenv("FABRIC_CFG_PATH", devConfigDir) 67 require.NoError(t, err, "failed to set FABRIC_CFG_PATH") 68 if resetFabricCfgPath { 69 return func() { 70 err := os.Setenv("FABRIC_CFG_PATH", oldFabricCfgPath) 71 assert.NoError(t, err) 72 } 73 } 74 75 return func() { 76 err := os.Unsetenv("FABRIC_CFG_PATH") 77 assert.NoError(t, err) 78 } 79 }