Skip to content

Instantly share code, notes, and snippets.

@jayunit100
Created September 3, 2016 14:11
Show Gist options
  • Save jayunit100/82836f49ab71831ed65fa029b7c59b2c to your computer and use it in GitHub Desktop.
Save jayunit100/82836f49ab71831ed65fa029b7c59b2c to your computer and use it in GitHub Desktop.
package main
// import "fmt"
import "testing"
import "os"
import "github.com/spf13/viper"
func AssertKV(t *testing.T, k string, v string){
t.Log("Viper: Asserting %v = %v ",k,v)
if viper.Get(k) != v{
viper.Debug()
t.Fail()
}
}
func AssertSlice(t *testing.T, k string, v string, elem int){
t.Log("Viper: Asserting SLICE %v [%v] = %v ",k, elem, v)
if viper.GetStringSlice(k)[elem]!= v{
t.Log("FAILING : %v (%v) != %v",viper.Get(k), elem, v)
viper.Debug()
t.Fail()
}
}
func TestCombinations(t *testing.T) {
viper.Reset()
// ENV Vars
/** Read an environment variable for the dog food
* export VIPER_DOOGFOOD="puppy chow"
*/
viper.SetEnvPrefix("viper")
os.Setenv("VIPER_DOGFOOD", "puppy chow")
// Viper: Read it in as "dogfood"
viper.BindEnv("dogfood")
AssertKV(t, "dogfood","puppy chow")
// Json or YAML
/**
* Now read some more stuff, from a json test.json file.
* Read from json for the cat food
*/
viper.SetConfigName("test")
viper.AddConfigPath(".")
viper.ReadInConfig()
// Hierarchichal parameters
/**
The json file provided also has another nested parameter...
"purina":{
"ingredients":["lamb","corn"]
}
*/
// Viper will Read it in as purina.ingredients a []string
AssertKV(t, "dogfood","puppy chow")
AssertSlice(t, "purina.ingredients","lamb",0)
AssertSlice(t, "purina.ingredients","corn",1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment