conditions_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package alerting
  2. import (
  3. "testing"
  4. "github.com/grafana/grafana/pkg/bus"
  5. "github.com/grafana/grafana/pkg/components/simplejson"
  6. m "github.com/grafana/grafana/pkg/models"
  7. "github.com/grafana/grafana/pkg/tsdb"
  8. . "github.com/smartystreets/goconvey/convey"
  9. )
  10. func TestQueryCondition(t *testing.T) {
  11. Convey("when evaluating query condition", t, func() {
  12. queryConditionScenario("Given avg() and > 100", func(ctx *queryConditionTestContext) {
  13. ctx.reducer = `{"type": "avg"}`
  14. ctx.evaluator = `{"type": ">", "params": [100]}`
  15. Convey("should fire when avg is above 100", func() {
  16. ctx.series = tsdb.TimeSeriesSlice{tsdb.NewTimeSeries("test1", [][2]float64{{120, 0}})}
  17. ctx.exec()
  18. So(ctx.result.Error, ShouldBeNil)
  19. So(ctx.result.Firing, ShouldBeTrue)
  20. })
  21. Convey("Should not fire when avg is below 100", func() {
  22. ctx.series = tsdb.TimeSeriesSlice{tsdb.NewTimeSeries("test1", [][2]float64{{90, 0}})}
  23. ctx.exec()
  24. So(ctx.result.Error, ShouldBeNil)
  25. So(ctx.result.Firing, ShouldBeFalse)
  26. })
  27. })
  28. })
  29. }
  30. type queryConditionTestContext struct {
  31. reducer string
  32. evaluator string
  33. series tsdb.TimeSeriesSlice
  34. result *AlertResultContext
  35. }
  36. type queryConditionScenarioFunc func(c *queryConditionTestContext)
  37. func (ctx *queryConditionTestContext) exec() {
  38. jsonModel, err := simplejson.NewJson([]byte(`{
  39. "type": "query",
  40. "query": {
  41. "params": ["A", "5m", "now"],
  42. "datasourceId": 1,
  43. "model": {"target": "aliasByNode(statsd.fakesite.counters.session_start.mobile.count, 4)"}
  44. },
  45. "reducer":` + ctx.reducer + `,
  46. "evaluator":` + ctx.evaluator + `
  47. }`))
  48. So(err, ShouldBeNil)
  49. condition, err := NewQueryCondition(jsonModel, 0)
  50. So(err, ShouldBeNil)
  51. condition.HandleRequest = func(req *tsdb.Request) (*tsdb.Response, error) {
  52. return &tsdb.Response{
  53. Results: map[string]*tsdb.QueryResult{
  54. "A": {Series: ctx.series},
  55. },
  56. }, nil
  57. }
  58. condition.Eval(ctx.result)
  59. }
  60. func queryConditionScenario(desc string, fn queryConditionScenarioFunc) {
  61. Convey(desc, func() {
  62. bus.AddHandler("test", func(query *m.GetDataSourceByIdQuery) error {
  63. query.Result = &m.DataSource{Id: 1, Type: "graphite"}
  64. return nil
  65. })
  66. ctx := &queryConditionTestContext{}
  67. ctx.result = &AlertResultContext{
  68. Rule: &AlertRule{},
  69. }
  70. fn(ctx)
  71. })
  72. }