rule_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. Convey("Can read noDataMode", func() {
  75. So(len(alertRule.NoDataMode), ShouldEqual, m.AlertStateCritical)
  76. })
  77. */
  78. })
  79. })
  80. }