spf13--viper/flags_test.go
David Calavera 66249a6550 Add FlagValue interface to support other flag systems.
Using an interface allows people to use their favourite flag system
with viper without being restricted to the semantics of pflag or the
standard library.

This change introduce two new functions `BindFlagValues` and
`BindFlagValue` that behave like `BindFlags` and `BindFlag` but using
the new interface as values.

This change also introduces two internal structures to transform
`*pflag.FlagSet` and `*pflag.Flag` into the new interface. This way,
viper keeps working as expected for people that are currently using the
pflag package without breaking backwards compatibility.

Signed-off-by: David Calavera <david.calavera@gmail.com>
2015-12-24 10:16:41 -05:00

66 lines
1.3 KiB
Go

package viper
import (
"testing"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
)
func TestBindFlagValueSet(t *testing.T) {
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
var testValues = map[string]*string{
"host": nil,
"port": nil,
"endpoint": nil,
}
var mutatedTestValues = map[string]string{
"host": "localhost",
"port": "6060",
"endpoint": "/public",
}
for name, _ := range testValues {
testValues[name] = flagSet.String(name, "", "test")
}
flagValueSet := pflagValueSet{flagSet}
err := BindFlagValues(flagValueSet)
if err != nil {
t.Fatalf("error binding flag set, %v", err)
}
flagSet.VisitAll(func(flag *pflag.Flag) {
flag.Value.Set(mutatedTestValues[flag.Name])
flag.Changed = true
})
for name, expected := range mutatedTestValues {
assert.Equal(t, Get(name), expected)
}
}
func TestBindFlagValue(t *testing.T) {
var testString = "testing"
var testValue = newStringValue(testString, &testString)
flag := &pflag.Flag{
Name: "testflag",
Value: testValue,
Changed: false,
}
flagValue := pflagValue{flag}
BindFlagValue("testvalue", flagValue)
assert.Equal(t, testString, Get("testvalue"))
flag.Value.Set("testing_mutate")
flag.Changed = true //hack for pflag usage
assert.Equal(t, "testing_mutate", Get("testvalue"))
}