test_notification.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 := NewRootNotifier()
  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(), []Notifier{notifiers})
  32. }
  33. func createTestEvalContext() *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.TODO(), testRule)
  42. ctx.ImagePublicUrl = "http://grafana.org/assets/img/blog/mixed_styles.png"
  43. ctx.IsTestRun = true
  44. ctx.Firing = true
  45. ctx.Error = nil
  46. ctx.EvalMatches = evalMatchesBasedOnState()
  47. return ctx
  48. }
  49. func evalMatchesBasedOnState() []*EvalMatch {
  50. matches := make([]*EvalMatch, 0)
  51. matches = append(matches, &EvalMatch{
  52. Metric: "High value",
  53. Value: null.FloatFrom(100),
  54. })
  55. matches = append(matches, &EvalMatch{
  56. Metric: "Higher Value",
  57. Value: null.FloatFrom(200),
  58. })
  59. return matches
  60. }