rule_test.go 2.2 KB

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