alert_rule_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package alerting
  2. import (
  3. "testing"
  4. "github.com/grafana/grafana/pkg/components/simplejson"
  5. "github.com/grafana/grafana/pkg/models"
  6. . "github.com/smartystreets/goconvey/convey"
  7. )
  8. func TestAlertRuleModel(t *testing.T) {
  9. Convey("Testing alert rule", t, func() {
  10. Convey("Can parse seconds", func() {
  11. seconds := getTimeDurationStringToSeconds("10s")
  12. So(seconds, ShouldEqual, 10)
  13. })
  14. Convey("Can parse minutes", func() {
  15. seconds := getTimeDurationStringToSeconds("10m")
  16. So(seconds, ShouldEqual, 600)
  17. })
  18. Convey("Can parse hours", func() {
  19. seconds := getTimeDurationStringToSeconds("1h")
  20. So(seconds, ShouldEqual, 3600)
  21. })
  22. Convey("defaults to seconds", func() {
  23. seconds := getTimeDurationStringToSeconds("1o")
  24. So(seconds, ShouldEqual, 1)
  25. })
  26. Convey("can construct alert rule model", func() {
  27. json := `
  28. {
  29. "name": "name2",
  30. "description": "desc2",
  31. "handler": 0,
  32. "enabled": true,
  33. "frequency": "60s",
  34. "conditions": [
  35. {
  36. "type": "query",
  37. "query": {
  38. "params": ["A", "5m", "now"],
  39. "datasourceId": 1,
  40. "model": {"target": "aliasByNode(statsd.fakesite.counters.session_start.mobile.count, 4)"}
  41. },
  42. "reducer": {"type": "avg", "params": []},
  43. "evaluator": {"type": ">", "params": [100]}
  44. }
  45. ]
  46. }
  47. `
  48. alertJSON, jsonErr := simplejson.NewJson([]byte(json))
  49. So(jsonErr, ShouldBeNil)
  50. alert := &models.Alert{
  51. Id: 1,
  52. OrgId: 1,
  53. DashboardId: 1,
  54. PanelId: 1,
  55. Settings: alertJSON,
  56. }
  57. alertRule, err := NewAlertRuleFromDBModel(alert)
  58. So(err, ShouldBeNil)
  59. So(alertRule.Conditions, ShouldHaveLength, 1)
  60. Convey("Can read query condition from json model", func() {
  61. queryCondition, ok := alertRule.Conditions[0].(*QueryCondition)
  62. So(ok, ShouldBeTrue)
  63. So(queryCondition.Query.From, ShouldEqual, "5m")
  64. So(queryCondition.Query.To, ShouldEqual, "now")
  65. So(queryCondition.Query.DatasourceId, ShouldEqual, 1)
  66. Convey("Can read query reducer", func() {
  67. reducer, ok := queryCondition.Reducer.(*SimpleReducer)
  68. So(ok, ShouldBeTrue)
  69. So(reducer.Type, ShouldEqual, "avg")
  70. })
  71. Convey("Can read evaluator", func() {
  72. evaluator, ok := queryCondition.Evaluator.(*DefaultAlertEvaluator)
  73. So(ok, ShouldBeTrue)
  74. So(evaluator.Type, ShouldEqual, ">")
  75. })
  76. })
  77. })
  78. })
  79. }