alert_rule_test.go 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. "notifications": [
  47. {"id": 1134},
  48. {"id": 22}
  49. ]
  50. }
  51. `
  52. alertJSON, jsonErr := simplejson.NewJson([]byte(json))
  53. So(jsonErr, ShouldBeNil)
  54. alert := &models.Alert{
  55. Id: 1,
  56. OrgId: 1,
  57. DashboardId: 1,
  58. PanelId: 1,
  59. Settings: alertJSON,
  60. }
  61. alertRule, err := NewAlertRuleFromDBModel(alert)
  62. So(err, ShouldBeNil)
  63. So(alertRule.Conditions, ShouldHaveLength, 1)
  64. Convey("Can read query condition from json model", func() {
  65. queryCondition, ok := alertRule.Conditions[0].(*QueryCondition)
  66. So(ok, ShouldBeTrue)
  67. So(queryCondition.Query.From, ShouldEqual, "5m")
  68. So(queryCondition.Query.To, ShouldEqual, "now")
  69. So(queryCondition.Query.DatasourceId, ShouldEqual, 1)
  70. Convey("Can read query reducer", func() {
  71. reducer, ok := queryCondition.Reducer.(*SimpleReducer)
  72. So(ok, ShouldBeTrue)
  73. So(reducer.Type, ShouldEqual, "avg")
  74. })
  75. Convey("Can read evaluator", func() {
  76. evaluator, ok := queryCondition.Evaluator.(*DefaultAlertEvaluator)
  77. So(ok, ShouldBeTrue)
  78. So(evaluator.Type, ShouldEqual, ">")
  79. })
  80. })
  81. Convey("Can read notifications", func() {
  82. So(len(alertRule.Notifications), ShouldEqual, 2)
  83. })
  84. })
  85. })
  86. }