rule_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package alerting
  2. import (
  3. "testing"
  4. "github.com/grafana/grafana/pkg/components/simplejson"
  5. m "github.com/grafana/grafana/pkg/models"
  6. . "github.com/smartystreets/goconvey/convey"
  7. )
  8. type FakeCondition struct{}
  9. func (f *FakeCondition) Eval(context *EvalContext) {}
  10. func TestAlertRuleModel(t *testing.T) {
  11. Convey("Testing alert rule", t, func() {
  12. RegisterCondition("test", func(model *simplejson.Json, index int) (Condition, error) {
  13. return &FakeCondition{}, nil
  14. })
  15. Convey("Can parse seconds", func() {
  16. seconds, _ := getTimeDurationStringToSeconds("10s")
  17. So(seconds, ShouldEqual, 10)
  18. })
  19. Convey("Can parse minutes", func() {
  20. seconds, _ := getTimeDurationStringToSeconds("10m")
  21. So(seconds, ShouldEqual, 600)
  22. })
  23. Convey("Can parse hours", func() {
  24. seconds, _ := getTimeDurationStringToSeconds("1h")
  25. So(seconds, ShouldEqual, 3600)
  26. })
  27. Convey("defaults to seconds", func() {
  28. seconds, _ := getTimeDurationStringToSeconds("1o")
  29. So(seconds, ShouldEqual, 1)
  30. })
  31. Convey("should return err for empty string", func() {
  32. _, err := getTimeDurationStringToSeconds("")
  33. So(err, ShouldNotBeNil)
  34. })
  35. Convey("can construct alert rule model", func() {
  36. json := `
  37. {
  38. "name": "name2",
  39. "description": "desc2",
  40. "handler": 0,
  41. "noDataMode": "critical",
  42. "enabled": true,
  43. "frequency": "60s",
  44. "conditions": [
  45. {
  46. "type": "test",
  47. "prop": 123
  48. }
  49. ],
  50. "notifications": [
  51. {"id": 1134},
  52. {"id": 22}
  53. ]
  54. }
  55. `
  56. alertJSON, jsonErr := simplejson.NewJson([]byte(json))
  57. So(jsonErr, ShouldBeNil)
  58. alert := &m.Alert{
  59. Id: 1,
  60. OrgId: 1,
  61. DashboardId: 1,
  62. PanelId: 1,
  63. Settings: alertJSON,
  64. }
  65. alertRule, err := NewRuleFromDBAlert(alert)
  66. So(err, ShouldBeNil)
  67. So(len(alertRule.Conditions), ShouldEqual, 1)
  68. Convey("Can read notifications", func() {
  69. So(len(alertRule.Notifications), ShouldEqual, 2)
  70. })
  71. /*
  72. Convey("Can read noDataMode", func() {
  73. So(len(alertRule.NoDataMode), ShouldEqual, m.AlertStateCritical)
  74. })
  75. */
  76. })
  77. })
  78. }