Skip to content

Commit

Permalink
timeout: add YAML unmarshaler
Browse files Browse the repository at this point in the history
Signed-off-by: Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
  • Loading branch information
zyga committed May 2, 2016
1 parent e038a08 commit 809df3f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
13 changes: 13 additions & 0 deletions timeout/timeout.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,19 @@ func (t *Timeout) UnmarshalJSON(buf []byte) error {
return nil
}

func (t *Timeout) UnmarshalYAML(unmarshal func(interface{}) error) error {
var str string
if err := unmarshal(&str); err != nil {
return err
}
dur, err := time.ParseDuration(str)
if err != nil {
return err
}
*t = Timeout(dur)
return nil
}

// String returns a string representing the duration
func (t Timeout) String() string {
return time.Duration(t).String()
Expand Down
11 changes: 9 additions & 2 deletions timeout/timeout_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"time"

. "gopkg.in/check.v1"
"gopkg.in/yaml.v2"
)

// Hook up check.v1 into the "go test" runner
Expand All @@ -42,7 +43,7 @@ func (s *TimeoutTestSuite) TestTimeoutMarshal(c *C) {
}

type testT struct {
T Timeout
T Timeout `yaml:"T"`
}

func (s *TimeoutTestSuite) TestTimeoutMarshalIndirect(c *C) {
Expand All @@ -51,8 +52,14 @@ func (s *TimeoutTestSuite) TestTimeoutMarshalIndirect(c *C) {
c.Check(string(bs), Equals, `{"T":"30s"}`)
}

func (s *TimeoutTestSuite) TestTimeoutUnmarshal(c *C) {
func (s *TimeoutTestSuite) TestTimeoutUnmarshalJSON(c *C) {
var t testT
c.Assert(json.Unmarshal([]byte(`{"T": "17ms"}`), &t), IsNil)
c.Check(t, DeepEquals, testT{T: Timeout(17 * time.Millisecond)})
}

func (s *TimeoutTestSuite) TestTimeoutUnmarshalYAML(c *C) {
var t testT
c.Assert(yaml.Unmarshal([]byte(`T: 17ms`), &t), IsNil)
c.Check(t, DeepEquals, testT{T: Timeout(17 * time.Millisecond)})
}

0 comments on commit 809df3f

Please sign in to comment.