Skip to content

Commit 3dae578

Browse files
author
Julien Pivotto
authored
Merge pull request #270 from metalmatze/duration-encoding-text
Add MarshalText and UnmarshalText for Duration
2 parents 1537f7d + ee8cd20 commit 3dae578

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

model/time.go

+12
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,18 @@ func (d Duration) String() string {
254254
return r
255255
}
256256

257+
// MarshalText implements the encoding.TextMarshaler interface.
258+
func (d *Duration) MarshalText() ([]byte, error) {
259+
return []byte(d.String()), nil
260+
}
261+
262+
// UnmarshalText implements the encoding.TextUnmarshaler interface.
263+
func (d *Duration) UnmarshalText(text []byte) error {
264+
var err error
265+
*d, err = ParseDuration(string(text))
266+
return err
267+
}
268+
257269
// MarshalYAML implements the yaml.Marshaler interface.
258270
func (d Duration) MarshalYAML() (interface{}, error) {
259271
return d.String(), nil

model/time_test.go

+73
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,79 @@ func TestParseDuration(t *testing.T) {
157157
}
158158
}
159159

160+
func TestDuration_UnmarshalText(t *testing.T) {
161+
var cases = []struct {
162+
in string
163+
out time.Duration
164+
165+
expectedString string
166+
}{
167+
{
168+
in: "0",
169+
out: 0,
170+
expectedString: "0s",
171+
}, {
172+
in: "0w",
173+
out: 0,
174+
expectedString: "0s",
175+
}, {
176+
in: "0s",
177+
out: 0,
178+
}, {
179+
in: "324ms",
180+
out: 324 * time.Millisecond,
181+
}, {
182+
in: "3s",
183+
out: 3 * time.Second,
184+
}, {
185+
in: "5m",
186+
out: 5 * time.Minute,
187+
}, {
188+
in: "1h",
189+
out: time.Hour,
190+
}, {
191+
in: "4d",
192+
out: 4 * 24 * time.Hour,
193+
}, {
194+
in: "4d1h",
195+
out: 4*24*time.Hour + time.Hour,
196+
}, {
197+
in: "14d",
198+
out: 14 * 24 * time.Hour,
199+
expectedString: "2w",
200+
}, {
201+
in: "3w",
202+
out: 3 * 7 * 24 * time.Hour,
203+
}, {
204+
in: "3w2d1h",
205+
out: 3*7*24*time.Hour + 2*24*time.Hour + time.Hour,
206+
expectedString: "23d1h",
207+
}, {
208+
in: "10y",
209+
out: 10 * 365 * 24 * time.Hour,
210+
},
211+
}
212+
213+
for _, c := range cases {
214+
var d Duration
215+
err := d.UnmarshalText([]byte(c.in))
216+
if err != nil {
217+
t.Errorf("Unexpected error on input %q", c.in)
218+
}
219+
if time.Duration(d) != c.out {
220+
t.Errorf("Expected %v but got %v", c.out, d)
221+
}
222+
expectedString := c.expectedString
223+
if c.expectedString == "" {
224+
expectedString = c.in
225+
}
226+
text, _ := d.MarshalText() // MarshalText returns hardcoded nil
227+
if string(text) != expectedString {
228+
t.Errorf("Expected duration string %q but got %q", c.in, d.String())
229+
}
230+
}
231+
}
232+
160233
func TestParseBadDuration(t *testing.T) {
161234
var cases = []string{
162235
"1",

0 commit comments

Comments
 (0)