From 0eeaa4c84e08dd27a913c5a64c1d307f9559e985 Mon Sep 17 00:00:00 2001 From: Joel Scoble Date: Fri, 21 Nov 2014 23:17:17 -0600 Subject: [PATCH] fix version command so that it will work with all supported config formats and added tests --- commands/version.go | 14 +++++++- commands/version_test.go | 71 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 commands/version_test.go diff --git a/commands/version.go b/commands/version.go index 3d1b2b069..b38393357 100644 --- a/commands/version.go +++ b/commands/version.go @@ -87,7 +87,19 @@ func getDateFormat() string { if params == nil { return time.RFC3339 } - parms := params.(map[string]interface{}) + + // var typMapIfaceIface = reflect.TypeOf(map[interface{}{}]interface{}{}) + // var typMapStringIface = reflect.TypeOf(map[string]interface{}{}) + parms := map[string]interface{}{} + switch params.(type) { + case map[interface{}]interface{}: + for k, v := range params.(map[interface{}]interface{}) { + parms[k.(string)] = v + } + case map[string]interface{}: + parms = params.(map[string]interface{}) + } + layout := parms["DateFormat"] if layout == nil || layout == "" { return time.RFC3339 diff --git a/commands/version_test.go b/commands/version_test.go new file mode 100644 index 000000000..b530efd6e --- /dev/null +++ b/commands/version_test.go @@ -0,0 +1,71 @@ +package commands + +import ( + "io/ioutil" + "testing" + + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" +) + +// config json +var JSONConfig = []byte(`{ + "params": { + "DateFormat": "Jan 2 2006" + } +}`) + +// config toml +var TOMLConfig = []byte(` +[params] +DateFormat = "Jan 2 2006" +`) + +// config yaml +var YAMLConfig = []byte(` +params: + DateFormat: "Jan 2 2006" +`) + +var config map[string]interface{} = make(map[string]interface{}) + +func TestGetDateFormatJSON(t *testing.T) { + jsonFile, _ := ioutil.TempFile("", "config.json") + fname := jsonFile.Name() + jsonFile.Write(JSONConfig) + jsonFile.Close() + viper.SetConfigFile(fname) + viper.SetConfigType("json") + viper.ReadInConfig() + + dateFmt := getDateFormat() + assert.Equal(t, "Jan 2 2006", dateFmt) +} + +func TestGetDateFormatTOML(t *testing.T) { + viper.Reset() + tomlFile, _ := ioutil.TempFile("", "config.toml") + fname := tomlFile.Name() + tomlFile.Write(TOMLConfig) + tomlFile.Close() + viper.SetConfigFile(fname) + viper.SetConfigType("toml") + viper.ReadInConfig() + + dateFmt := getDateFormat() + assert.Equal(t, "Jan 2 2006", dateFmt) +} + +func TestGetDateFormatYAML(t *testing.T) { + viper.Reset() + yamlFile, _ := ioutil.TempFile("", "config.yaml") + fname := yamlFile.Name() + yamlFile.Write(YAMLConfig) + yamlFile.Close() + viper.SetConfigFile(fname) + viper.SetConfigType("yaml") + viper.ReadInConfig() + + dateFmt := getDateFormat() + assert.Equal(t, "Jan 2 2006", dateFmt) +}