reducer_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package conditions
  2. import (
  3. "testing"
  4. "gopkg.in/guregu/null.v3"
  5. "github.com/grafana/grafana/pkg/tsdb"
  6. . "github.com/smartystreets/goconvey/convey"
  7. )
  8. func TestSimpleReducer(t *testing.T) {
  9. Convey("Test simple reducer by calculating", t, func() {
  10. Convey("sum", func() {
  11. result := testReducer("sum", 1, 2, 3)
  12. So(result, ShouldEqual, float64(6))
  13. })
  14. Convey("min", func() {
  15. result := testReducer("min", 3, 2, 1)
  16. So(result, ShouldEqual, float64(1))
  17. })
  18. Convey("max", func() {
  19. result := testReducer("max", 1, 2, 3)
  20. So(result, ShouldEqual, float64(3))
  21. })
  22. Convey("count", func() {
  23. result := testReducer("count", 1, 2, 3000)
  24. So(result, ShouldEqual, float64(3))
  25. })
  26. Convey("last", func() {
  27. result := testReducer("last", 1, 2, 3000)
  28. So(result, ShouldEqual, float64(3000))
  29. })
  30. Convey("median odd amount of numbers", func() {
  31. result := testReducer("median", 1, 2, 3000)
  32. So(result, ShouldEqual, float64(2))
  33. })
  34. Convey("median even amount of numbers", func() {
  35. result := testReducer("median", 1, 2, 4, 3000)
  36. So(result, ShouldEqual, float64(3))
  37. })
  38. Convey("median with one values", func() {
  39. result := testReducer("median", 1)
  40. So(result, ShouldEqual, float64(1))
  41. })
  42. Convey("avg", func() {
  43. result := testReducer("avg", 1, 2, 3)
  44. So(result, ShouldEqual, float64(2))
  45. })
  46. Convey("avg of number values and null values should ignore nulls", func() {
  47. reducer := NewSimpleReducer("avg")
  48. series := &tsdb.TimeSeries{
  49. Name: "test time serie",
  50. }
  51. series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFrom(3), 1))
  52. series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFromPtr(nil), 2))
  53. series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFromPtr(nil), 3))
  54. series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFrom(3), 4))
  55. So(reducer.Reduce(series).Float64, ShouldEqual, float64(3))
  56. })
  57. })
  58. }
  59. func testReducer(typ string, datapoints ...float64) float64 {
  60. reducer := NewSimpleReducer(typ)
  61. series := &tsdb.TimeSeries{
  62. Name: "test time serie",
  63. }
  64. for idx := range datapoints {
  65. series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFrom(datapoints[idx]), 1234134))
  66. }
  67. return reducer.Reduce(series).Float64
  68. }