Fixe `ToDurationE()`

It used to return zero valeus in some cases. The details are described
in [this issue](https://github.com/spf13/viper/issues/203). More cases
were also added in the unit test `TestToDuration()`
This commit is contained in:
Chih-Hung Yeh 2016-09-20 04:24:24 +08:00 committed by Bjørn Erik Pedersen
parent 4532b05430
commit fa673d63c1
2 changed files with 34 additions and 11 deletions

View File

@ -174,10 +174,29 @@ func TestIndirectPointers(t *testing.T) {
} }
func TestToDuration(t *testing.T) { func TestToDuration(t *testing.T) {
a := time.Second * 5 var td time.Duration = 5
ai := int64(a) tests := []struct {
b := time.Second * 5 input interface{}
bf := float64(b) expected time.Duration
assert.Equal(t, ToDuration(ai), a) }{
assert.Equal(t, ToDuration(bf), b) {time.Duration(5), td},
{int64(5), td},
{int32(5), td},
{int16(5), td},
{int8(5), td},
{int(5), td},
{float64(5), td},
{float32(5), td},
{string("5"), td},
{string("5ns"), td},
{string("5us"), time.Microsecond * td},
{string("5µs"), time.Microsecond * td},
{string("5ms"), time.Millisecond * td},
{string("5s"), time.Second * td},
{string("5m"), time.Minute * td},
{string("5h"), time.Hour * td},
}
for _, v := range tests {
assert.Equal(t, v.expected, ToDuration(v.input))
}
} }

View File

@ -43,14 +43,18 @@ func ToDurationE(i interface{}) (d time.Duration, err error) {
switch s := i.(type) { switch s := i.(type) {
case time.Duration: case time.Duration:
return s, nil return s, nil
case int64: case int64, int32, int16, int8, int:
d = time.Duration(s) d = time.Duration(ToInt64(s))
return return
case float64: case float32, float64:
d = time.Duration(s) d = time.Duration(ToFloat64(s))
return return
case string: case string:
d, err = time.ParseDuration(s) if strings.ContainsAny(s, "nsuµmh") {
d, err = time.ParseDuration(s)
} else {
d, err = time.ParseDuration(s + "ns")
}
return return
default: default:
err = fmt.Errorf("Unable to Cast %#v to Duration\n", i) err = fmt.Errorf("Unable to Cast %#v to Duration\n", i)