grafana/pkg/tsdb/influxdb/query_builder_test.go

73 lines
2.3 KiB
Go
Raw Normal View History

2016-10-05 03:56:34 -05:00
package influxdb
import (
"testing"
"github.com/grafana/grafana/pkg/tsdb"
2016-10-05 03:56:34 -05:00
. "github.com/smartystreets/goconvey/convey"
)
func TestInfluxdbQueryBuilder(t *testing.T) {
2016-10-05 03:56:34 -05:00
Convey("Influxdb query builder", t, func() {
2016-10-06 07:16:26 -05:00
builder := QueryBuilder{}
2016-10-05 03:56:34 -05:00
qp1, _ := NewQueryPart("field", []string{"value"})
qp2, _ := NewQueryPart("mean", []string{})
groupBy1, _ := NewQueryPart("time", []string{"$interval"})
groupBy2, _ := NewQueryPart("tag", []string{"datacenter"})
groupBy3, _ := NewQueryPart("fill", []string{"null"})
tag1 := &Tag{Key: "hostname", Value: "server1", Operator: "="}
tag2 := &Tag{Key: "hostname", Value: "server2", Operator: "=", Condition: "OR"}
2016-10-05 03:56:34 -05:00
queryContext := &tsdb.QueryContext{
2016-10-07 04:33:17 -05:00
TimeRange: tsdb.NewTimeRange("5m", "now"),
}
2016-10-06 07:16:26 -05:00
Convey("can build simple query", func() {
query := &Query{
Selects: []*Select{{*qp1, *qp2}},
Measurement: "cpu",
Policy: "policy",
GroupBy: []*QueryPart{groupBy1, groupBy3},
Interval: "10s",
}
rawQuery, err := builder.Build(query, queryContext)
So(err, ShouldBeNil)
2016-10-10 00:12:21 -05:00
So(rawQuery, ShouldEqual, `SELECT mean("value") FROM "policy"."cpu" WHERE time > now() - 5m GROUP BY time(200ms) fill(null)`)
2016-10-05 03:56:34 -05:00
})
2016-10-06 07:16:26 -05:00
Convey("can build query with group bys", func() {
query := &Query{
Selects: []*Select{{*qp1, *qp2}},
Measurement: "cpu",
GroupBy: []*QueryPart{groupBy1, groupBy2, groupBy3},
Tags: []*Tag{tag1, tag2},
Interval: "5s",
}
rawQuery, err := builder.Build(query, queryContext)
So(err, ShouldBeNil)
2016-10-10 00:12:21 -05:00
So(rawQuery, ShouldEqual, `SELECT mean("value") FROM "cpu" WHERE "hostname" = 'server1' OR "hostname" = 'server2' AND time > now() - 5m GROUP BY time(200ms), "datacenter" fill(null)`)
})
Convey("can render time range", func() {
2016-10-07 04:33:17 -05:00
query := Query{}
2016-10-10 04:58:06 -05:00
builder := &QueryBuilder{}
Convey("render from: 2h to now-1h", func() {
2016-10-07 04:33:17 -05:00
query := Query{}
queryContext := &tsdb.QueryContext{TimeRange: tsdb.NewTimeRange("2h", "now-1h")}
2016-10-10 04:58:06 -05:00
So(builder.renderTimeFilter(&query, queryContext), ShouldEqual, "time > now() - 2h and time < now() - 1h")
})
Convey("render from: 10m", func() {
2016-10-07 04:33:17 -05:00
queryContext := &tsdb.QueryContext{TimeRange: tsdb.NewTimeRange("10m", "now")}
2016-10-10 04:58:06 -05:00
So(builder.renderTimeFilter(&query, queryContext), ShouldEqual, "time > now() - 10m")
})
2016-10-05 03:56:34 -05:00
})
})
}