test_notification.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package alerting
  2. import (
  3. "context"
  4. "github.com/grafana/grafana/pkg/bus"
  5. "github.com/grafana/grafana/pkg/components/null"
  6. "github.com/grafana/grafana/pkg/components/simplejson"
  7. "github.com/grafana/grafana/pkg/log"
  8. m "github.com/grafana/grafana/pkg/models"
  9. )
  10. type NotificationTestCommand struct {
  11. State m.AlertStateType
  12. Name string
  13. Type string
  14. Settings *simplejson.Json
  15. }
  16. func init() {
  17. bus.AddHandler("alerting", handleNotificationTestCommand)
  18. }
  19. func handleNotificationTestCommand(cmd *NotificationTestCommand) error {
  20. notifier := newNotificationService()
  21. model := &m.AlertNotification{
  22. Name: cmd.Name,
  23. Type: cmd.Type,
  24. Settings: cmd.Settings,
  25. }
  26. notifiers, err := notifier.createNotifierFor(model)
  27. if err != nil {
  28. log.Error2("Failed to create notifier", "error", err.Error())
  29. return err
  30. }
  31. return notifier.sendNotifications(createTestEvalContext(cmd), []Notifier{notifiers})
  32. }
  33. func createTestEvalContext(cmd *NotificationTestCommand) *EvalContext {
  34. testRule := &Rule{
  35. DashboardId: 1,
  36. PanelId: 1,
  37. Name: "Test notification",
  38. Message: "Someone is testing the alert notification within grafana.",
  39. State: m.AlertStateAlerting,
  40. }
  41. ctx := NewEvalContext(context.Background(), testRule)
  42. if cmd.Settings.Get("uploadImage").MustBool(true) {
  43. ctx.ImagePublicUrl = "http://grafana.org/assets/img/blog/mixed_styles.png"
  44. }
  45. ctx.IsTestRun = true
  46. ctx.Firing = true
  47. ctx.Error = nil
  48. ctx.EvalMatches = evalMatchesBasedOnState()
  49. return ctx
  50. }
  51. func evalMatchesBasedOnState() []*EvalMatch {
  52. matches := make([]*EvalMatch, 0)
  53. matches = append(matches, &EvalMatch{
  54. Metric: "High value",
  55. Value: null.FloatFrom(100),
  56. })
  57. matches = append(matches, &EvalMatch{
  58. Metric: "Higher Value",
  59. Value: null.FloatFrom(200),
  60. })
  61. return matches
  62. }