test_notification.go 1.8 KB

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