From 45b9ea7b4e980a09b24d9d854b754199f449c59e Mon Sep 17 00:00:00 2001 From: Nutmos Date: Tue, 9 Feb 2021 16:23:38 +0700 Subject: [PATCH] Prometheus: Min step defaults to seconds when no unit is set to prevent errors when running alerts. (#30966) * update interval to fix no unit * fix bug * update with new method * format go * add test * change test method to add test error nil * add simplejson and model package * change json format * add parentheses * add simplejson to function * change mode to model * move assert import package * add one enter to avoid goimport error * change to test case --- pkg/tsdb/interval.go | 8 ++++++++ pkg/tsdb/interval_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/pkg/tsdb/interval.go b/pkg/tsdb/interval.go index dd6eab539c7..781cd30b41a 100644 --- a/pkg/tsdb/interval.go +++ b/pkg/tsdb/interval.go @@ -2,6 +2,7 @@ package tsdb import ( "fmt" + "regexp" "strings" "time" @@ -81,6 +82,13 @@ func GetIntervalFrom(dsInfo *models.DataSource, queryModel *simplejson.Json, def } interval = strings.Replace(strings.Replace(interval, "<", "", 1), ">", "", 1) + isPureNum, err := regexp.MatchString(`^\d+$`, interval) + if err != nil { + return time.Duration(0), err + } + if isPureNum { + interval += "s" + } parsedInterval, err := time.ParseDuration(interval) if err != nil { return time.Duration(0), err diff --git a/pkg/tsdb/interval_test.go b/pkg/tsdb/interval_test.go index d4c273d942d..bb9edbb5c29 100644 --- a/pkg/tsdb/interval_test.go +++ b/pkg/tsdb/interval_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + "github.com/grafana/grafana/pkg/components/simplejson" + "github.com/grafana/grafana/pkg/models" "github.com/stretchr/testify/assert" ) @@ -65,3 +67,26 @@ func TestFormatDuration(t *testing.T) { }) } } + +func TestGetIntervalFrom(t *testing.T) { + testCases := []struct { + name string + dsInfo *models.DataSource + queryModel string + defaultInterval time.Duration + expected time.Duration + }{ + {"45s", nil, `{"interval": "45s"}`, time.Second * 15, time.Second * 45}, + {"45", nil, `{"interval": "45"}`, time.Second * 15, time.Second * 45}, + {"2m", nil, `{"interval": "2m"}`, time.Second * 15, time.Minute * 2}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + js, _ := simplejson.NewJson([]byte(tc.queryModel)) + actual, err := GetIntervalFrom(tc.dsInfo, js, tc.defaultInterval) + assert.Nil(t, err) + assert.Equal(t, tc.expected, actual) + }) + } +}