rule_test.go 2.0 KB

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