lib/duration: Implement encoding.TextUnmarshaler
This commit is contained in:
parent
d892d1693d
commit
5ca13ff9e5
|
@ -18,14 +18,8 @@ type Duration struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
// UnmarshalTOML parses a duration string.
|
// UnmarshalTOML parses a duration string.
|
||||||
func (d *Duration) UnmarshalTOML(dataInterface interface{}) error {
|
func (d *Duration) UnmarshalText(data []byte) error {
|
||||||
var data string
|
|
||||||
switch dataInterface.(type) {
|
|
||||||
case string:
|
|
||||||
data = dataInterface.(string)
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("invalid duration: \"%s\"", dataInterface)
|
|
||||||
}
|
|
||||||
// " + int + unit + "
|
// " + int + unit + "
|
||||||
if len(data) < 2 {
|
if len(data) < 2 {
|
||||||
return fmt.Errorf("invalid duration: \"%s\"", data)
|
return fmt.Errorf("invalid duration: \"%s\"", data)
|
||||||
|
|
|
@ -16,6 +16,8 @@ func TestDuration(t *testing.T) {
|
||||||
duration time.Duration
|
duration time.Duration
|
||||||
}{
|
}{
|
||||||
{"", "invalid duration: \"\"", 0},
|
{"", "invalid duration: \"\"", 0},
|
||||||
|
{"3", "invalid duration: \"3\"", 0},
|
||||||
|
{"am", "unable to parse duration \"am\": strconv.Atoi: parsing \"a\": invalid syntax", 0},
|
||||||
{"1x", "invalid duration unit \"x\"", 0},
|
{"1x", "invalid duration unit \"x\"", 0},
|
||||||
{"1s", "", time.Second},
|
{"1s", "", time.Second},
|
||||||
{"73s", "", time.Second * 73},
|
{"73s", "", time.Second * 73},
|
||||||
|
@ -34,7 +36,7 @@ func TestDuration(t *testing.T) {
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
|
|
||||||
d := Duration{}
|
d := Duration{}
|
||||||
err := d.UnmarshalTOML(test.input)
|
err := d.UnmarshalText([]byte(test.input))
|
||||||
duration := d.Duration
|
duration := d.Duration
|
||||||
|
|
||||||
if test.err == "" {
|
if test.err == "" {
|
||||||
|
@ -44,13 +46,4 @@ func TestDuration(t *testing.T) {
|
||||||
assert.EqualError(err, test.err)
|
assert.EqualError(err, test.err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
d := Duration{}
|
|
||||||
err := d.UnmarshalTOML(3)
|
|
||||||
assert.Error(err)
|
|
||||||
assert.Contains(err.Error(), "invalid duration")
|
|
||||||
|
|
||||||
err = d.UnmarshalTOML("am")
|
|
||||||
assert.Error(err)
|
|
||||||
assert.EqualError(err, "unable to parse duration \"am\": strconv.Atoi: parsing \"a\": invalid syntax")
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue