github.com/hyperledger/burrow@v0.34.5-0.20220512172541-77f09336001d/config/source/source_test.go (about) 1 package source 2 3 import ( 4 "io/ioutil" 5 "os" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 "github.com/stretchr/testify/require" 10 ) 11 12 func TestEnvironment(t *testing.T) { 13 envVar := "FISH_SPOON_ALPHA" 14 jsonString := JSONString(newTestConfig()) 15 os.Setenv(envVar, jsonString) 16 conf := new(animalConfig) 17 err := Environment(envVar).Apply(conf) 18 assert.NoError(t, err) 19 assert.Equal(t, jsonString, JSONString(conf)) 20 } 21 22 func TestDeepCopy(t *testing.T) { 23 conf := newTestConfig() 24 confCopy, err := DeepCopy(conf) 25 require.NoError(t, err) 26 assert.Equal(t, conf, confCopy) 27 } 28 29 func TestFile(t *testing.T) { 30 tomlString := TOMLString(newTestConfig()) 31 file := writeConfigFile(t, newTestConfig()) 32 defer os.Remove(file) 33 conf := new(animalConfig) 34 err := File(file, false).Apply(conf) 35 assert.NoError(t, err) 36 assert.Equal(t, tomlString, TOMLString(conf)) 37 } 38 39 func TestCascade(t *testing.T) { 40 envVar := "FISH_SPOON_ALPHA" 41 // Both fall through so baseConfig returned 42 conf := newTestConfig() 43 err := Cascade(true, 44 Environment(envVar), 45 File("", false)).Apply(conf) 46 assert.NoError(t, err) 47 assert.Equal(t, newTestConfig(), conf) 48 49 // Env not set so falls through to file 50 fileConfig := newTestConfig() 51 file := writeConfigFile(t, fileConfig) 52 defer os.Remove(file) 53 conf = new(animalConfig) 54 err = Cascade(true, 55 Environment(envVar), 56 File(file, false)).Apply(conf) 57 assert.NoError(t, err) 58 assert.Equal(t, TOMLString(fileConfig), TOMLString(conf)) 59 60 // Env set so caught by environment source 61 envConfig := animalConfig{ 62 Name: "Slug", 63 NumLegs: 0, 64 } 65 os.Setenv(envVar, JSONString(envConfig)) 66 conf = newTestConfig() 67 err = Cascade(true, 68 Environment(envVar), 69 File(file, false)).Apply(conf) 70 assert.NoError(t, err) 71 assert.Equal(t, TOMLString(envConfig), TOMLString(conf)) 72 } 73 74 func TestDetectFormat(t *testing.T) { 75 assert.Equal(t, TOML, DetectFormat("")) 76 assert.Equal(t, JSON, DetectFormat("{")) 77 assert.Equal(t, JSON, DetectFormat("\n\n\t \n\n {")) 78 assert.Equal(t, TOML, DetectFormat("[Tendermint]\n Seeds =\"foobar@val0\"}")) 79 } 80 81 func writeConfigFile(t *testing.T, conf interface{}) string { 82 tomlString := TOMLString(conf) 83 f, err := ioutil.TempFile("", "source-test.toml") 84 assert.NoError(t, err) 85 f.Write(([]byte)(tomlString)) 86 f.Close() 87 return f.Name() 88 } 89 90 // Test types 91 92 type legConfig struct { 93 Leg int 94 Colour byte 95 } 96 97 type animalConfig struct { 98 Name string 99 NumLegs int 100 Legs []legConfig 101 } 102 103 func newTestConfig() *animalConfig { 104 return &animalConfig{ 105 Name: "Froggy!", 106 NumLegs: 2, 107 Legs: []legConfig{ 108 { 109 Leg: 1, 110 Colour: 034, 111 }, 112 { 113 Leg: 2, 114 Colour: 034, 115 }, 116 }, 117 } 118 }