Skip to content

Commit

Permalink
Support upstream time.ParseDuration (prometheus#117)
Browse files Browse the repository at this point in the history
This change supports model time.ParseDuration and is backwards
compatible with upstream.

Also added a small Makefile to mimic what Travis is currently doing.

Signed-off-by: John McFarlane <john@rockfloat.com>
  • Loading branch information
jmcfarlane committed Jun 4, 2018
1 parent 7600349 commit caaa610
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
5 changes: 5 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
get:
go get -t -v ./...

test:
go test -v ./...
4 changes: 4 additions & 0 deletions model/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,10 @@ var durationRE = regexp.MustCompile("^([0-9]+)(y|w|d|h|m|s|ms)$")
func ParseDuration(durationStr string) (Duration, error) {
matches := durationRE.FindStringSubmatch(durationStr)
if len(matches) != 3 {
// If single unit validation fails, still support time.ParseDuration
if d, err := time.ParseDuration(durationStr); err == nil {
return Duration(d), nil
}
return 0, fmt.Errorf("not a valid duration string: %q", durationStr)
}
var (
Expand Down
33 changes: 32 additions & 1 deletion model/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,18 @@ func TestParseDuration(t *testing.T) {
in: "10y",
out: 10 * 365 * 24 * time.Hour,
},

// Test compatibility with time.Duration
{
in: "5m0s",
out: 5 * time.Minute,
}, {
in: "5m4s",
out: 5*time.Minute + time.Second*4,
}, {
in: "5m4s3ns",
out: 5*time.Minute + time.Second*4 + time.Nanosecond*3,
},
}

for _, c := range cases {
Expand All @@ -126,7 +138,26 @@ func TestParseDuration(t *testing.T) {
t.Errorf("Expected %v but got %v", c.out, d)
}
if d.String() != c.in {
t.Errorf("Expected duration string %q but got %q", c.in, d.String())
// If the string representations differ but are logically
// the same consider this a non error condition.
if c.out.Nanoseconds() != time.Duration(d).Nanoseconds() {
t.Errorf("Expected duration string %q but got %q", c.in, d.String())
}
}
}
}

func TestParseDurationInvalidFormats(t *testing.T) {
for _, invalid := range []string{
// Not a duration
"",
// Seemingly valid duration, but is neither single unit nor upstream
"5w0s",
// Assumption about units
"5",
} {
if _, err := ParseDuration(invalid); err == nil {
t.Errorf("Expected error on invalid input %q", invalid)
}
}
}

0 comments on commit caaa610

Please sign in to comment.