Chore: Refactor alerting notifier tests to remove goconvey (#40758)

This commit is contained in:
Serge Zaitsev
2021-10-21 17:04:43 +02:00
committed by GitHub
parent 8d06bddeda
commit 76e30c5e97
17 changed files with 1293 additions and 1312 deletions
@@ -10,8 +10,9 @@ import (
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations" "github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestReplaceIllegalCharswithUnderscore(t *testing.T) { func TestReplaceIllegalCharswithUnderscore(t *testing.T) {
@@ -80,57 +81,55 @@ func TestWhenAlertManagerShouldNotify(t *testing.T) {
//nolint:goconst //nolint:goconst
func TestAlertmanagerNotifier(t *testing.T) { func TestAlertmanagerNotifier(t *testing.T) {
Convey("Alertmanager notifier tests", t, func() { t.Run("Parsing alert notification from settings", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "alertmanager", Name: "alertmanager",
Type: "alertmanager", Type: "alertmanager",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := NewAlertmanagerNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := NewAlertmanagerNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("from settings", func() { t.Run("from settings", func(t *testing.T) {
json := `{ "url": "http://127.0.0.1:9093/", "basicAuthUser": "user", "basicAuthPassword": "password" }` json := `{ "url": "http://127.0.0.1:9093/", "basicAuthUser": "user", "basicAuthPassword": "password" }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "alertmanager", Name: "alertmanager",
Type: "alertmanager", Type: "alertmanager",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewAlertmanagerNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewAlertmanagerNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
alertmanagerNotifier := not.(*AlertmanagerNotifier) alertmanagerNotifier := not.(*AlertmanagerNotifier)
So(err, ShouldBeNil) require.NoError(t, err)
So(alertmanagerNotifier.BasicAuthUser, ShouldEqual, "user") require.Equal(t, alertmanagerNotifier.BasicAuthUser, "user")
So(alertmanagerNotifier.BasicAuthPassword, ShouldEqual, "password") require.Equal(t, alertmanagerNotifier.BasicAuthPassword, "password")
So(alertmanagerNotifier.URL, ShouldResemble, []string{"http://127.0.0.1:9093/"}) require.Equal(t, alertmanagerNotifier.URL, []string{"http://127.0.0.1:9093/"})
}) })
Convey("from settings with multiple alertmanager", func() { t.Run("from settings with multiple alertmanager", func(t *testing.T) {
json := `{ "url": "http://alertmanager1:9093,http://alertmanager2:9093" }` json := `{ "url": "http://alertmanager1:9093,http://alertmanager2:9093" }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "alertmanager", Name: "alertmanager",
Type: "alertmanager", Type: "alertmanager",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewAlertmanagerNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewAlertmanagerNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
alertmanagerNotifier := not.(*AlertmanagerNotifier) alertmanagerNotifier := not.(*AlertmanagerNotifier)
So(err, ShouldBeNil) require.NoError(t, err)
So(alertmanagerNotifier.URL, ShouldResemble, []string{"http://alertmanager1:9093", "http://alertmanager2:9093"}) require.Equal(t, alertmanagerNotifier.URL, []string{"http://alertmanager1:9093", "http://alertmanager2:9093"})
})
}) })
}) })
} }
+26 -27
View File
@@ -9,8 +9,9 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/validations" "github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestShouldSendAlertNotification(t *testing.T) { func TestShouldSendAlertNotification(t *testing.T) {
@@ -184,38 +185,36 @@ func TestShouldSendAlertNotification(t *testing.T) {
} }
func TestBaseNotifier(t *testing.T) { func TestBaseNotifier(t *testing.T) {
Convey("default constructor for notifiers", t, func() { bJSON := simplejson.New()
bJSON := simplejson.New()
model := &models.AlertNotification{ model := &models.AlertNotification{
Uid: "1", Uid: "1",
Name: "name", Name: "name",
Type: "email", Type: "email",
Settings: bJSON, Settings: bJSON,
} }
Convey("can parse false value", func() { t.Run("can parse false value", func(t *testing.T) {
bJSON.Set("uploadImage", false) bJSON.Set("uploadImage", false)
base := NewNotifierBase(model) base := NewNotifierBase(model)
So(base.UploadImage, ShouldBeFalse) require.False(t, base.UploadImage)
}) })
Convey("can parse true value", func() { t.Run("can parse true value", func(t *testing.T) {
bJSON.Set("uploadImage", true) bJSON.Set("uploadImage", true)
base := NewNotifierBase(model) base := NewNotifierBase(model)
So(base.UploadImage, ShouldBeTrue) require.True(t, base.UploadImage)
}) })
Convey("default value should be true for backwards compatibility", func() { t.Run("default value should be true for backwards compatibility", func(t *testing.T) {
base := NewNotifierBase(model) base := NewNotifierBase(model)
So(base.UploadImage, ShouldBeTrue) require.True(t, base.UploadImage)
}) })
Convey("default value should be false for backwards compatibility", func() { t.Run("default value should be false for backwards compatibility", func(t *testing.T) {
base := NewNotifierBase(model) base := NewNotifierBase(model)
So(base.DisableResolveMessage, ShouldBeFalse) require.False(t, base.DisableResolveMessage)
})
}) })
} }
@@ -9,51 +9,50 @@ import (
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations" "github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func TestDingDingNotifier(t *testing.T) { func TestDingDingNotifier(t *testing.T) {
Convey("Dingding notifier tests", t, func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "dingding_testing", Name: "dingding_testing",
Type: "dingding", Type: "dingding",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := newDingDingNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := newDingDingNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("settings should trigger incident", func() { t.Run("settings should trigger incident", func(t *testing.T) {
json := `{ "url": "https://www.google.com" }` json := `{ "url": "https://www.google.com" }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "dingding_testing", Name: "dingding_testing",
Type: "dingding", Type: "dingding",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := newDingDingNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := newDingDingNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
notifier := not.(*DingDingNotifier) notifier := not.(*DingDingNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(notifier.Name, ShouldEqual, "dingding_testing") require.Equal(t, "dingding_testing", notifier.Name)
So(notifier.Type, ShouldEqual, "dingding") require.Equal(t, "dingding", notifier.Type)
So(notifier.URL, ShouldEqual, "https://www.google.com") require.Equal(t, "https://www.google.com", notifier.URL)
Convey("genBody should not panic", func() { t.Run("genBody should not panic", func(t *testing.T) {
evalContext := alerting.NewEvalContext(context.Background(), evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{ &alerting.Rule{
State: models.AlertStateAlerting, State: models.AlertStateAlerting,
Message: `{host="localhost"}`, Message: `{host="localhost"}`,
}, &validations.OSSPluginRequestValidator{}) }, &validations.OSSPluginRequestValidator{})
_, err = notifier.genBody(evalContext, "") _, err = notifier.genBody(evalContext, "")
So(err, ShouldBeNil) require.Nil(t, err)
})
}) })
}) })
} }
+30 -31
View File
@@ -6,51 +6,50 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func TestDiscordNotifier(t *testing.T) { func TestDiscordNotifier(t *testing.T) {
Convey("Discord notifier tests", t, func() { t.Run("Parsing alert notification from settings", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "discord_testing", Name: "discord_testing",
Type: "discord", Type: "discord",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := newDiscordNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := newDiscordNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("settings should trigger incident", func() { t.Run("settings should trigger incident", func(t *testing.T) {
json := ` json := `
{ {
"avatar_url": "https://grafana.com/img/fav32.png", "avatar_url": "https://grafana.com/img/fav32.png",
"content": "@everyone Please check this notification", "content": "@everyone Please check this notification",
"url": "https://web.hook/" "url": "https://web.hook/"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "discord_testing", Name: "discord_testing",
Type: "discord", Type: "discord",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := newDiscordNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := newDiscordNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
discordNotifier := not.(*DiscordNotifier) discordNotifier := not.(*DiscordNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(discordNotifier.Name, ShouldEqual, "discord_testing") require.Equal(t, "discord_testing", discordNotifier.Name)
So(discordNotifier.Type, ShouldEqual, "discord") require.Equal(t, "discord", discordNotifier.Type)
So(discordNotifier.AvatarURL, ShouldEqual, "https://grafana.com/img/fav32.png") require.Equal(t, "https://grafana.com/img/fav32.png", discordNotifier.AvatarURL)
So(discordNotifier.Content, ShouldEqual, "@everyone Please check this notification") require.Equal(t, "@everyone Please check this notification", discordNotifier.Content)
So(discordNotifier.WebhookURL, ShouldEqual, "https://web.hook/") require.Equal(t, "https://web.hook/", discordNotifier.WebhookURL)
})
}) })
}) })
} }
+46 -47
View File
@@ -6,74 +6,73 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func TestEmailNotifier(t *testing.T) { func TestEmailNotifier(t *testing.T) {
Convey("Email notifier tests", t, func() { t.Run("Parsing alert notification from settings", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "ops", Name: "ops",
Type: "email", Type: "email",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := NewEmailNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := NewEmailNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("from settings", func() { t.Run("from settings", func(t *testing.T) {
json := ` json := `
{ {
"addresses": "ops@grafana.org" "addresses": "ops@grafana.org"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "ops", Name: "ops",
Type: "email", Type: "email",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewEmailNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewEmailNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
emailNotifier := not.(*EmailNotifier) emailNotifier := not.(*EmailNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(emailNotifier.Name, ShouldEqual, "ops") require.Equal(t, "ops", emailNotifier.Name)
So(emailNotifier.Type, ShouldEqual, "email") require.Equal(t, "email", emailNotifier.Type)
So(emailNotifier.Addresses[0], ShouldEqual, "ops@grafana.org") require.Equal(t, "ops@grafana.org", emailNotifier.Addresses[0])
}) })
Convey("from settings with two emails", func() { t.Run("from settings with two emails", func(t *testing.T) {
json := ` json := `
{ {
"addresses": "ops@grafana.org;dev@grafana.org" "addresses": "ops@grafana.org;dev@grafana.org"
}` }`
settingsJSON, err := simplejson.NewJson([]byte(json)) settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil) require.Nil(t, err)
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "ops", Name: "ops",
Type: "email", Type: "email",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewEmailNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewEmailNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
emailNotifier := not.(*EmailNotifier) emailNotifier := not.(*EmailNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(emailNotifier.Name, ShouldEqual, "ops") require.Equal(t, "ops", emailNotifier.Name)
So(emailNotifier.Type, ShouldEqual, "email") require.Equal(t, "email", emailNotifier.Type)
So(len(emailNotifier.Addresses), ShouldEqual, 2) require.Equal(t, 2, len(emailNotifier.Addresses))
So(emailNotifier.Addresses[0], ShouldEqual, "ops@grafana.org") require.Equal(t, "ops@grafana.org", emailNotifier.Addresses[0])
So(emailNotifier.Addresses[1], ShouldEqual, "dev@grafana.org") require.Equal(t, "dev@grafana.org", emailNotifier.Addresses[1])
})
}) })
}) })
} }
@@ -6,47 +6,46 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func TestGoogleChatNotifier(t *testing.T) { func TestGoogleChatNotifier(t *testing.T) {
Convey("Google Hangouts Chat notifier tests", t, func() { t.Run("Parsing alert notification from settings", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "ops", Name: "ops",
Type: "googlechat", Type: "googlechat",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := newGoogleChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := newGoogleChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("from settings", func() { t.Run("from settings", func(t *testing.T) {
json := ` json := `
{ {
"url": "http://google.com" "url": "http://google.com"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "ops", Name: "ops",
Type: "googlechat", Type: "googlechat",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := newGoogleChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := newGoogleChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
webhookNotifier := not.(*GoogleChatNotifier) webhookNotifier := not.(*GoogleChatNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(webhookNotifier.Name, ShouldEqual, "ops") require.Equal(t, "ops", webhookNotifier.Name)
So(webhookNotifier.Type, ShouldEqual, "googlechat") require.Equal(t, "googlechat", webhookNotifier.Type)
So(webhookNotifier.URL, ShouldEqual, "http://google.com") require.Equal(t, "http://google.com", webhookNotifier.URL)
})
}) })
}) })
} }
+47 -48
View File
@@ -6,75 +6,74 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
//nolint:goconst //nolint:goconst
func TestHipChatNotifier(t *testing.T) { func TestHipChatNotifier(t *testing.T) {
Convey("HipChat notifier tests", t, func() { t.Run("Parsing alert notification from settings", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "ops", Name: "ops",
Type: "hipchat", Type: "hipchat",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := NewHipChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := NewHipChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("from settings", func() { t.Run("from settings", func(t *testing.T) {
json := ` json := `
{ {
"url": "http://google.com" "url": "http://google.com"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "ops", Name: "ops",
Type: "hipchat", Type: "hipchat",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewHipChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewHipChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
hipchatNotifier := not.(*HipChatNotifier) hipchatNotifier := not.(*HipChatNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(hipchatNotifier.Name, ShouldEqual, "ops") require.Equal(t, "ops", hipchatNotifier.Name)
So(hipchatNotifier.Type, ShouldEqual, "hipchat") require.Equal(t, "hipchat", hipchatNotifier.Type)
So(hipchatNotifier.URL, ShouldEqual, "http://google.com") require.Equal(t, "http://google.com", hipchatNotifier.URL)
So(hipchatNotifier.APIKey, ShouldEqual, "") require.Equal(t, "", hipchatNotifier.APIKey)
So(hipchatNotifier.RoomID, ShouldEqual, "") require.Equal(t, "", hipchatNotifier.RoomID)
}) })
Convey("from settings with Recipient and Mention", func() { t.Run("from settings with Recipient and Mention", func(t *testing.T) {
json := ` json := `
{ {
"url": "http://www.hipchat.com", "url": "http://www.hipchat.com",
"apikey": "1234", "apikey": "1234",
"roomid": "1234" "roomid": "1234"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "ops", Name: "ops",
Type: "hipchat", Type: "hipchat",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewHipChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewHipChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
hipchatNotifier := not.(*HipChatNotifier) hipchatNotifier := not.(*HipChatNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(hipchatNotifier.Name, ShouldEqual, "ops") require.Equal(t, "ops", hipchatNotifier.Name)
So(hipchatNotifier.Type, ShouldEqual, "hipchat") require.Equal(t, "hipchat", hipchatNotifier.Type)
So(hipchatNotifier.URL, ShouldEqual, "http://www.hipchat.com") require.Equal(t, "http://www.hipchat.com", hipchatNotifier.URL)
So(hipchatNotifier.APIKey, ShouldEqual, "1234") require.Equal(t, "1234", hipchatNotifier.APIKey)
So(hipchatNotifier.RoomID, ShouldEqual, "1234") require.Equal(t, "1234", hipchatNotifier.RoomID)
})
}) })
}) })
} }
+29 -30
View File
@@ -6,49 +6,48 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func TestKafkaNotifier(t *testing.T) { func TestKafkaNotifier(t *testing.T) {
Convey("Kafka notifier tests", t, func() { t.Run("Parsing alert notification from settings", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "kafka_testing", Name: "kafka_testing",
Type: "kafka", Type: "kafka",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := NewKafkaNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := NewKafkaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("settings should send an event to kafka", func() { t.Run("settings should send an event to kafka", func(t *testing.T) {
json := ` json := `
{ {
"kafkaRestProxy": "http://localhost:8082", "kafkaRestProxy": "http://localhost:8082",
"kafkaTopic": "topic1" "kafkaTopic": "topic1"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "kafka_testing", Name: "kafka_testing",
Type: "kafka", Type: "kafka",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewKafkaNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewKafkaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
kafkaNotifier := not.(*KafkaNotifier) kafkaNotifier := not.(*KafkaNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(kafkaNotifier.Name, ShouldEqual, "kafka_testing") require.Equal(t, "kafka_testing", kafkaNotifier.Name)
So(kafkaNotifier.Type, ShouldEqual, "kafka") require.Equal(t, "kafka", kafkaNotifier.Type)
So(kafkaNotifier.Endpoint, ShouldEqual, "http://localhost:8082") require.Equal(t, "http://localhost:8082", kafkaNotifier.Endpoint)
So(kafkaNotifier.Topic, ShouldEqual, "topic1") require.Equal(t, "topic1", kafkaNotifier.Topic)
})
}) })
}) })
} }
+27 -28
View File
@@ -6,43 +6,42 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func TestLineNotifier(t *testing.T) { func TestLineNotifier(t *testing.T) {
Convey("Line notifier tests", t, func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "line_testing", Name: "line_testing",
Type: "line", Type: "line",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := NewLINENotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := NewLINENotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("settings should trigger incident", func() { t.Run("settings should trigger incident", func(t *testing.T) {
json := ` json := `
{ {
"token": "abcdefgh0123456789" "token": "abcdefgh0123456789"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "line_testing", Name: "line_testing",
Type: "line", Type: "line",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewLINENotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewLINENotifier(model, ossencryption.ProvideService().GetDecryptedValue)
lineNotifier := not.(*LineNotifier) lineNotifier := not.(*LineNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(lineNotifier.Name, ShouldEqual, "line_testing") require.Equal(t, "line_testing", lineNotifier.Name)
So(lineNotifier.Type, ShouldEqual, "line") require.Equal(t, "line", lineNotifier.Type)
So(lineNotifier.Token, ShouldEqual, "abcdefgh0123456789") require.Equal(t, "abcdefgh0123456789", lineNotifier.Token)
})
}) })
} }
+173 -172
View File
@@ -2,6 +2,8 @@ package notifiers
import ( import (
"context" "context"
"reflect"
"strings"
"testing" "testing"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
@@ -10,217 +12,216 @@ import (
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations" "github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func TestOpsGenieNotifier(t *testing.T) { func TestOpsGenieNotifier(t *testing.T) {
Convey("OpsGenie notifier tests", t, func() { t.Run("Parsing alert notification from settings", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "opsgenie_testing", Name: "opsgenie_testing",
Type: "opsgenie", Type: "opsgenie",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("settings should trigger incident", func() { t.Run("settings should trigger incident", func(t *testing.T) {
json := ` json := `
{ {
"apiKey": "abcdefgh0123456789" "apiKey": "abcdefgh0123456789"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "opsgenie_testing", Name: "opsgenie_testing",
Type: "opsgenie", Type: "opsgenie",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
opsgenieNotifier := not.(*OpsGenieNotifier) opsgenieNotifier := not.(*OpsGenieNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(opsgenieNotifier.Name, ShouldEqual, "opsgenie_testing") require.Equal(t, "opsgenie_testing", opsgenieNotifier.Name)
So(opsgenieNotifier.Type, ShouldEqual, "opsgenie") require.Equal(t, "opsgenie", opsgenieNotifier.Type)
So(opsgenieNotifier.APIKey, ShouldEqual, "abcdefgh0123456789") require.Equal(t, "abcdefgh0123456789", opsgenieNotifier.APIKey)
})
}) })
})
Convey("Handling notification tags", func() { t.Run("Handling notification tags", func(t *testing.T) {
Convey("invalid sendTagsAs value should return error", func() { t.Run("invalid sendTagsAs value should return error", func(t *testing.T) {
json := `{ json := `{
"apiKey": "abcdefgh0123456789", "apiKey": "abcdefgh0123456789",
"sendTagsAs": "not_a_valid_value" "sendTagsAs": "not_a_valid_value"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "opsgenie_testing", Name: "opsgenie_testing",
Type: "opsgenie", Type: "opsgenie",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
So(err, ShouldHaveSameTypeAs, alerting.ValidationError{}) require.Equal(t, reflect.TypeOf(err), reflect.TypeOf(alerting.ValidationError{}))
So(err.Error(), ShouldEndWith, "Invalid value for sendTagsAs: \"not_a_valid_value\"") require.True(t, strings.HasSuffix(err.Error(), "Invalid value for sendTagsAs: \"not_a_valid_value\""))
}) })
Convey("alert payload should include tag pairs only as an array in the tags key when sendAsTags is not set", func() { t.Run("alert payload should include tag pairs only as an array in the tags key when sendAsTags is not set", func(t *testing.T) {
json := `{ json := `{
"apiKey": "abcdefgh0123456789" "apiKey": "abcdefgh0123456789"
}` }`
tagPairs := []*models.Tag{ tagPairs := []*models.Tag{
{Key: "keyOnly"}, {Key: "keyOnly"},
{Key: "aKey", Value: "aValue"}, {Key: "aKey", Value: "aValue"},
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "opsgenie_testing",
Type: "opsgenie",
Settings: settingsJSON,
}
notifier, notifierErr := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue) // unhandled error
opsgenieNotifier := notifier.(*OpsGenieNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: tagPairs,
}, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true
tags := make([]string, 0)
details := make(map[string]interface{})
bus.AddHandlerCtx("alerting", func(ctx context.Context, cmd *models.SendWebhookSync) error {
bodyJSON, err := simplejson.NewJson([]byte(cmd.Body))
if err == nil {
tags = bodyJSON.Get("tags").MustStringArray([]string{})
details = bodyJSON.Get("details").MustMap(map[string]interface{}{})
} }
return err
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "opsgenie_testing",
Type: "opsgenie",
Settings: settingsJSON,
}
notifier, notifierErr := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue) // unhandled error
opsgenieNotifier := notifier.(*OpsGenieNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: tagPairs,
}, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true
tags := make([]string, 0)
details := make(map[string]interface{})
bus.AddHandlerCtx("alerting", func(ctx context.Context, cmd *models.SendWebhookSync) error {
bodyJSON, err := simplejson.NewJson([]byte(cmd.Body))
if err == nil {
tags = bodyJSON.Get("tags").MustStringArray([]string{})
details = bodyJSON.Get("details").MustMap(map[string]interface{}{})
}
return err
})
alertErr := opsgenieNotifier.createAlert(evalContext)
So(notifierErr, ShouldBeNil)
So(alertErr, ShouldBeNil)
So(tags, ShouldResemble, []string{"keyOnly", "aKey:aValue"})
So(details, ShouldResemble, map[string]interface{}{"url": ""})
}) })
Convey("alert payload should include tag pairs only as a map in the details key when sendAsTags=details", func() { alertErr := opsgenieNotifier.createAlert(evalContext)
json := `{
require.Nil(t, notifierErr)
require.Nil(t, alertErr)
require.Equal(t, tags, []string{"keyOnly", "aKey:aValue"})
require.Equal(t, details, map[string]interface{}{"url": ""})
})
t.Run("alert payload should include tag pairs only as a map in the details key when sendAsTags=details", func(t *testing.T) {
json := `{
"apiKey": "abcdefgh0123456789", "apiKey": "abcdefgh0123456789",
"sendTagsAs": "details" "sendTagsAs": "details"
}` }`
tagPairs := []*models.Tag{ tagPairs := []*models.Tag{
{Key: "keyOnly"}, {Key: "keyOnly"},
{Key: "aKey", Value: "aValue"}, {Key: "aKey", Value: "aValue"},
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "opsgenie_testing",
Type: "opsgenie",
Settings: settingsJSON,
}
notifier, notifierErr := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue) // unhandled error
opsgenieNotifier := notifier.(*OpsGenieNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: tagPairs,
}, nil)
evalContext.IsTestRun = true
tags := make([]string, 0)
details := make(map[string]interface{})
bus.AddHandlerCtx("alerting", func(ctx context.Context, cmd *models.SendWebhookSync) error {
bodyJSON, err := simplejson.NewJson([]byte(cmd.Body))
if err == nil {
tags = bodyJSON.Get("tags").MustStringArray([]string{})
details = bodyJSON.Get("details").MustMap(map[string]interface{}{})
} }
return err
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "opsgenie_testing",
Type: "opsgenie",
Settings: settingsJSON,
}
notifier, notifierErr := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue) // unhandled error
opsgenieNotifier := notifier.(*OpsGenieNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: tagPairs,
}, nil)
evalContext.IsTestRun = true
tags := make([]string, 0)
details := make(map[string]interface{})
bus.AddHandlerCtx("alerting", func(ctx context.Context, cmd *models.SendWebhookSync) error {
bodyJSON, err := simplejson.NewJson([]byte(cmd.Body))
if err == nil {
tags = bodyJSON.Get("tags").MustStringArray([]string{})
details = bodyJSON.Get("details").MustMap(map[string]interface{}{})
}
return err
})
alertErr := opsgenieNotifier.createAlert(evalContext)
So(notifierErr, ShouldBeNil)
So(alertErr, ShouldBeNil)
So(tags, ShouldResemble, []string{})
So(details, ShouldResemble, map[string]interface{}{"keyOnly": "", "aKey": "aValue", "url": ""})
}) })
Convey("alert payload should include tag pairs as both a map in the details key and an array in the tags key when sendAsTags=both", func() { alertErr := opsgenieNotifier.createAlert(evalContext)
json := `{
require.Nil(t, notifierErr)
require.Nil(t, alertErr)
require.Equal(t, tags, []string{})
require.Equal(t, details, map[string]interface{}{"keyOnly": "", "aKey": "aValue", "url": ""})
})
t.Run("alert payload should include tag pairs as both a map in the details key and an array in the tags key when sendAsTags=both", func(t *testing.T) {
json := `{
"apiKey": "abcdefgh0123456789", "apiKey": "abcdefgh0123456789",
"sendTagsAs": "both" "sendTagsAs": "both"
}` }`
tagPairs := []*models.Tag{ tagPairs := []*models.Tag{
{Key: "keyOnly"}, {Key: "keyOnly"},
{Key: "aKey", Value: "aValue"}, {Key: "aKey", Value: "aValue"},
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "opsgenie_testing",
Type: "opsgenie",
Settings: settingsJSON,
}
notifier, notifierErr := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue) // unhandled error
opsgenieNotifier := notifier.(*OpsGenieNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: tagPairs,
}, nil)
evalContext.IsTestRun = true
tags := make([]string, 0)
details := make(map[string]interface{})
bus.AddHandlerCtx("alerting", func(ctx context.Context, cmd *models.SendWebhookSync) error {
bodyJSON, err := simplejson.NewJson([]byte(cmd.Body))
if err == nil {
tags = bodyJSON.Get("tags").MustStringArray([]string{})
details = bodyJSON.Get("details").MustMap(map[string]interface{}{})
} }
return err
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "opsgenie_testing",
Type: "opsgenie",
Settings: settingsJSON,
}
notifier, notifierErr := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue) // unhandled error
opsgenieNotifier := notifier.(*OpsGenieNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: tagPairs,
}, nil)
evalContext.IsTestRun = true
tags := make([]string, 0)
details := make(map[string]interface{})
bus.AddHandlerCtx("alerting", func(ctx context.Context, cmd *models.SendWebhookSync) error {
bodyJSON, err := simplejson.NewJson([]byte(cmd.Body))
if err == nil {
tags = bodyJSON.Get("tags").MustStringArray([]string{})
details = bodyJSON.Get("details").MustMap(map[string]interface{}{})
}
return err
})
alertErr := opsgenieNotifier.createAlert(evalContext)
So(notifierErr, ShouldBeNil)
So(alertErr, ShouldBeNil)
So(tags, ShouldResemble, []string{"keyOnly", "aKey:aValue"})
So(details, ShouldResemble, map[string]interface{}{"keyOnly": "", "aKey": "aValue", "url": ""})
}) })
alertErr := opsgenieNotifier.createAlert(evalContext)
require.Nil(t, notifierErr)
require.Nil(t, alertErr)
require.Equal(t, tags, []string{"keyOnly", "aKey:aValue"})
require.Equal(t, details, map[string]interface{}{"keyOnly": "", "aKey": "aValue", "url": ""})
}) })
}) })
} }
+423 -426
View File
@@ -12,7 +12,8 @@ import (
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations" "github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func presenceComparer(a, b string) bool { func presenceComparer(a, b string) bool {
@@ -26,516 +27,512 @@ func presenceComparer(a, b string) bool {
} }
func TestPagerdutyNotifier(t *testing.T) { func TestPagerdutyNotifier(t *testing.T) {
Convey("Pagerduty notifier tests", t, func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { json := `{ }`
Convey("empty settings should return error", func() {
json := `{ }`
settingsJSON, err := simplejson.NewJson([]byte(json)) settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil) require.Nil(t, err)
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "pageduty_testing", Name: "pageduty_testing",
Type: "pagerduty", Type: "pagerduty",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err = NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err = NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("severity should override default", func() { t.Run("severity should override default", func(t *testing.T) {
json := `{ "integrationKey": "abcdefgh0123456789", "severity": "info", "tags": ["foo"]}` json := `{ "integrationKey": "abcdefgh0123456789", "severity": "info", "tags": ["foo"]}`
settingsJSON, err := simplejson.NewJson([]byte(json)) settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil) require.Nil(t, err)
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "pagerduty_testing", Name: "pagerduty_testing",
Type: "pagerduty", Type: "pagerduty",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
pagerdutyNotifier := not.(*PagerdutyNotifier) pagerdutyNotifier := not.(*PagerdutyNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(pagerdutyNotifier.Name, ShouldEqual, "pagerduty_testing") require.Equal(t, "pagerduty_testing", pagerdutyNotifier.Name)
So(pagerdutyNotifier.Type, ShouldEqual, "pagerduty") require.Equal(t, "pagerduty", pagerdutyNotifier.Type)
So(pagerdutyNotifier.Key, ShouldEqual, "abcdefgh0123456789") require.Equal(t, "abcdefgh0123456789", pagerdutyNotifier.Key)
So(pagerdutyNotifier.Severity, ShouldEqual, "info") require.Equal(t, "info", pagerdutyNotifier.Severity)
So(pagerdutyNotifier.AutoResolve, ShouldBeFalse) require.False(t, pagerdutyNotifier.AutoResolve)
}) })
Convey("auto resolve and severity should have expected defaults", func() { t.Run("auto resolve and severity should have expected defaults", func(t *testing.T) {
json := `{ "integrationKey": "abcdefgh0123456789" }` json := `{ "integrationKey": "abcdefgh0123456789" }`
settingsJSON, err := simplejson.NewJson([]byte(json)) settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil) require.Nil(t, err)
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "pagerduty_testing", Name: "pagerduty_testing",
Type: "pagerduty", Type: "pagerduty",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
pagerdutyNotifier := not.(*PagerdutyNotifier) pagerdutyNotifier := not.(*PagerdutyNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(pagerdutyNotifier.Name, ShouldEqual, "pagerduty_testing") require.Equal(t, "pagerduty_testing", pagerdutyNotifier.Name)
So(pagerdutyNotifier.Type, ShouldEqual, "pagerduty") require.Equal(t, "pagerduty", pagerdutyNotifier.Type)
So(pagerdutyNotifier.Key, ShouldEqual, "abcdefgh0123456789") require.Equal(t, "abcdefgh0123456789", pagerdutyNotifier.Key)
So(pagerdutyNotifier.Severity, ShouldEqual, "critical") require.Equal(t, "critical", pagerdutyNotifier.Severity)
So(pagerdutyNotifier.AutoResolve, ShouldBeFalse) require.False(t, pagerdutyNotifier.AutoResolve)
}) })
Convey("settings should trigger incident", func() { t.Run("settings should trigger incident", func(t *testing.T) {
json := ` json := `
{ {
"integrationKey": "abcdefgh0123456789", "integrationKey": "abcdefgh0123456789",
"autoResolve": false "autoResolve": false
}` }`
settingsJSON, err := simplejson.NewJson([]byte(json)) settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil) require.Nil(t, err)
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "pagerduty_testing", Name: "pagerduty_testing",
Type: "pagerduty", Type: "pagerduty",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
pagerdutyNotifier := not.(*PagerdutyNotifier) pagerdutyNotifier := not.(*PagerdutyNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(pagerdutyNotifier.Name, ShouldEqual, "pagerduty_testing") require.Equal(t, "pagerduty_testing", pagerdutyNotifier.Name)
So(pagerdutyNotifier.Type, ShouldEqual, "pagerduty") require.Equal(t, "pagerduty", pagerdutyNotifier.Type)
So(pagerdutyNotifier.Key, ShouldEqual, "abcdefgh0123456789") require.Equal(t, "abcdefgh0123456789", pagerdutyNotifier.Key)
So(pagerdutyNotifier.AutoResolve, ShouldBeFalse) require.False(t, pagerdutyNotifier.AutoResolve)
}) })
Convey("should return properly formatted default v2 event payload", func() { t.Run("should return properly formatted default v2 event payload", func(t *testing.T) {
json := `{ json := `{
"integrationKey": "abcdefgh0123456789", "integrationKey": "abcdefgh0123456789",
"autoResolve": false "autoResolve": false
}` }`
settingsJSON, err := simplejson.NewJson([]byte(json)) settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil) require.Nil(t, err)
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "pagerduty_testing", Name: "pagerduty_testing",
Type: "pagerduty", Type: "pagerduty",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil) require.Nil(t, err)
pagerdutyNotifier := not.(*PagerdutyNotifier) pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{ evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0, ID: 0,
Name: "someRule", Name: "someRule",
Message: "someMessage", Message: "someMessage",
State: models.AlertStateAlerting, State: models.AlertStateAlerting,
}, &validations.OSSPluginRequestValidator{}) }, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true evalContext.IsTestRun = true
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext) payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil) require.Nil(t, err)
payload, err := simplejson.NewJson(payloadJSON) payload, err := simplejson.NewJson(payloadJSON)
So(err, ShouldBeNil) require.Nil(t, err)
diff := cmp.Diff(map[string]interface{}{ diff := cmp.Diff(map[string]interface{}{
"client": "Grafana", "client": "Grafana",
"client_url": "", "client_url": "",
"dedup_key": "alertId-0", "dedup_key": "alertId-0",
"event_action": "trigger", "event_action": "trigger",
"links": []interface{}{ "links": []interface{}{
map[string]interface{}{ map[string]interface{}{
"href": "", "href": "",
}, },
}, },
"payload": map[string]interface{}{ "payload": map[string]interface{}{
"component": "Grafana", "component": "Grafana",
"source": "<<PRESENCE>>", "source": "<<PRESENCE>>",
"custom_details": map[string]interface{}{ "custom_details": map[string]interface{}{
"state": "alerting", "state": "alerting",
}, },
"severity": "critical", "severity": "critical",
"summary": "someRule - someMessage", "summary": "someRule - someMessage",
"timestamp": "<<PRESENCE>>", "timestamp": "<<PRESENCE>>",
}, },
"routing_key": "abcdefgh0123456789", "routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer)) }, payload.Interface(), cmp.Comparer(presenceComparer))
So(diff, ShouldBeEmpty) require.Empty(t, diff)
}) })
Convey("should return properly formatted default v2 event payload with empty message", func() { t.Run("should return properly formatted default v2 event payload with empty message", func(t *testing.T) {
json := `{ json := `{
"integrationKey": "abcdefgh0123456789", "integrationKey": "abcdefgh0123456789",
"autoResolve": false "autoResolve": false
}` }`
settingsJSON, err := simplejson.NewJson([]byte(json)) settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil) require.Nil(t, err)
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "pagerduty_testing", Name: "pagerduty_testing",
Type: "pagerduty", Type: "pagerduty",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil) require.Nil(t, err)
pagerdutyNotifier := not.(*PagerdutyNotifier) pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{ evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0, ID: 0,
Name: "someRule", Name: "someRule",
State: models.AlertStateAlerting, State: models.AlertStateAlerting,
}, &validations.OSSPluginRequestValidator{}) }, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true evalContext.IsTestRun = true
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext) payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil) require.Nil(t, err)
payload, err := simplejson.NewJson(payloadJSON) payload, err := simplejson.NewJson(payloadJSON)
So(err, ShouldBeNil) require.Nil(t, err)
diff := cmp.Diff(map[string]interface{}{ diff := cmp.Diff(map[string]interface{}{
"client": "Grafana", "client": "Grafana",
"client_url": "", "client_url": "",
"dedup_key": "alertId-0", "dedup_key": "alertId-0",
"event_action": "trigger", "event_action": "trigger",
"links": []interface{}{ "links": []interface{}{
map[string]interface{}{ map[string]interface{}{
"href": "", "href": "",
}, },
}, },
"payload": map[string]interface{}{ "payload": map[string]interface{}{
"component": "Grafana", "component": "Grafana",
"source": "<<PRESENCE>>", "source": "<<PRESENCE>>",
"custom_details": map[string]interface{}{ "custom_details": map[string]interface{}{
"state": "alerting", "state": "alerting",
}, },
"severity": "critical", "severity": "critical",
"summary": "someRule", "summary": "someRule",
"timestamp": "<<PRESENCE>>", "timestamp": "<<PRESENCE>>",
}, },
"routing_key": "abcdefgh0123456789", "routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer)) }, payload.Interface(), cmp.Comparer(presenceComparer))
So(diff, ShouldBeEmpty) require.Empty(t, diff)
}) })
Convey("should return properly formatted payload with message moved to details", func() { t.Run("should return properly formatted payload with message moved to details", func(t *testing.T) {
json := `{ json := `{
"integrationKey": "abcdefgh0123456789", "integrationKey": "abcdefgh0123456789",
"autoResolve": false, "autoResolve": false,
"messageInDetails": true "messageInDetails": true
}` }`
settingsJSON, err := simplejson.NewJson([]byte(json)) settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil) require.Nil(t, err)
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "pagerduty_testing", Name: "pagerduty_testing",
Type: "pagerduty", Type: "pagerduty",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil) require.Nil(t, err)
pagerdutyNotifier := not.(*PagerdutyNotifier) pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{ evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0, ID: 0,
Name: "someRule", Name: "someRule",
Message: "someMessage", Message: "someMessage",
State: models.AlertStateAlerting, State: models.AlertStateAlerting,
}, &validations.OSSPluginRequestValidator{}) }, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true evalContext.IsTestRun = true
evalContext.EvalMatches = []*alerting.EvalMatch{ evalContext.EvalMatches = []*alerting.EvalMatch{
{ {
// nil is a terrible value to test with, but the cmp.Diff doesn't // nil is a terrible value to test with, but the cmp.Diff doesn't
// like comparing actual floats. So this is roughly the equivalent // like comparing actual floats. So this is roughly the equivalent
// of <<PRESENCE>> // of <<PRESENCE>>
Value: null.FloatFromPtr(nil), Value: null.FloatFromPtr(nil),
Metric: "someMetric", Metric: "someMetric",
},
}
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext)
require.NoError(t, err)
payload, err := simplejson.NewJson(payloadJSON)
require.NoError(t, err)
diff := cmp.Diff(map[string]interface{}{
"client": "Grafana",
"client_url": "",
"dedup_key": "alertId-0",
"event_action": "trigger",
"links": []interface{}{
map[string]interface{}{
"href": "",
},
},
"payload": map[string]interface{}{
"component": "Grafana",
"source": "<<PRESENCE>>",
"custom_details": map[string]interface{}{
"message": "someMessage",
"queries": map[string]interface{}{
"someMetric": nil,
}, },
} "state": "alerting",
},
"severity": "critical",
"summary": "someRule",
"timestamp": "<<PRESENCE>>",
},
"routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer))
require.Empty(t, diff)
})
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext) t.Run("should return properly formatted v2 event payload when using override tags", func(t *testing.T) {
So(err, ShouldBeNil) json := `{
payload, err := simplejson.NewJson(payloadJSON)
So(err, ShouldBeNil)
diff := cmp.Diff(map[string]interface{}{
"client": "Grafana",
"client_url": "",
"dedup_key": "alertId-0",
"event_action": "trigger",
"links": []interface{}{
map[string]interface{}{
"href": "",
},
},
"payload": map[string]interface{}{
"component": "Grafana",
"source": "<<PRESENCE>>",
"custom_details": map[string]interface{}{
"message": "someMessage",
"queries": map[string]interface{}{
"someMetric": nil,
},
"state": "alerting",
},
"severity": "critical",
"summary": "someRule",
"timestamp": "<<PRESENCE>>",
},
"routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer))
So(diff, ShouldBeEmpty)
})
Convey("should return properly formatted v2 event payload when using override tags", func() {
json := `{
"integrationKey": "abcdefgh0123456789", "integrationKey": "abcdefgh0123456789",
"autoResolve": false "autoResolve": false
}` }`
settingsJSON, err := simplejson.NewJson([]byte(json)) settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil) require.NoError(t, err)
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "pagerduty_testing", Name: "pagerduty_testing",
Type: "pagerduty", Type: "pagerduty",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil) require.NoError(t, err)
pagerdutyNotifier := not.(*PagerdutyNotifier) pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{ evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0, ID: 0,
Name: "someRule", Name: "someRule",
Message: "someMessage", Message: "someMessage",
State: models.AlertStateAlerting, State: models.AlertStateAlerting,
AlertRuleTags: []*models.Tag{ AlertRuleTags: []*models.Tag{
{Key: "keyOnly"}, {Key: "keyOnly"},
{Key: "group", Value: "aGroup"}, {Key: "group", Value: "aGroup"},
{Key: "class", Value: "aClass"}, {Key: "class", Value: "aClass"},
{Key: "component", Value: "aComponent"}, {Key: "component", Value: "aComponent"},
{Key: "severity", Value: "warning"}, {Key: "severity", Value: "warning"},
{Key: "dedup_key", Value: "key-" + strings.Repeat("x", 260)}, {Key: "dedup_key", Value: "key-" + strings.Repeat("x", 260)},
}, },
}, &validations.OSSPluginRequestValidator{}) }, &validations.OSSPluginRequestValidator{})
evalContext.ImagePublicURL = "http://somewhere.com/omg_dont_panic.png" evalContext.ImagePublicURL = "http://somewhere.com/omg_dont_panic.png"
evalContext.IsTestRun = true evalContext.IsTestRun = true
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext) payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil) require.NoError(t, err)
payload, err := simplejson.NewJson(payloadJSON) payload, err := simplejson.NewJson(payloadJSON)
So(err, ShouldBeNil) require.NoError(t, err)
diff := cmp.Diff(map[string]interface{}{ diff := cmp.Diff(map[string]interface{}{
"client": "Grafana", "client": "Grafana",
"client_url": "", "client_url": "",
"dedup_key": "key-" + strings.Repeat("x", 250), "dedup_key": "key-" + strings.Repeat("x", 250),
"event_action": "trigger", "event_action": "trigger",
"links": []interface{}{ "links": []interface{}{
map[string]interface{}{ map[string]interface{}{
"href": "", "href": "",
}, },
}, },
"payload": map[string]interface{}{ "payload": map[string]interface{}{
"source": "<<PRESENCE>>", "source": "<<PRESENCE>>",
"component": "aComponent", "component": "aComponent",
"custom_details": map[string]interface{}{ "custom_details": map[string]interface{}{
"group": "aGroup", "group": "aGroup",
"class": "aClass", "class": "aClass",
"component": "aComponent", "component": "aComponent",
"severity": "warning", "severity": "warning",
"dedup_key": "key-" + strings.Repeat("x", 250), "dedup_key": "key-" + strings.Repeat("x", 250),
"keyOnly": "", "keyOnly": "",
"state": "alerting", "state": "alerting",
}, },
"severity": "warning", "severity": "warning",
"summary": "someRule - someMessage", "summary": "someRule - someMessage",
"timestamp": "<<PRESENCE>>", "timestamp": "<<PRESENCE>>",
"class": "aClass", "class": "aClass",
"group": "aGroup", "group": "aGroup",
}, },
"images": []interface{}{ "images": []interface{}{
map[string]interface{}{ map[string]interface{}{
"src": "http://somewhere.com/omg_dont_panic.png", "src": "http://somewhere.com/omg_dont_panic.png",
}, },
}, },
"routing_key": "abcdefgh0123456789", "routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer)) }, payload.Interface(), cmp.Comparer(presenceComparer))
So(diff, ShouldBeEmpty) require.Empty(t, diff)
}) })
Convey("should support multiple levels of severity", func() { t.Run("should support multiple levels of severity", func(t *testing.T) {
json := `{ json := `{
"integrationKey": "abcdefgh0123456789", "integrationKey": "abcdefgh0123456789",
"autoResolve": false "autoResolve": false
}` }`
settingsJSON, err := simplejson.NewJson([]byte(json)) settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil) require.NoError(t, err)
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "pagerduty_testing", Name: "pagerduty_testing",
Type: "pagerduty", Type: "pagerduty",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil) require.NoError(t, err)
pagerdutyNotifier := not.(*PagerdutyNotifier) pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{ evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0, ID: 0,
Name: "someRule", Name: "someRule",
Message: "someMessage", Message: "someMessage",
State: models.AlertStateAlerting, State: models.AlertStateAlerting,
AlertRuleTags: []*models.Tag{ AlertRuleTags: []*models.Tag{
{Key: "keyOnly"}, {Key: "keyOnly"},
{Key: "group", Value: "aGroup"}, {Key: "group", Value: "aGroup"},
{Key: "class", Value: "aClass"}, {Key: "class", Value: "aClass"},
{Key: "component", Value: "aComponent"}, {Key: "component", Value: "aComponent"},
{Key: "severity", Value: "info"}, {Key: "severity", Value: "info"},
}, },
}, &validations.OSSPluginRequestValidator{}) }, &validations.OSSPluginRequestValidator{})
evalContext.ImagePublicURL = "http://somewhere.com/omg_dont_panic.png" evalContext.ImagePublicURL = "http://somewhere.com/omg_dont_panic.png"
evalContext.IsTestRun = true evalContext.IsTestRun = true
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext) payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil) require.NoError(t, err)
payload, err := simplejson.NewJson(payloadJSON) payload, err := simplejson.NewJson(payloadJSON)
So(err, ShouldBeNil) require.NoError(t, err)
diff := cmp.Diff(map[string]interface{}{ diff := cmp.Diff(map[string]interface{}{
"client": "Grafana", "client": "Grafana",
"client_url": "", "client_url": "",
"dedup_key": "alertId-0", "dedup_key": "alertId-0",
"event_action": "trigger", "event_action": "trigger",
"links": []interface{}{ "links": []interface{}{
map[string]interface{}{ map[string]interface{}{
"href": "", "href": "",
}, },
}, },
"payload": map[string]interface{}{ "payload": map[string]interface{}{
"source": "<<PRESENCE>>", "source": "<<PRESENCE>>",
"component": "aComponent", "component": "aComponent",
"custom_details": map[string]interface{}{ "custom_details": map[string]interface{}{
"group": "aGroup", "group": "aGroup",
"class": "aClass", "class": "aClass",
"component": "aComponent", "component": "aComponent",
"severity": "info", "severity": "info",
"keyOnly": "", "keyOnly": "",
"state": "alerting", "state": "alerting",
}, },
"severity": "info", "severity": "info",
"summary": "someRule - someMessage", "summary": "someRule - someMessage",
"timestamp": "<<PRESENCE>>", "timestamp": "<<PRESENCE>>",
"class": "aClass", "class": "aClass",
"group": "aGroup", "group": "aGroup",
}, },
"images": []interface{}{ "images": []interface{}{
map[string]interface{}{ map[string]interface{}{
"src": "http://somewhere.com/omg_dont_panic.png", "src": "http://somewhere.com/omg_dont_panic.png",
}, },
}, },
"routing_key": "abcdefgh0123456789", "routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer)) }, payload.Interface(), cmp.Comparer(presenceComparer))
So(diff, ShouldBeEmpty) require.Empty(t, diff)
}) })
Convey("should ignore invalid severity for PD but keep the tag", func() { t.Run("should ignore invalid severity for PD but keep the tag", func(t *testing.T) {
json := `{ json := `{
"integrationKey": "abcdefgh0123456789", "integrationKey": "abcdefgh0123456789",
"autoResolve": false, "autoResolve": false,
"severity": "critical" "severity": "critical"
}` }`
settingsJSON, err := simplejson.NewJson([]byte(json)) settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil) require.NoError(t, err)
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "pagerduty_testing", Name: "pagerduty_testing",
Type: "pagerduty", Type: "pagerduty",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil) require.NoError(t, err)
pagerdutyNotifier := not.(*PagerdutyNotifier) pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{ evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0, ID: 0,
Name: "someRule", Name: "someRule",
Message: "someMessage", Message: "someMessage",
State: models.AlertStateAlerting, State: models.AlertStateAlerting,
AlertRuleTags: []*models.Tag{ AlertRuleTags: []*models.Tag{
{Key: "keyOnly"}, {Key: "keyOnly"},
{Key: "group", Value: "aGroup"}, {Key: "group", Value: "aGroup"},
{Key: "class", Value: "aClass"}, {Key: "class", Value: "aClass"},
{Key: "component", Value: "aComponent"}, {Key: "component", Value: "aComponent"},
{Key: "severity", Value: "llama"}, {Key: "severity", Value: "llama"},
}, },
}, &validations.OSSPluginRequestValidator{}) }, &validations.OSSPluginRequestValidator{})
evalContext.ImagePublicURL = "http://somewhere.com/omg_dont_panic.png" evalContext.ImagePublicURL = "http://somewhere.com/omg_dont_panic.png"
evalContext.IsTestRun = true evalContext.IsTestRun = true
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext) payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil) require.NoError(t, err)
payload, err := simplejson.NewJson(payloadJSON) payload, err := simplejson.NewJson(payloadJSON)
So(err, ShouldBeNil) require.NoError(t, err)
diff := cmp.Diff(map[string]interface{}{ diff := cmp.Diff(map[string]interface{}{
"client": "Grafana", "client": "Grafana",
"client_url": "", "client_url": "",
"dedup_key": "alertId-0", "dedup_key": "alertId-0",
"event_action": "trigger", "event_action": "trigger",
"links": []interface{}{ "links": []interface{}{
map[string]interface{}{ map[string]interface{}{
"href": "", "href": "",
}, },
}, },
"payload": map[string]interface{}{ "payload": map[string]interface{}{
"source": "<<PRESENCE>>", "source": "<<PRESENCE>>",
"component": "aComponent", "component": "aComponent",
"custom_details": map[string]interface{}{ "custom_details": map[string]interface{}{
"group": "aGroup", "group": "aGroup",
"class": "aClass", "class": "aClass",
"component": "aComponent", "component": "aComponent",
"severity": "llama", "severity": "llama",
"keyOnly": "", "keyOnly": "",
"state": "alerting", "state": "alerting",
}, },
"severity": "critical", "severity": "critical",
"summary": "someRule - someMessage", "summary": "someRule - someMessage",
"timestamp": "<<PRESENCE>>", "timestamp": "<<PRESENCE>>",
"class": "aClass", "class": "aClass",
"group": "aGroup", "group": "aGroup",
}, },
"images": []interface{}{ "images": []interface{}{
map[string]interface{}{ map[string]interface{}{
"src": "http://somewhere.com/omg_dont_panic.png", "src": "http://somewhere.com/omg_dont_panic.png",
}, },
}, },
"routing_key": "abcdefgh0123456789", "routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer)) }, payload.Interface(), cmp.Comparer(presenceComparer))
So(diff, ShouldBeEmpty) require.Empty(t, diff)
})
})
}) })
} }
@@ -10,28 +10,28 @@ import (
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations" "github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func TestPushoverNotifier(t *testing.T) { func TestPushoverNotifier(t *testing.T) {
Convey("Pushover notifier tests", t, func() { t.Run("Parsing alert notification from settings", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "Pushover", Name: "Pushover",
Type: "pushover", Type: "pushover",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := NewPushoverNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := NewPushoverNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("from settings", func() { t.Run("from settings", func(t *testing.T) {
json := ` json := `
{ {
"apiToken": "4SrUFQL4A5V5TQ1z5Pg9nxHXPXSTve", "apiToken": "4SrUFQL4A5V5TQ1z5Pg9nxHXPXSTve",
"userKey": "tzNZYf36y0ohWwXo4XoUrB61rz1A4o", "userKey": "tzNZYf36y0ohWwXo4XoUrB61rz1A4o",
@@ -41,58 +41,55 @@ func TestPushoverNotifier(t *testing.T) {
"okSound": "magic" "okSound": "magic"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "Pushover", Name: "Pushover",
Type: "pushover", Type: "pushover",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewPushoverNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewPushoverNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
pushoverNotifier := not.(*PushoverNotifier) pushoverNotifier := not.(*PushoverNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(pushoverNotifier.Name, ShouldEqual, "Pushover") require.Equal(t, "Pushover", pushoverNotifier.Name)
So(pushoverNotifier.Type, ShouldEqual, "pushover") require.Equal(t, "pushover", pushoverNotifier.Type)
So(pushoverNotifier.APIToken, ShouldEqual, "4SrUFQL4A5V5TQ1z5Pg9nxHXPXSTve") require.Equal(t, "4SrUFQL4A5V5TQ1z5Pg9nxHXPXSTve", pushoverNotifier.APIToken)
So(pushoverNotifier.UserKey, ShouldEqual, "tzNZYf36y0ohWwXo4XoUrB61rz1A4o") require.Equal(t, "tzNZYf36y0ohWwXo4XoUrB61rz1A4o", pushoverNotifier.UserKey)
So(pushoverNotifier.AlertingPriority, ShouldEqual, 1) require.Equal(t, 1, pushoverNotifier.AlertingPriority)
So(pushoverNotifier.OKPriority, ShouldEqual, 2) require.Equal(t, 2, pushoverNotifier.OKPriority)
So(pushoverNotifier.AlertingSound, ShouldEqual, "pushover") require.Equal(t, "pushover", pushoverNotifier.AlertingSound)
So(pushoverNotifier.OKSound, ShouldEqual, "magic") require.Equal(t, "magic", pushoverNotifier.OKSound)
})
}) })
}) })
} }
func TestGenPushoverBody(t *testing.T) { func TestGenPushoverBody(t *testing.T) {
Convey("Pushover body generation tests", t, func() { t.Run("Given common sounds", func(t *testing.T) {
Convey("Given common sounds", func() { sirenSound := "siren_sound_tst"
sirenSound := "siren_sound_tst" successSound := "success_sound_tst"
successSound := "success_sound_tst" notifier := &PushoverNotifier{AlertingSound: sirenSound, OKSound: successSound}
notifier := &PushoverNotifier{AlertingSound: sirenSound, OKSound: successSound}
Convey("When alert is firing - should use siren sound", func() { t.Run("When alert is firing - should use siren sound", func(t *testing.T) {
evalContext := alerting.NewEvalContext(context.Background(), evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{ &alerting.Rule{
State: models.AlertStateAlerting, State: models.AlertStateAlerting,
}, &validations.OSSPluginRequestValidator{}) }, &validations.OSSPluginRequestValidator{})
_, pushoverBody, err := notifier.genPushoverBody(evalContext, "", "") _, pushoverBody, err := notifier.genPushoverBody(evalContext, "", "")
So(err, ShouldBeNil) require.Nil(t, err)
So(strings.Contains(pushoverBody.String(), sirenSound), ShouldBeTrue) require.True(t, strings.Contains(pushoverBody.String(), sirenSound))
}) })
Convey("When alert is ok - should use success sound", func() { t.Run("When alert is ok - should use success sound", func(t *testing.T) {
evalContext := alerting.NewEvalContext(context.Background(), evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{ &alerting.Rule{
State: models.AlertStateOK, State: models.AlertStateOK,
}, &validations.OSSPluginRequestValidator{}) }, &validations.OSSPluginRequestValidator{})
_, pushoverBody, err := notifier.genPushoverBody(evalContext, "", "") _, pushoverBody, err := notifier.genPushoverBody(evalContext, "", "")
So(err, ShouldBeNil) require.Nil(t, err)
So(strings.Contains(pushoverBody.String(), successSound), ShouldBeTrue) require.True(t, strings.Contains(pushoverBody.String(), successSound))
})
}) })
}) })
} }
+30 -31
View File
@@ -6,51 +6,50 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func TestSensuNotifier(t *testing.T) { func TestSensuNotifier(t *testing.T) {
Convey("Sensu notifier tests", t, func() { t.Run("Parsing alert notification from settings", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "sensu", Name: "sensu",
Type: "sensu", Type: "sensu",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := NewSensuNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := NewSensuNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("from settings", func() { t.Run("from settings", func(t *testing.T) {
json := ` json := `
{ {
"url": "http://sensu-api.example.com:4567/results", "url": "http://sensu-api.example.com:4567/results",
"source": "grafana_instance_01", "source": "grafana_instance_01",
"handler": "myhandler" "handler": "myhandler"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "sensu", Name: "sensu",
Type: "sensu", Type: "sensu",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewSensuNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewSensuNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
sensuNotifier := not.(*SensuNotifier) sensuNotifier := not.(*SensuNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(sensuNotifier.Name, ShouldEqual, "sensu") require.Equal(t, "sensu", sensuNotifier.Name)
So(sensuNotifier.Type, ShouldEqual, "sensu") require.Equal(t, "sensu", sensuNotifier.Type)
So(sensuNotifier.URL, ShouldEqual, "http://sensu-api.example.com:4567/results") require.Equal(t, "http://sensu-api.example.com:4567/results", sensuNotifier.URL)
So(sensuNotifier.Source, ShouldEqual, "grafana_instance_01") require.Equal(t, "grafana_instance_01", sensuNotifier.Source)
So(sensuNotifier.Handler, ShouldEqual, "myhandler") require.Equal(t, "myhandler", sensuNotifier.Handler)
})
}) })
}) })
} }
+43 -44
View File
@@ -6,69 +6,68 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func TestTeamsNotifier(t *testing.T) { func TestTeamsNotifier(t *testing.T) {
Convey("Teams notifier tests", t, func() { t.Run("Parsing alert notification from settings", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "ops", Name: "ops",
Type: "teams", Type: "teams",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := NewTeamsNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := NewTeamsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("from settings", func() { t.Run("from settings", func(t *testing.T) {
json := ` json := `
{ {
"url": "http://google.com" "url": "http://google.com"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "ops", Name: "ops",
Type: "teams", Type: "teams",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewTeamsNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewTeamsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
teamsNotifier := not.(*TeamsNotifier) teamsNotifier := not.(*TeamsNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(teamsNotifier.Name, ShouldEqual, "ops") require.Equal(t, "ops", teamsNotifier.Name)
So(teamsNotifier.Type, ShouldEqual, "teams") require.Equal(t, "teams", teamsNotifier.Type)
So(teamsNotifier.URL, ShouldEqual, "http://google.com") require.Equal(t, "http://google.com", teamsNotifier.URL)
}) })
Convey("from settings with Recipient and Mention", func() { t.Run("from settings with Recipient and Mention", func(t *testing.T) {
json := ` json := `
{ {
"url": "http://google.com" "url": "http://google.com"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "ops", Name: "ops",
Type: "teams", Type: "teams",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewTeamsNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewTeamsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
teamsNotifier := not.(*TeamsNotifier) teamsNotifier := not.(*TeamsNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(teamsNotifier.Name, ShouldEqual, "ops") require.Equal(t, "ops", teamsNotifier.Name)
So(teamsNotifier.Type, ShouldEqual, "teams") require.Equal(t, "teams", teamsNotifier.Type)
So(teamsNotifier.URL, ShouldEqual, "http://google.com") require.Equal(t, "http://google.com", teamsNotifier.URL)
})
}) })
}) })
} }
@@ -9,51 +9,67 @@ import (
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations" "github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func TestTelegramNotifier(t *testing.T) { func TestTelegramNotifier(t *testing.T) {
Convey("Telegram notifier tests", t, func() { t.Run("Parsing alert notification from settings", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "telegram_testing", Name: "telegram_testing",
Type: "telegram", Type: "telegram",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := NewTelegramNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := NewTelegramNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("settings should trigger incident", func() { t.Run("settings should trigger incident", func(t *testing.T) {
json := ` json := `
{ {
"bottoken": "abcdefgh0123456789", "bottoken": "abcdefgh0123456789",
"chatid": "-1234567890" "chatid": "-1234567890"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "telegram_testing", Name: "telegram_testing",
Type: "telegram", Type: "telegram",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewTelegramNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewTelegramNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
telegramNotifier := not.(*TelegramNotifier) telegramNotifier := not.(*TelegramNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(telegramNotifier.Name, ShouldEqual, "telegram_testing") require.Equal(t, "telegram_testing", telegramNotifier.Name)
So(telegramNotifier.Type, ShouldEqual, "telegram") require.Equal(t, "telegram", telegramNotifier.Type)
So(telegramNotifier.BotToken, ShouldEqual, "abcdefgh0123456789") require.Equal(t, "abcdefgh0123456789", telegramNotifier.BotToken)
So(telegramNotifier.ChatID, ShouldEqual, "-1234567890") require.Equal(t, "-1234567890", telegramNotifier.ChatID)
}) })
Convey("generateCaption should generate a message with all pertinent details", func() { t.Run("generateCaption should generate a message with all pertinent details", func(t *testing.T) {
evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{
Name: "This is an alarm",
Message: "Some kind of message.",
State: models.AlertStateOK,
}, &validations.OSSPluginRequestValidator{})
caption := generateImageCaption(evalContext, "http://grafa.url/abcdef", "")
require.LessOrEqual(t, len(caption), 1024)
require.Contains(t, caption, "Some kind of message.")
require.Contains(t, caption, "[OK] This is an alarm")
require.Contains(t, caption, "http://grafa.url/abcdef")
})
t.Run("When generating a message", func(t *testing.T) {
t.Run("URL should be skipped if it's too long", func(t *testing.T) {
evalContext := alerting.NewEvalContext(context.Background(), evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{ &alerting.Rule{
Name: "This is an alarm", Name: "This is an alarm",
@@ -61,65 +77,48 @@ func TestTelegramNotifier(t *testing.T) {
State: models.AlertStateOK, State: models.AlertStateOK,
}, &validations.OSSPluginRequestValidator{}) }, &validations.OSSPluginRequestValidator{})
caption := generateImageCaption(evalContext, "http://grafa.url/abcdef", "") caption := generateImageCaption(evalContext,
So(len(caption), ShouldBeLessThanOrEqualTo, 1024) "http://grafa.url/abcdefaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
So(caption, ShouldContainSubstring, "Some kind of message.") "foo bar")
So(caption, ShouldContainSubstring, "[OK] This is an alarm") require.LessOrEqual(t, len(caption), 1024)
So(caption, ShouldContainSubstring, "http://grafa.url/abcdef") require.Contains(t, caption, "Some kind of message.")
require.Contains(t, caption, "[OK] This is an alarm")
require.Contains(t, caption, "foo bar")
require.NotContains(t, caption, "http")
}) })
Convey("When generating a message", func() { t.Run("Message should be trimmed if it's too long", func(t *testing.T) {
Convey("URL should be skipped if it's too long", func() { evalContext := alerting.NewEvalContext(context.Background(),
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
&alerting.Rule{ Name: "This is an alarm",
Name: "This is an alarm", Message: "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I promise I will. Yes siree that's it. But suddenly Telegram increased the length so now we need some lorem ipsum to fix this test. Here we go: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus consectetur molestie cursus. Donec suscipit egestas nisi. Proin ut efficitur ex. Mauris mi augue, volutpat a nisi vel, euismod dictum arcu. Sed quis tempor eros, sed malesuada dolor. Ut orci augue, viverra sit amet blandit quis, faucibus sit amet ex. Duis condimentum efficitur lectus, id dignissim quam tempor id. Morbi sollicitudin rhoncus diam, id tincidunt lectus scelerisque vitae. Etiam imperdiet semper sem, vel eleifend ligula mollis eget. Etiam ultrices fringilla lacus, sit amet pharetra ex blandit quis. Suspendisse in egestas neque, et posuere lectus. Vestibulum eu ex dui. Sed molestie nulla a lobortis scelerisque. Nulla ipsum ex, iaculis vitae vehicula sit amet, fermentum eu eros.",
Message: "Some kind of message.", State: models.AlertStateOK,
State: models.AlertStateOK, }, &validations.OSSPluginRequestValidator{})
}, &validations.OSSPluginRequestValidator{})
caption := generateImageCaption(evalContext, caption := generateImageCaption(evalContext,
"http://grafa.url/abcdefaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "http://grafa.url/foo",
"foo bar") "")
So(len(caption), ShouldBeLessThanOrEqualTo, 1024) require.LessOrEqual(t, len(caption), 1024)
So(caption, ShouldContainSubstring, "Some kind of message.") require.Contains(t, caption, "[OK] This is an alarm")
So(caption, ShouldContainSubstring, "[OK] This is an alarm") require.NotContains(t, caption, "http")
So(caption, ShouldContainSubstring, "foo bar") require.Contains(t, caption, "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I promise I will. Yes siree that's it. But suddenly Telegram increased the length so now we need some lorem ipsum to fix this test. Here we go: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus consectetur molestie cursus. Donec suscipit egestas nisi. Proin ut efficitur ex. Mauris mi augue, volutpat a nisi vel, euismod dictum arcu. Sed quis tempor eros, sed malesuada dolor. Ut orci augue, viverra sit amet blandit quis, faucibus sit amet ex. Duis condimentum efficitur lectus, id dignissim quam tempor id. Morbi sollicitudin rhoncus diam, id tincidunt lectus scelerisque vitae. Etiam imperdiet semper sem, vel eleifend ligula mollis eget. Etiam ultrices fringilla lacus, sit amet pharetra ex blandit quis. Suspendisse in egestas neque, et posuere lectus. Vestibulum eu ex dui. Sed molestie nulla a lobortis sceleri")
So(caption, ShouldNotContainSubstring, "http") })
})
Convey("Message should be trimmed if it's too long", func() { t.Run("Metrics should be skipped if they don't fit", func(t *testing.T) {
evalContext := alerting.NewEvalContext(context.Background(), evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{ &alerting.Rule{
Name: "This is an alarm", Name: "This is an alarm",
Message: "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I promise I will. Yes siree that's it. But suddenly Telegram increased the length so now we need some lorem ipsum to fix this test. Here we go: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus consectetur molestie cursus. Donec suscipit egestas nisi. Proin ut efficitur ex. Mauris mi augue, volutpat a nisi vel, euismod dictum arcu. Sed quis tempor eros, sed malesuada dolor. Ut orci augue, viverra sit amet blandit quis, faucibus sit amet ex. Duis condimentum efficitur lectus, id dignissim quam tempor id. Morbi sollicitudin rhoncus diam, id tincidunt lectus scelerisque vitae. Etiam imperdiet semper sem, vel eleifend ligula mollis eget. Etiam ultrices fringilla lacus, sit amet pharetra ex blandit quis. Suspendisse in egestas neque, et posuere lectus. Vestibulum eu ex dui. Sed molestie nulla a lobortis scelerisque. Nulla ipsum ex, iaculis vitae vehicula sit amet, fermentum eu eros.", Message: "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I promise I will. Yes siree that's it. But suddenly Telegram increased the length so now we need some lorem ipsum to fix this test. Here we go: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus consectetur molestie cursus. Donec suscipit egestas nisi. Proin ut efficitur ex. Mauris mi augue, volutpat a nisi vel, euismod dictum arcu. Sed quis tempor eros, sed malesuada dolor. Ut orci augue, viverra sit amet blandit quis, faucibus sit amet ex. Duis condimentum efficitur lectus, id dignissim quam tempor id. Morbi sollicitudin rhoncus diam, id tincidunt lectus scelerisque vitae. Etiam imperdiet semper sem, vel eleifend ligula mollis eget. Etiam ultrices fringilla lacus, sit amet pharetra ex blandit quis. Suspendisse in egestas neque, et posuere lectus. Vestibulum eu ex dui. Sed molestie nulla a lobortis sceleri",
State: models.AlertStateOK, State: models.AlertStateOK,
}, &validations.OSSPluginRequestValidator{}) }, &validations.OSSPluginRequestValidator{})
caption := generateImageCaption(evalContext, caption := generateImageCaption(evalContext,
"http://grafa.url/foo", "http://grafa.url/foo",
"") "foo bar long song")
So(len(caption), ShouldBeLessThanOrEqualTo, 1024) require.LessOrEqual(t, len(caption), 1024)
So(caption, ShouldContainSubstring, "[OK] This is an alarm") require.Contains(t, caption, "[OK] This is an alarm")
So(caption, ShouldNotContainSubstring, "http") require.NotContains(t, caption, "http")
So(caption, ShouldContainSubstring, "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I promise I will. Yes siree that's it. But suddenly Telegram increased the length so now we need some lorem ipsum to fix this test. Here we go: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus consectetur molestie cursus. Donec suscipit egestas nisi. Proin ut efficitur ex. Mauris mi augue, volutpat a nisi vel, euismod dictum arcu. Sed quis tempor eros, sed malesuada dolor. Ut orci augue, viverra sit amet blandit quis, faucibus sit amet ex. Duis condimentum efficitur lectus, id dignissim quam tempor id. Morbi sollicitudin rhoncus diam, id tincidunt lectus scelerisque vitae. Etiam imperdiet semper sem, vel eleifend ligula mollis eget. Etiam ultrices fringilla lacus, sit amet pharetra ex blandit quis. Suspendisse in egestas neque, et posuere lectus. Vestibulum eu ex dui. Sed molestie nulla a lobortis sceleri") require.NotContains(t, caption, "foo bar")
})
Convey("Metrics should be skipped if they don't fit", func() {
evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{
Name: "This is an alarm",
Message: "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I promise I will. Yes siree that's it. But suddenly Telegram increased the length so now we need some lorem ipsum to fix this test. Here we go: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus consectetur molestie cursus. Donec suscipit egestas nisi. Proin ut efficitur ex. Mauris mi augue, volutpat a nisi vel, euismod dictum arcu. Sed quis tempor eros, sed malesuada dolor. Ut orci augue, viverra sit amet blandit quis, faucibus sit amet ex. Duis condimentum efficitur lectus, id dignissim quam tempor id. Morbi sollicitudin rhoncus diam, id tincidunt lectus scelerisque vitae. Etiam imperdiet semper sem, vel eleifend ligula mollis eget. Etiam ultrices fringilla lacus, sit amet pharetra ex blandit quis. Suspendisse in egestas neque, et posuere lectus. Vestibulum eu ex dui. Sed molestie nulla a lobortis sceleri",
State: models.AlertStateOK,
}, &validations.OSSPluginRequestValidator{})
caption := generateImageCaption(evalContext,
"http://grafa.url/foo",
"foo bar long song")
So(len(caption), ShouldBeLessThanOrEqualTo, 1024)
So(caption, ShouldContainSubstring, "[OK] This is an alarm")
So(caption, ShouldNotContainSubstring, "http")
So(caption, ShouldNotContainSubstring, "foo bar")
})
}) })
}) })
}) })
+73 -74
View File
@@ -8,118 +8,117 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func TestThreemaNotifier(t *testing.T) { func TestThreemaNotifier(t *testing.T) {
Convey("Threema notifier tests", t, func() { t.Run("Parsing alert notification from settings", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "threema_testing", Name: "threema_testing",
Type: "threema", Type: "threema",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("valid settings should be parsed successfully", func() { t.Run("valid settings should be parsed successfully", func(t *testing.T) {
json := ` json := `
{ {
"gateway_id": "*3MAGWID", "gateway_id": "*3MAGWID",
"recipient_id": "ECHOECHO", "recipient_id": "ECHOECHO",
"api_secret": "1234" "api_secret": "1234"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "threema_testing", Name: "threema_testing",
Type: "threema", Type: "threema",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil) require.Nil(t, err)
threemaNotifier := not.(*ThreemaNotifier) threemaNotifier := not.(*ThreemaNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(threemaNotifier.Name, ShouldEqual, "threema_testing") require.Equal(t, "threema_testing", threemaNotifier.Name)
So(threemaNotifier.Type, ShouldEqual, "threema") require.Equal(t, "threema", threemaNotifier.Type)
So(threemaNotifier.GatewayID, ShouldEqual, "*3MAGWID") require.Equal(t, "*3MAGWID", threemaNotifier.GatewayID)
So(threemaNotifier.RecipientID, ShouldEqual, "ECHOECHO") require.Equal(t, "ECHOECHO", threemaNotifier.RecipientID)
So(threemaNotifier.APISecret, ShouldEqual, "1234") require.Equal(t, "1234", threemaNotifier.APISecret)
}) })
Convey("invalid Threema Gateway IDs should be rejected (prefix)", func() { t.Run("invalid Threema Gateway IDs should be rejected (prefix)", func(t *testing.T) {
json := ` json := `
{ {
"gateway_id": "ECHOECHO", "gateway_id": "ECHOECHO",
"recipient_id": "ECHOECHO", "recipient_id": "ECHOECHO",
"api_secret": "1234" "api_secret": "1234"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "threema_testing", Name: "threema_testing",
Type: "threema", Type: "threema",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(not, ShouldBeNil) require.Nil(t, not)
var valErr alerting.ValidationError var valErr alerting.ValidationError
So(errors.As(err, &valErr), ShouldBeTrue) require.True(t, errors.As(err, &valErr))
So(valErr.Reason, ShouldEqual, "Invalid Threema Gateway ID: Must start with a *") require.Equal(t, "Invalid Threema Gateway ID: Must start with a *", valErr.Reason)
}) })
Convey("invalid Threema Gateway IDs should be rejected (length)", func() { t.Run("invalid Threema Gateway IDs should be rejected (length)", func(t *testing.T) {
json := ` json := `
{ {
"gateway_id": "*ECHOECHO", "gateway_id": "*ECHOECHO",
"recipient_id": "ECHOECHO", "recipient_id": "ECHOECHO",
"api_secret": "1234" "api_secret": "1234"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "threema_testing", Name: "threema_testing",
Type: "threema", Type: "threema",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(not, ShouldBeNil) require.Nil(t, not)
var valErr alerting.ValidationError var valErr alerting.ValidationError
So(errors.As(err, &valErr), ShouldBeTrue) require.True(t, errors.As(err, &valErr))
So(valErr.Reason, ShouldEqual, "Invalid Threema Gateway ID: Must be 8 characters long") require.Equal(t, "Invalid Threema Gateway ID: Must be 8 characters long", valErr.Reason)
}) })
Convey("invalid Threema Recipient IDs should be rejected (length)", func() { t.Run("invalid Threema Recipient IDs should be rejected (length)", func(t *testing.T) {
json := ` json := `
{ {
"gateway_id": "*3MAGWID", "gateway_id": "*3MAGWID",
"recipient_id": "ECHOECH", "recipient_id": "ECHOECH",
"api_secret": "1234" "api_secret": "1234"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "threema_testing", Name: "threema_testing",
Type: "threema", Type: "threema",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(not, ShouldBeNil) require.Nil(t, not)
var valErr alerting.ValidationError var valErr alerting.ValidationError
So(errors.As(err, &valErr), ShouldBeTrue) require.True(t, errors.As(err, &valErr))
So(valErr.Reason, ShouldEqual, "Invalid Threema Recipient ID: Must be 8 characters long") require.Equal(t, "Invalid Threema Recipient ID: Must be 8 characters long", valErr.Reason)
})
}) })
}) })
} }
+104 -105
View File
@@ -10,7 +10,8 @@ import (
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption" "github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations" "github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
) )
func presenceComparerInt(a, b int64) bool { func presenceComparerInt(a, b int64) bool {
@@ -23,140 +24,138 @@ func presenceComparerInt(a, b int64) bool {
return a == b return a == b
} }
func TestVictoropsNotifier(t *testing.T) { func TestVictoropsNotifier(t *testing.T) {
Convey("Victorops notifier tests", t, func() { t.Run("Parsing alert notification from settings", func(t *testing.T) {
Convey("Parsing alert notification from settings", func() { t.Run("empty settings should return error", func(t *testing.T) {
Convey("empty settings should return error", func() { json := `{ }`
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "victorops_testing", Name: "victorops_testing",
Type: "victorops", Type: "victorops",
Settings: settingsJSON, Settings: settingsJSON,
} }
_, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue) _, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil) require.Error(t, err)
}) })
Convey("from settings", func() { t.Run("from settings", func(t *testing.T) {
json := ` json := `
{ {
"url": "http://google.com" "url": "http://google.com"
}` }`
settingsJSON, _ := simplejson.NewJson([]byte(json)) settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "victorops_testing", Name: "victorops_testing",
Type: "victorops", Type: "victorops",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
victoropsNotifier := not.(*VictoropsNotifier) victoropsNotifier := not.(*VictoropsNotifier)
So(err, ShouldBeNil) require.Nil(t, err)
So(victoropsNotifier.Name, ShouldEqual, "victorops_testing") require.Equal(t, "victorops_testing", victoropsNotifier.Name)
So(victoropsNotifier.Type, ShouldEqual, "victorops") require.Equal(t, "victorops", victoropsNotifier.Type)
So(victoropsNotifier.URL, ShouldEqual, "http://google.com") require.Equal(t, "http://google.com", victoropsNotifier.URL)
}) })
Convey("should return properly formatted event payload when using severity override tag", func() { t.Run("should return properly formatted event payload when using severity override tag", func(t *testing.T) {
json := ` json := `
{ {
"url": "http://google.com" "url": "http://google.com"
}` }`
settingsJSON, err := simplejson.NewJson([]byte(json)) settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil) require.Nil(t, err)
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "victorops_testing", Name: "victorops_testing",
Type: "victorops", Type: "victorops",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil) require.Nil(t, err)
victoropsNotifier := not.(*VictoropsNotifier) victoropsNotifier := not.(*VictoropsNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{ evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0, ID: 0,
Name: "someRule", Name: "someRule",
Message: "someMessage", Message: "someMessage",
State: models.AlertStateAlerting, State: models.AlertStateAlerting,
AlertRuleTags: []*models.Tag{ AlertRuleTags: []*models.Tag{
{Key: "keyOnly"}, {Key: "keyOnly"},
{Key: "severity", Value: "warning"}, {Key: "severity", Value: "warning"},
}, },
}, &validations.OSSPluginRequestValidator{}) }, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true evalContext.IsTestRun = true
payload, err := victoropsNotifier.buildEventPayload(evalContext) payload, err := victoropsNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil) require.Nil(t, err)
diff := cmp.Diff(map[string]interface{}{ diff := cmp.Diff(map[string]interface{}{
"alert_url": "", "alert_url": "",
"entity_display_name": "[Alerting] someRule", "entity_display_name": "[Alerting] someRule",
"entity_id": "someRule", "entity_id": "someRule",
"message_type": "WARNING", "message_type": "WARNING",
"metrics": map[string]interface{}{}, "metrics": map[string]interface{}{},
"monitoring_tool": "Grafana v", "monitoring_tool": "Grafana v",
"state_message": "someMessage", "state_message": "someMessage",
"state_start_time": int64(-1), "state_start_time": int64(-1),
"timestamp": int64(-1), "timestamp": int64(-1),
}, payload.Interface(), cmp.Comparer(presenceComparerInt)) }, payload.Interface(), cmp.Comparer(presenceComparerInt))
So(diff, ShouldBeEmpty) require.Empty(t, diff)
}) })
Convey("resolving with severity works properly", func() { t.Run("resolving with severity works properly", func(t *testing.T) {
json := ` json := `
{ {
"url": "http://google.com" "url": "http://google.com"
}` }`
settingsJSON, err := simplejson.NewJson([]byte(json)) settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil) require.Nil(t, err)
model := &models.AlertNotification{ model := &models.AlertNotification{
Name: "victorops_testing", Name: "victorops_testing",
Type: "victorops", Type: "victorops",
Settings: settingsJSON, Settings: settingsJSON,
} }
not, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue) not, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil) require.Nil(t, err)
victoropsNotifier := not.(*VictoropsNotifier) victoropsNotifier := not.(*VictoropsNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{ evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0, ID: 0,
Name: "someRule", Name: "someRule",
Message: "someMessage", Message: "someMessage",
State: models.AlertStateOK, State: models.AlertStateOK,
AlertRuleTags: []*models.Tag{ AlertRuleTags: []*models.Tag{
{Key: "keyOnly"}, {Key: "keyOnly"},
{Key: "severity", Value: "warning"}, {Key: "severity", Value: "warning"},
}, },
}, &validations.OSSPluginRequestValidator{}) }, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true evalContext.IsTestRun = true
payload, err := victoropsNotifier.buildEventPayload(evalContext) payload, err := victoropsNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil) require.Nil(t, err)
diff := cmp.Diff(map[string]interface{}{ diff := cmp.Diff(map[string]interface{}{
"alert_url": "", "alert_url": "",
"entity_display_name": "[OK] someRule", "entity_display_name": "[OK] someRule",
"entity_id": "someRule", "entity_id": "someRule",
"message_type": "RECOVERY", "message_type": "RECOVERY",
"metrics": map[string]interface{}{}, "metrics": map[string]interface{}{},
"monitoring_tool": "Grafana v", "monitoring_tool": "Grafana v",
"state_message": "someMessage", "state_message": "someMessage",
"state_start_time": int64(-1), "state_start_time": int64(-1),
"timestamp": int64(-1), "timestamp": int64(-1),
}, payload.Interface(), cmp.Comparer(presenceComparerInt)) }, payload.Interface(), cmp.Comparer(presenceComparerInt))
So(diff, ShouldBeEmpty) require.Empty(t, diff)
})
}) })
}) })
} }