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
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 1293 additions and 1312 deletions

View File

@ -10,8 +10,9 @@ import (
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestReplaceIllegalCharswithUnderscore(t *testing.T) {
@ -80,57 +81,55 @@ func TestWhenAlertManagerShouldNotify(t *testing.T) {
//nolint:goconst
func TestAlertmanagerNotifier(t *testing.T) {
Convey("Alertmanager notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("Parsing alert notification from settings", func(t *testing.T) {
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "alertmanager",
Type: "alertmanager",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "alertmanager",
Type: "alertmanager",
Settings: settingsJSON,
}
_, err := NewAlertmanagerNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err := NewAlertmanagerNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("from settings", func() {
json := `{ "url": "http://127.0.0.1:9093/", "basicAuthUser": "user", "basicAuthPassword": "password" }`
t.Run("from settings", func(t *testing.T) {
json := `{ "url": "http://127.0.0.1:9093/", "basicAuthUser": "user", "basicAuthPassword": "password" }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "alertmanager",
Type: "alertmanager",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "alertmanager",
Type: "alertmanager",
Settings: settingsJSON,
}
not, err := NewAlertmanagerNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
alertmanagerNotifier := not.(*AlertmanagerNotifier)
not, err := NewAlertmanagerNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
alertmanagerNotifier := not.(*AlertmanagerNotifier)
So(err, ShouldBeNil)
So(alertmanagerNotifier.BasicAuthUser, ShouldEqual, "user")
So(alertmanagerNotifier.BasicAuthPassword, ShouldEqual, "password")
So(alertmanagerNotifier.URL, ShouldResemble, []string{"http://127.0.0.1:9093/"})
})
require.NoError(t, err)
require.Equal(t, alertmanagerNotifier.BasicAuthUser, "user")
require.Equal(t, alertmanagerNotifier.BasicAuthPassword, "password")
require.Equal(t, alertmanagerNotifier.URL, []string{"http://127.0.0.1:9093/"})
})
Convey("from settings with multiple alertmanager", func() {
json := `{ "url": "http://alertmanager1:9093,http://alertmanager2:9093" }`
t.Run("from settings with multiple alertmanager", func(t *testing.T) {
json := `{ "url": "http://alertmanager1:9093,http://alertmanager2:9093" }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "alertmanager",
Type: "alertmanager",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "alertmanager",
Type: "alertmanager",
Settings: settingsJSON,
}
not, err := NewAlertmanagerNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
alertmanagerNotifier := not.(*AlertmanagerNotifier)
not, err := NewAlertmanagerNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
alertmanagerNotifier := not.(*AlertmanagerNotifier)
So(err, ShouldBeNil)
So(alertmanagerNotifier.URL, ShouldResemble, []string{"http://alertmanager1:9093", "http://alertmanager2:9093"})
})
require.NoError(t, err)
require.Equal(t, alertmanagerNotifier.URL, []string{"http://alertmanager1:9093", "http://alertmanager2:9093"})
})
})
}

View File

@ -9,8 +9,9 @@ import (
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestShouldSendAlertNotification(t *testing.T) {
@ -184,38 +185,36 @@ func TestShouldSendAlertNotification(t *testing.T) {
}
func TestBaseNotifier(t *testing.T) {
Convey("default constructor for notifiers", t, func() {
bJSON := simplejson.New()
bJSON := simplejson.New()
model := &models.AlertNotification{
Uid: "1",
Name: "name",
Type: "email",
Settings: bJSON,
}
model := &models.AlertNotification{
Uid: "1",
Name: "name",
Type: "email",
Settings: bJSON,
}
Convey("can parse false value", func() {
bJSON.Set("uploadImage", false)
t.Run("can parse false value", func(t *testing.T) {
bJSON.Set("uploadImage", false)
base := NewNotifierBase(model)
So(base.UploadImage, ShouldBeFalse)
})
base := NewNotifierBase(model)
require.False(t, base.UploadImage)
})
Convey("can parse true value", func() {
bJSON.Set("uploadImage", true)
t.Run("can parse true value", func(t *testing.T) {
bJSON.Set("uploadImage", true)
base := NewNotifierBase(model)
So(base.UploadImage, ShouldBeTrue)
})
base := NewNotifierBase(model)
require.True(t, base.UploadImage)
})
Convey("default value should be true for backwards compatibility", func() {
base := NewNotifierBase(model)
So(base.UploadImage, ShouldBeTrue)
})
t.Run("default value should be true for backwards compatibility", func(t *testing.T) {
base := NewNotifierBase(model)
require.True(t, base.UploadImage)
})
Convey("default value should be false for backwards compatibility", func() {
base := NewNotifierBase(model)
So(base.DisableResolveMessage, ShouldBeFalse)
})
t.Run("default value should be false for backwards compatibility", func(t *testing.T) {
base := NewNotifierBase(model)
require.False(t, base.DisableResolveMessage)
})
}

View File

@ -9,51 +9,50 @@ import (
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func TestDingDingNotifier(t *testing.T) {
Convey("Dingding notifier tests", t, func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "dingding_testing",
Type: "dingding",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "dingding_testing",
Type: "dingding",
Settings: settingsJSON,
}
_, err := newDingDingNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
Convey("settings should trigger incident", func() {
json := `{ "url": "https://www.google.com" }`
_, err := newDingDingNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
t.Run("settings should trigger incident", func(t *testing.T) {
json := `{ "url": "https://www.google.com" }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "dingding_testing",
Type: "dingding",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "dingding_testing",
Type: "dingding",
Settings: settingsJSON,
}
not, err := newDingDingNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
notifier := not.(*DingDingNotifier)
not, err := newDingDingNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
notifier := not.(*DingDingNotifier)
So(err, ShouldBeNil)
So(notifier.Name, ShouldEqual, "dingding_testing")
So(notifier.Type, ShouldEqual, "dingding")
So(notifier.URL, ShouldEqual, "https://www.google.com")
require.Nil(t, err)
require.Equal(t, "dingding_testing", notifier.Name)
require.Equal(t, "dingding", notifier.Type)
require.Equal(t, "https://www.google.com", notifier.URL)
Convey("genBody should not panic", func() {
evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{
State: models.AlertStateAlerting,
Message: `{host="localhost"}`,
}, &validations.OSSPluginRequestValidator{})
_, err = notifier.genBody(evalContext, "")
So(err, ShouldBeNil)
})
t.Run("genBody should not panic", func(t *testing.T) {
evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{
State: models.AlertStateAlerting,
Message: `{host="localhost"}`,
}, &validations.OSSPluginRequestValidator{})
_, err = notifier.genBody(evalContext, "")
require.Nil(t, err)
})
})
}

View File

@ -6,51 +6,50 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func TestDiscordNotifier(t *testing.T) {
Convey("Discord notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("Parsing alert notification from settings", func(t *testing.T) {
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "discord_testing",
Type: "discord",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "discord_testing",
Type: "discord",
Settings: settingsJSON,
}
_, err := newDiscordNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err := newDiscordNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("settings should trigger incident", func() {
json := `
t.Run("settings should trigger incident", func(t *testing.T) {
json := `
{
"avatar_url": "https://grafana.com/img/fav32.png",
"content": "@everyone Please check this notification",
"url": "https://web.hook/"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "discord_testing",
Type: "discord",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "discord_testing",
Type: "discord",
Settings: settingsJSON,
}
not, err := newDiscordNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
discordNotifier := not.(*DiscordNotifier)
not, err := newDiscordNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
discordNotifier := not.(*DiscordNotifier)
So(err, ShouldBeNil)
So(discordNotifier.Name, ShouldEqual, "discord_testing")
So(discordNotifier.Type, ShouldEqual, "discord")
So(discordNotifier.AvatarURL, ShouldEqual, "https://grafana.com/img/fav32.png")
So(discordNotifier.Content, ShouldEqual, "@everyone Please check this notification")
So(discordNotifier.WebhookURL, ShouldEqual, "https://web.hook/")
})
require.Nil(t, err)
require.Equal(t, "discord_testing", discordNotifier.Name)
require.Equal(t, "discord", discordNotifier.Type)
require.Equal(t, "https://grafana.com/img/fav32.png", discordNotifier.AvatarURL)
require.Equal(t, "@everyone Please check this notification", discordNotifier.Content)
require.Equal(t, "https://web.hook/", discordNotifier.WebhookURL)
})
})
}

View File

@ -6,74 +6,73 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func TestEmailNotifier(t *testing.T) {
Convey("Email notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("Parsing alert notification from settings", func(t *testing.T) {
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "email",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "email",
Settings: settingsJSON,
}
_, err := NewEmailNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err := NewEmailNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("from settings", func() {
json := `
t.Run("from settings", func(t *testing.T) {
json := `
{
"addresses": "ops@grafana.org"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "email",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "email",
Settings: settingsJSON,
}
not, err := NewEmailNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
emailNotifier := not.(*EmailNotifier)
not, err := NewEmailNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
emailNotifier := not.(*EmailNotifier)
So(err, ShouldBeNil)
So(emailNotifier.Name, ShouldEqual, "ops")
So(emailNotifier.Type, ShouldEqual, "email")
So(emailNotifier.Addresses[0], ShouldEqual, "ops@grafana.org")
})
require.Nil(t, err)
require.Equal(t, "ops", emailNotifier.Name)
require.Equal(t, "email", emailNotifier.Type)
require.Equal(t, "ops@grafana.org", emailNotifier.Addresses[0])
})
Convey("from settings with two emails", func() {
json := `
t.Run("from settings with two emails", func(t *testing.T) {
json := `
{
"addresses": "ops@grafana.org;dev@grafana.org"
}`
settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil)
settingsJSON, err := simplejson.NewJson([]byte(json))
require.Nil(t, err)
model := &models.AlertNotification{
Name: "ops",
Type: "email",
Settings: settingsJSON,
}
model := &models.AlertNotification{
Name: "ops",
Type: "email",
Settings: settingsJSON,
}
not, err := NewEmailNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
emailNotifier := not.(*EmailNotifier)
not, err := NewEmailNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
emailNotifier := not.(*EmailNotifier)
So(err, ShouldBeNil)
So(emailNotifier.Name, ShouldEqual, "ops")
So(emailNotifier.Type, ShouldEqual, "email")
So(len(emailNotifier.Addresses), ShouldEqual, 2)
require.Nil(t, err)
require.Equal(t, "ops", emailNotifier.Name)
require.Equal(t, "email", emailNotifier.Type)
require.Equal(t, 2, len(emailNotifier.Addresses))
So(emailNotifier.Addresses[0], ShouldEqual, "ops@grafana.org")
So(emailNotifier.Addresses[1], ShouldEqual, "dev@grafana.org")
})
require.Equal(t, "ops@grafana.org", emailNotifier.Addresses[0])
require.Equal(t, "dev@grafana.org", emailNotifier.Addresses[1])
})
})
}

View File

@ -6,47 +6,46 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func TestGoogleChatNotifier(t *testing.T) {
Convey("Google Hangouts Chat notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("Parsing alert notification from settings", func(t *testing.T) {
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "googlechat",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "googlechat",
Settings: settingsJSON,
}
_, err := newGoogleChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err := newGoogleChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("from settings", func() {
json := `
t.Run("from settings", func(t *testing.T) {
json := `
{
"url": "http://google.com"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "googlechat",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "googlechat",
Settings: settingsJSON,
}
not, err := newGoogleChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
webhookNotifier := not.(*GoogleChatNotifier)
not, err := newGoogleChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
webhookNotifier := not.(*GoogleChatNotifier)
So(err, ShouldBeNil)
So(webhookNotifier.Name, ShouldEqual, "ops")
So(webhookNotifier.Type, ShouldEqual, "googlechat")
So(webhookNotifier.URL, ShouldEqual, "http://google.com")
})
require.Nil(t, err)
require.Equal(t, "ops", webhookNotifier.Name)
require.Equal(t, "googlechat", webhookNotifier.Type)
require.Equal(t, "http://google.com", webhookNotifier.URL)
})
})
}

View File

@ -6,75 +6,74 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
//nolint:goconst
func TestHipChatNotifier(t *testing.T) {
Convey("HipChat notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("Parsing alert notification from settings", func(t *testing.T) {
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "hipchat",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "hipchat",
Settings: settingsJSON,
}
_, err := NewHipChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err := NewHipChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("from settings", func() {
json := `
t.Run("from settings", func(t *testing.T) {
json := `
{
"url": "http://google.com"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "hipchat",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "hipchat",
Settings: settingsJSON,
}
not, err := NewHipChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
hipchatNotifier := not.(*HipChatNotifier)
not, err := NewHipChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
hipchatNotifier := not.(*HipChatNotifier)
So(err, ShouldBeNil)
So(hipchatNotifier.Name, ShouldEqual, "ops")
So(hipchatNotifier.Type, ShouldEqual, "hipchat")
So(hipchatNotifier.URL, ShouldEqual, "http://google.com")
So(hipchatNotifier.APIKey, ShouldEqual, "")
So(hipchatNotifier.RoomID, ShouldEqual, "")
})
require.Nil(t, err)
require.Equal(t, "ops", hipchatNotifier.Name)
require.Equal(t, "hipchat", hipchatNotifier.Type)
require.Equal(t, "http://google.com", hipchatNotifier.URL)
require.Equal(t, "", hipchatNotifier.APIKey)
require.Equal(t, "", hipchatNotifier.RoomID)
})
Convey("from settings with Recipient and Mention", func() {
json := `
t.Run("from settings with Recipient and Mention", func(t *testing.T) {
json := `
{
"url": "http://www.hipchat.com",
"apikey": "1234",
"roomid": "1234"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "hipchat",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "hipchat",
Settings: settingsJSON,
}
not, err := NewHipChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
hipchatNotifier := not.(*HipChatNotifier)
not, err := NewHipChatNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
hipchatNotifier := not.(*HipChatNotifier)
So(err, ShouldBeNil)
So(hipchatNotifier.Name, ShouldEqual, "ops")
So(hipchatNotifier.Type, ShouldEqual, "hipchat")
So(hipchatNotifier.URL, ShouldEqual, "http://www.hipchat.com")
So(hipchatNotifier.APIKey, ShouldEqual, "1234")
So(hipchatNotifier.RoomID, ShouldEqual, "1234")
})
require.Nil(t, err)
require.Equal(t, "ops", hipchatNotifier.Name)
require.Equal(t, "hipchat", hipchatNotifier.Type)
require.Equal(t, "http://www.hipchat.com", hipchatNotifier.URL)
require.Equal(t, "1234", hipchatNotifier.APIKey)
require.Equal(t, "1234", hipchatNotifier.RoomID)
})
})
}

View File

@ -6,49 +6,48 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func TestKafkaNotifier(t *testing.T) {
Convey("Kafka notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("Parsing alert notification from settings", func(t *testing.T) {
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "kafka_testing",
Type: "kafka",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "kafka_testing",
Type: "kafka",
Settings: settingsJSON,
}
_, err := NewKafkaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err := NewKafkaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("settings should send an event to kafka", func() {
json := `
t.Run("settings should send an event to kafka", func(t *testing.T) {
json := `
{
"kafkaRestProxy": "http://localhost:8082",
"kafkaTopic": "topic1"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "kafka_testing",
Type: "kafka",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "kafka_testing",
Type: "kafka",
Settings: settingsJSON,
}
not, err := NewKafkaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
kafkaNotifier := not.(*KafkaNotifier)
not, err := NewKafkaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
kafkaNotifier := not.(*KafkaNotifier)
So(err, ShouldBeNil)
So(kafkaNotifier.Name, ShouldEqual, "kafka_testing")
So(kafkaNotifier.Type, ShouldEqual, "kafka")
So(kafkaNotifier.Endpoint, ShouldEqual, "http://localhost:8082")
So(kafkaNotifier.Topic, ShouldEqual, "topic1")
})
require.Nil(t, err)
require.Equal(t, "kafka_testing", kafkaNotifier.Name)
require.Equal(t, "kafka", kafkaNotifier.Type)
require.Equal(t, "http://localhost:8082", kafkaNotifier.Endpoint)
require.Equal(t, "topic1", kafkaNotifier.Topic)
})
})
}

View File

@ -6,43 +6,42 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func TestLineNotifier(t *testing.T) {
Convey("Line notifier tests", t, func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "line_testing",
Type: "line",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "line_testing",
Type: "line",
Settings: settingsJSON,
}
_, err := NewLINENotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
Convey("settings should trigger incident", func() {
json := `
_, err := NewLINENotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
t.Run("settings should trigger incident", func(t *testing.T) {
json := `
{
"token": "abcdefgh0123456789"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "line_testing",
Type: "line",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "line_testing",
Type: "line",
Settings: settingsJSON,
}
not, err := NewLINENotifier(model, ossencryption.ProvideService().GetDecryptedValue)
lineNotifier := not.(*LineNotifier)
not, err := NewLINENotifier(model, ossencryption.ProvideService().GetDecryptedValue)
lineNotifier := not.(*LineNotifier)
So(err, ShouldBeNil)
So(lineNotifier.Name, ShouldEqual, "line_testing")
So(lineNotifier.Type, ShouldEqual, "line")
So(lineNotifier.Token, ShouldEqual, "abcdefgh0123456789")
})
require.Nil(t, err)
require.Equal(t, "line_testing", lineNotifier.Name)
require.Equal(t, "line", lineNotifier.Type)
require.Equal(t, "abcdefgh0123456789", lineNotifier.Token)
})
}

View File

@ -2,6 +2,8 @@ package notifiers
import (
"context"
"reflect"
"strings"
"testing"
"github.com/grafana/grafana/pkg/bus"
@ -10,217 +12,216 @@ import (
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func TestOpsGenieNotifier(t *testing.T) {
Convey("OpsGenie notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("Parsing alert notification from settings", func(t *testing.T) {
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "opsgenie_testing",
Type: "opsgenie",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "opsgenie_testing",
Type: "opsgenie",
Settings: settingsJSON,
}
_, err := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("settings should trigger incident", func() {
json := `
t.Run("settings should trigger incident", func(t *testing.T) {
json := `
{
"apiKey": "abcdefgh0123456789"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "opsgenie_testing",
Type: "opsgenie",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "opsgenie_testing",
Type: "opsgenie",
Settings: settingsJSON,
}
not, err := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
opsgenieNotifier := not.(*OpsGenieNotifier)
not, err := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
opsgenieNotifier := not.(*OpsGenieNotifier)
So(err, ShouldBeNil)
So(opsgenieNotifier.Name, ShouldEqual, "opsgenie_testing")
So(opsgenieNotifier.Type, ShouldEqual, "opsgenie")
So(opsgenieNotifier.APIKey, ShouldEqual, "abcdefgh0123456789")
})
require.Nil(t, err)
require.Equal(t, "opsgenie_testing", opsgenieNotifier.Name)
require.Equal(t, "opsgenie", opsgenieNotifier.Type)
require.Equal(t, "abcdefgh0123456789", opsgenieNotifier.APIKey)
})
})
Convey("Handling notification tags", func() {
Convey("invalid sendTagsAs value should return error", func() {
json := `{
t.Run("Handling notification tags", func(t *testing.T) {
t.Run("invalid sendTagsAs value should return error", func(t *testing.T) {
json := `{
"apiKey": "abcdefgh0123456789",
"sendTagsAs": "not_a_valid_value"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "opsgenie_testing",
Type: "opsgenie",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "opsgenie_testing",
Type: "opsgenie",
Settings: settingsJSON,
}
_, err := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
So(err, ShouldHaveSameTypeAs, alerting.ValidationError{})
So(err.Error(), ShouldEndWith, "Invalid value for sendTagsAs: \"not_a_valid_value\"")
})
_, err := NewOpsGenieNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
require.Equal(t, reflect.TypeOf(err), reflect.TypeOf(alerting.ValidationError{}))
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() {
json := `{
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 := `{
"apiKey": "abcdefgh0123456789"
}`
tagPairs := []*models.Tag{
{Key: "keyOnly"},
{Key: "aKey", Value: "aValue"},
tagPairs := []*models.Tag{
{Key: "keyOnly"},
{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{}{})
}
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": ""})
return err
})
Convey("alert payload should include tag pairs only as a map in the details key when sendAsTags=details", func() {
json := `{
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{}{"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",
"sendTagsAs": "details"
}`
tagPairs := []*models.Tag{
{Key: "keyOnly"},
{Key: "aKey", Value: "aValue"},
tagPairs := []*models.Tag{
{Key: "keyOnly"},
{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{}{})
}
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": ""})
return err
})
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() {
json := `{
alertErr := opsgenieNotifier.createAlert(evalContext)
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",
"sendTagsAs": "both"
}`
tagPairs := []*models.Tag{
{Key: "keyOnly"},
{Key: "aKey", Value: "aValue"},
tagPairs := []*models.Tag{
{Key: "keyOnly"},
{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{}{})
}
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": ""})
return err
})
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": ""})
})
})
}

View File

@ -12,7 +12,8 @@ import (
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func presenceComparer(a, b string) bool {
@ -26,516 +27,512 @@ func presenceComparer(a, b string) bool {
}
func TestPagerdutyNotifier(t *testing.T) {
Convey("Pagerduty notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil)
settingsJSON, err := simplejson.NewJson([]byte(json))
require.Nil(t, err)
model := &models.AlertNotification{
Name: "pageduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
model := &models.AlertNotification{
Name: "pageduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
_, err = NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err = NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("severity should override default", func() {
json := `{ "integrationKey": "abcdefgh0123456789", "severity": "info", "tags": ["foo"]}`
t.Run("severity should override default", func(t *testing.T) {
json := `{ "integrationKey": "abcdefgh0123456789", "severity": "info", "tags": ["foo"]}`
settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil)
settingsJSON, err := simplejson.NewJson([]byte(json))
require.Nil(t, err)
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
pagerdutyNotifier := not.(*PagerdutyNotifier)
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
pagerdutyNotifier := not.(*PagerdutyNotifier)
So(err, ShouldBeNil)
So(pagerdutyNotifier.Name, ShouldEqual, "pagerduty_testing")
So(pagerdutyNotifier.Type, ShouldEqual, "pagerduty")
So(pagerdutyNotifier.Key, ShouldEqual, "abcdefgh0123456789")
So(pagerdutyNotifier.Severity, ShouldEqual, "info")
So(pagerdutyNotifier.AutoResolve, ShouldBeFalse)
})
require.Nil(t, err)
require.Equal(t, "pagerduty_testing", pagerdutyNotifier.Name)
require.Equal(t, "pagerduty", pagerdutyNotifier.Type)
require.Equal(t, "abcdefgh0123456789", pagerdutyNotifier.Key)
require.Equal(t, "info", pagerdutyNotifier.Severity)
require.False(t, pagerdutyNotifier.AutoResolve)
})
Convey("auto resolve and severity should have expected defaults", func() {
json := `{ "integrationKey": "abcdefgh0123456789" }`
t.Run("auto resolve and severity should have expected defaults", func(t *testing.T) {
json := `{ "integrationKey": "abcdefgh0123456789" }`
settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil)
settingsJSON, err := simplejson.NewJson([]byte(json))
require.Nil(t, err)
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
pagerdutyNotifier := not.(*PagerdutyNotifier)
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
pagerdutyNotifier := not.(*PagerdutyNotifier)
So(err, ShouldBeNil)
So(pagerdutyNotifier.Name, ShouldEqual, "pagerduty_testing")
So(pagerdutyNotifier.Type, ShouldEqual, "pagerduty")
So(pagerdutyNotifier.Key, ShouldEqual, "abcdefgh0123456789")
So(pagerdutyNotifier.Severity, ShouldEqual, "critical")
So(pagerdutyNotifier.AutoResolve, ShouldBeFalse)
})
require.Nil(t, err)
require.Equal(t, "pagerduty_testing", pagerdutyNotifier.Name)
require.Equal(t, "pagerduty", pagerdutyNotifier.Type)
require.Equal(t, "abcdefgh0123456789", pagerdutyNotifier.Key)
require.Equal(t, "critical", pagerdutyNotifier.Severity)
require.False(t, pagerdutyNotifier.AutoResolve)
})
Convey("settings should trigger incident", func() {
json := `
t.Run("settings should trigger incident", func(t *testing.T) {
json := `
{
"integrationKey": "abcdefgh0123456789",
"autoResolve": false
}`
settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil)
settingsJSON, err := simplejson.NewJson([]byte(json))
require.Nil(t, err)
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
pagerdutyNotifier := not.(*PagerdutyNotifier)
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
pagerdutyNotifier := not.(*PagerdutyNotifier)
So(err, ShouldBeNil)
So(pagerdutyNotifier.Name, ShouldEqual, "pagerduty_testing")
So(pagerdutyNotifier.Type, ShouldEqual, "pagerduty")
So(pagerdutyNotifier.Key, ShouldEqual, "abcdefgh0123456789")
So(pagerdutyNotifier.AutoResolve, ShouldBeFalse)
})
require.Nil(t, err)
require.Equal(t, "pagerduty_testing", pagerdutyNotifier.Name)
require.Equal(t, "pagerduty", pagerdutyNotifier.Type)
require.Equal(t, "abcdefgh0123456789", pagerdutyNotifier.Key)
require.False(t, pagerdutyNotifier.AutoResolve)
})
Convey("should return properly formatted default v2 event payload", func() {
json := `{
t.Run("should return properly formatted default v2 event payload", func(t *testing.T) {
json := `{
"integrationKey": "abcdefgh0123456789",
"autoResolve": false
}`
settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil)
settingsJSON, err := simplejson.NewJson([]byte(json))
require.Nil(t, err)
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil)
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Nil(t, err)
pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
}, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true
pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
}, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil)
payload, err := simplejson.NewJson(payloadJSON)
So(err, ShouldBeNil)
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext)
require.Nil(t, err)
payload, err := simplejson.NewJson(payloadJSON)
require.Nil(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{}{
"state": "alerting",
},
"severity": "critical",
"summary": "someRule - someMessage",
"timestamp": "<<PRESENCE>>",
},
"routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer))
So(diff, ShouldBeEmpty)
})
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{}{
"state": "alerting",
},
"severity": "critical",
"summary": "someRule - someMessage",
"timestamp": "<<PRESENCE>>",
},
"routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer))
require.Empty(t, diff)
})
Convey("should return properly formatted default v2 event payload with empty message", func() {
json := `{
t.Run("should return properly formatted default v2 event payload with empty message", func(t *testing.T) {
json := `{
"integrationKey": "abcdefgh0123456789",
"autoResolve": false
}`
settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil)
settingsJSON, err := simplejson.NewJson([]byte(json))
require.Nil(t, err)
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil)
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Nil(t, err)
pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
State: models.AlertStateAlerting,
}, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true
pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
State: models.AlertStateAlerting,
}, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil)
payload, err := simplejson.NewJson(payloadJSON)
So(err, ShouldBeNil)
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext)
require.Nil(t, err)
payload, err := simplejson.NewJson(payloadJSON)
require.Nil(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{}{
"state": "alerting",
},
"severity": "critical",
"summary": "someRule",
"timestamp": "<<PRESENCE>>",
},
"routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer))
So(diff, ShouldBeEmpty)
})
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{}{
"state": "alerting",
},
"severity": "critical",
"summary": "someRule",
"timestamp": "<<PRESENCE>>",
},
"routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer))
require.Empty(t, diff)
})
Convey("should return properly formatted payload with message moved to details", func() {
json := `{
t.Run("should return properly formatted payload with message moved to details", func(t *testing.T) {
json := `{
"integrationKey": "abcdefgh0123456789",
"autoResolve": false,
"messageInDetails": true
}`
settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil)
settingsJSON, err := simplejson.NewJson([]byte(json))
require.Nil(t, err)
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil)
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Nil(t, err)
pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
}, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true
evalContext.EvalMatches = []*alerting.EvalMatch{
{
// nil is a terrible value to test with, but the cmp.Diff doesn't
// like comparing actual floats. So this is roughly the equivalent
// of <<PRESENCE>>
Value: null.FloatFromPtr(nil),
Metric: "someMetric",
pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
}, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true
evalContext.EvalMatches = []*alerting.EvalMatch{
{
// nil is a terrible value to test with, but the cmp.Diff doesn't
// like comparing actual floats. So this is roughly the equivalent
// of <<PRESENCE>>
Value: null.FloatFromPtr(nil),
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)
So(err, ShouldBeNil)
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 := `{
t.Run("should return properly formatted v2 event payload when using override tags", func(t *testing.T) {
json := `{
"integrationKey": "abcdefgh0123456789",
"autoResolve": false
}`
settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil)
settingsJSON, err := simplejson.NewJson([]byte(json))
require.NoError(t, err)
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil)
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.NoError(t, err)
pagerdutyNotifier := not.(*PagerdutyNotifier)
pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: []*models.Tag{
{Key: "keyOnly"},
{Key: "group", Value: "aGroup"},
{Key: "class", Value: "aClass"},
{Key: "component", Value: "aComponent"},
{Key: "severity", Value: "warning"},
{Key: "dedup_key", Value: "key-" + strings.Repeat("x", 260)},
},
}, &validations.OSSPluginRequestValidator{})
evalContext.ImagePublicURL = "http://somewhere.com/omg_dont_panic.png"
evalContext.IsTestRun = true
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: []*models.Tag{
{Key: "keyOnly"},
{Key: "group", Value: "aGroup"},
{Key: "class", Value: "aClass"},
{Key: "component", Value: "aComponent"},
{Key: "severity", Value: "warning"},
{Key: "dedup_key", Value: "key-" + strings.Repeat("x", 260)},
},
}, &validations.OSSPluginRequestValidator{})
evalContext.ImagePublicURL = "http://somewhere.com/omg_dont_panic.png"
evalContext.IsTestRun = true
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil)
payload, err := simplejson.NewJson(payloadJSON)
So(err, ShouldBeNil)
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": "key-" + strings.Repeat("x", 250),
"event_action": "trigger",
"links": []interface{}{
map[string]interface{}{
"href": "",
},
},
"payload": map[string]interface{}{
"source": "<<PRESENCE>>",
"component": "aComponent",
"custom_details": map[string]interface{}{
"group": "aGroup",
"class": "aClass",
"component": "aComponent",
"severity": "warning",
"dedup_key": "key-" + strings.Repeat("x", 250),
"keyOnly": "",
"state": "alerting",
},
"severity": "warning",
"summary": "someRule - someMessage",
"timestamp": "<<PRESENCE>>",
"class": "aClass",
"group": "aGroup",
},
"images": []interface{}{
map[string]interface{}{
"src": "http://somewhere.com/omg_dont_panic.png",
},
},
"routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer))
So(diff, ShouldBeEmpty)
})
diff := cmp.Diff(map[string]interface{}{
"client": "Grafana",
"client_url": "",
"dedup_key": "key-" + strings.Repeat("x", 250),
"event_action": "trigger",
"links": []interface{}{
map[string]interface{}{
"href": "",
},
},
"payload": map[string]interface{}{
"source": "<<PRESENCE>>",
"component": "aComponent",
"custom_details": map[string]interface{}{
"group": "aGroup",
"class": "aClass",
"component": "aComponent",
"severity": "warning",
"dedup_key": "key-" + strings.Repeat("x", 250),
"keyOnly": "",
"state": "alerting",
},
"severity": "warning",
"summary": "someRule - someMessage",
"timestamp": "<<PRESENCE>>",
"class": "aClass",
"group": "aGroup",
},
"images": []interface{}{
map[string]interface{}{
"src": "http://somewhere.com/omg_dont_panic.png",
},
},
"routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer))
require.Empty(t, diff)
})
Convey("should support multiple levels of severity", func() {
json := `{
t.Run("should support multiple levels of severity", func(t *testing.T) {
json := `{
"integrationKey": "abcdefgh0123456789",
"autoResolve": false
}`
settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil)
settingsJSON, err := simplejson.NewJson([]byte(json))
require.NoError(t, err)
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil)
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.NoError(t, err)
pagerdutyNotifier := not.(*PagerdutyNotifier)
pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: []*models.Tag{
{Key: "keyOnly"},
{Key: "group", Value: "aGroup"},
{Key: "class", Value: "aClass"},
{Key: "component", Value: "aComponent"},
{Key: "severity", Value: "info"},
},
}, &validations.OSSPluginRequestValidator{})
evalContext.ImagePublicURL = "http://somewhere.com/omg_dont_panic.png"
evalContext.IsTestRun = true
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: []*models.Tag{
{Key: "keyOnly"},
{Key: "group", Value: "aGroup"},
{Key: "class", Value: "aClass"},
{Key: "component", Value: "aComponent"},
{Key: "severity", Value: "info"},
},
}, &validations.OSSPluginRequestValidator{})
evalContext.ImagePublicURL = "http://somewhere.com/omg_dont_panic.png"
evalContext.IsTestRun = true
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil)
payload, err := simplejson.NewJson(payloadJSON)
So(err, ShouldBeNil)
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{}{
"source": "<<PRESENCE>>",
"component": "aComponent",
"custom_details": map[string]interface{}{
"group": "aGroup",
"class": "aClass",
"component": "aComponent",
"severity": "info",
"keyOnly": "",
"state": "alerting",
},
"severity": "info",
"summary": "someRule - someMessage",
"timestamp": "<<PRESENCE>>",
"class": "aClass",
"group": "aGroup",
},
"images": []interface{}{
map[string]interface{}{
"src": "http://somewhere.com/omg_dont_panic.png",
},
},
"routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer))
So(diff, ShouldBeEmpty)
})
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{}{
"source": "<<PRESENCE>>",
"component": "aComponent",
"custom_details": map[string]interface{}{
"group": "aGroup",
"class": "aClass",
"component": "aComponent",
"severity": "info",
"keyOnly": "",
"state": "alerting",
},
"severity": "info",
"summary": "someRule - someMessage",
"timestamp": "<<PRESENCE>>",
"class": "aClass",
"group": "aGroup",
},
"images": []interface{}{
map[string]interface{}{
"src": "http://somewhere.com/omg_dont_panic.png",
},
},
"routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer))
require.Empty(t, diff)
})
Convey("should ignore invalid severity for PD but keep the tag", func() {
json := `{
t.Run("should ignore invalid severity for PD but keep the tag", func(t *testing.T) {
json := `{
"integrationKey": "abcdefgh0123456789",
"autoResolve": false,
"severity": "critical"
}`
settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil)
settingsJSON, err := simplejson.NewJson([]byte(json))
require.NoError(t, err)
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
model := &models.AlertNotification{
Name: "pagerduty_testing",
Type: "pagerduty",
Settings: settingsJSON,
}
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil)
not, err := NewPagerdutyNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.NoError(t, err)
pagerdutyNotifier := not.(*PagerdutyNotifier)
pagerdutyNotifier := not.(*PagerdutyNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: []*models.Tag{
{Key: "keyOnly"},
{Key: "group", Value: "aGroup"},
{Key: "class", Value: "aClass"},
{Key: "component", Value: "aComponent"},
{Key: "severity", Value: "llama"},
},
}, &validations.OSSPluginRequestValidator{})
evalContext.ImagePublicURL = "http://somewhere.com/omg_dont_panic.png"
evalContext.IsTestRun = true
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: []*models.Tag{
{Key: "keyOnly"},
{Key: "group", Value: "aGroup"},
{Key: "class", Value: "aClass"},
{Key: "component", Value: "aComponent"},
{Key: "severity", Value: "llama"},
},
}, &validations.OSSPluginRequestValidator{})
evalContext.ImagePublicURL = "http://somewhere.com/omg_dont_panic.png"
evalContext.IsTestRun = true
payloadJSON, err := pagerdutyNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil)
payload, err := simplejson.NewJson(payloadJSON)
So(err, ShouldBeNil)
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{}{
"source": "<<PRESENCE>>",
"component": "aComponent",
"custom_details": map[string]interface{}{
"group": "aGroup",
"class": "aClass",
"component": "aComponent",
"severity": "llama",
"keyOnly": "",
"state": "alerting",
},
"severity": "critical",
"summary": "someRule - someMessage",
"timestamp": "<<PRESENCE>>",
"class": "aClass",
"group": "aGroup",
},
"images": []interface{}{
map[string]interface{}{
"src": "http://somewhere.com/omg_dont_panic.png",
},
},
"routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer))
So(diff, ShouldBeEmpty)
})
})
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{}{
"source": "<<PRESENCE>>",
"component": "aComponent",
"custom_details": map[string]interface{}{
"group": "aGroup",
"class": "aClass",
"component": "aComponent",
"severity": "llama",
"keyOnly": "",
"state": "alerting",
},
"severity": "critical",
"summary": "someRule - someMessage",
"timestamp": "<<PRESENCE>>",
"class": "aClass",
"group": "aGroup",
},
"images": []interface{}{
map[string]interface{}{
"src": "http://somewhere.com/omg_dont_panic.png",
},
},
"routing_key": "abcdefgh0123456789",
}, payload.Interface(), cmp.Comparer(presenceComparer))
require.Empty(t, diff)
})
}

View File

@ -10,28 +10,28 @@ import (
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func TestPushoverNotifier(t *testing.T) {
Convey("Pushover notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("Parsing alert notification from settings", func(t *testing.T) {
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "Pushover",
Type: "pushover",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "Pushover",
Type: "pushover",
Settings: settingsJSON,
}
_, err := NewPushoverNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err := NewPushoverNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("from settings", func() {
json := `
t.Run("from settings", func(t *testing.T) {
json := `
{
"apiToken": "4SrUFQL4A5V5TQ1z5Pg9nxHXPXSTve",
"userKey": "tzNZYf36y0ohWwXo4XoUrB61rz1A4o",
@ -41,58 +41,55 @@ func TestPushoverNotifier(t *testing.T) {
"okSound": "magic"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "Pushover",
Type: "pushover",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "Pushover",
Type: "pushover",
Settings: settingsJSON,
}
not, err := NewPushoverNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
pushoverNotifier := not.(*PushoverNotifier)
not, err := NewPushoverNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
pushoverNotifier := not.(*PushoverNotifier)
So(err, ShouldBeNil)
So(pushoverNotifier.Name, ShouldEqual, "Pushover")
So(pushoverNotifier.Type, ShouldEqual, "pushover")
So(pushoverNotifier.APIToken, ShouldEqual, "4SrUFQL4A5V5TQ1z5Pg9nxHXPXSTve")
So(pushoverNotifier.UserKey, ShouldEqual, "tzNZYf36y0ohWwXo4XoUrB61rz1A4o")
So(pushoverNotifier.AlertingPriority, ShouldEqual, 1)
So(pushoverNotifier.OKPriority, ShouldEqual, 2)
So(pushoverNotifier.AlertingSound, ShouldEqual, "pushover")
So(pushoverNotifier.OKSound, ShouldEqual, "magic")
})
require.Nil(t, err)
require.Equal(t, "Pushover", pushoverNotifier.Name)
require.Equal(t, "pushover", pushoverNotifier.Type)
require.Equal(t, "4SrUFQL4A5V5TQ1z5Pg9nxHXPXSTve", pushoverNotifier.APIToken)
require.Equal(t, "tzNZYf36y0ohWwXo4XoUrB61rz1A4o", pushoverNotifier.UserKey)
require.Equal(t, 1, pushoverNotifier.AlertingPriority)
require.Equal(t, 2, pushoverNotifier.OKPriority)
require.Equal(t, "pushover", pushoverNotifier.AlertingSound)
require.Equal(t, "magic", pushoverNotifier.OKSound)
})
})
}
func TestGenPushoverBody(t *testing.T) {
Convey("Pushover body generation tests", t, func() {
Convey("Given common sounds", func() {
sirenSound := "siren_sound_tst"
successSound := "success_sound_tst"
notifier := &PushoverNotifier{AlertingSound: sirenSound, OKSound: successSound}
t.Run("Given common sounds", func(t *testing.T) {
sirenSound := "siren_sound_tst"
successSound := "success_sound_tst"
notifier := &PushoverNotifier{AlertingSound: sirenSound, OKSound: successSound}
Convey("When alert is firing - should use siren sound", func() {
evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{
State: models.AlertStateAlerting,
}, &validations.OSSPluginRequestValidator{})
_, pushoverBody, err := notifier.genPushoverBody(evalContext, "", "")
t.Run("When alert is firing - should use siren sound", func(t *testing.T) {
evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{
State: models.AlertStateAlerting,
}, &validations.OSSPluginRequestValidator{})
_, pushoverBody, err := notifier.genPushoverBody(evalContext, "", "")
So(err, ShouldBeNil)
So(strings.Contains(pushoverBody.String(), sirenSound), ShouldBeTrue)
})
require.Nil(t, err)
require.True(t, strings.Contains(pushoverBody.String(), sirenSound))
})
Convey("When alert is ok - should use success sound", func() {
evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{
State: models.AlertStateOK,
}, &validations.OSSPluginRequestValidator{})
_, pushoverBody, err := notifier.genPushoverBody(evalContext, "", "")
t.Run("When alert is ok - should use success sound", func(t *testing.T) {
evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{
State: models.AlertStateOK,
}, &validations.OSSPluginRequestValidator{})
_, pushoverBody, err := notifier.genPushoverBody(evalContext, "", "")
So(err, ShouldBeNil)
So(strings.Contains(pushoverBody.String(), successSound), ShouldBeTrue)
})
require.Nil(t, err)
require.True(t, strings.Contains(pushoverBody.String(), successSound))
})
})
}

View File

@ -6,51 +6,50 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func TestSensuNotifier(t *testing.T) {
Convey("Sensu notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("Parsing alert notification from settings", func(t *testing.T) {
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "sensu",
Type: "sensu",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "sensu",
Type: "sensu",
Settings: settingsJSON,
}
_, err := NewSensuNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err := NewSensuNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("from settings", func() {
json := `
t.Run("from settings", func(t *testing.T) {
json := `
{
"url": "http://sensu-api.example.com:4567/results",
"source": "grafana_instance_01",
"handler": "myhandler"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "sensu",
Type: "sensu",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "sensu",
Type: "sensu",
Settings: settingsJSON,
}
not, err := NewSensuNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
sensuNotifier := not.(*SensuNotifier)
not, err := NewSensuNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
sensuNotifier := not.(*SensuNotifier)
So(err, ShouldBeNil)
So(sensuNotifier.Name, ShouldEqual, "sensu")
So(sensuNotifier.Type, ShouldEqual, "sensu")
So(sensuNotifier.URL, ShouldEqual, "http://sensu-api.example.com:4567/results")
So(sensuNotifier.Source, ShouldEqual, "grafana_instance_01")
So(sensuNotifier.Handler, ShouldEqual, "myhandler")
})
require.Nil(t, err)
require.Equal(t, "sensu", sensuNotifier.Name)
require.Equal(t, "sensu", sensuNotifier.Type)
require.Equal(t, "http://sensu-api.example.com:4567/results", sensuNotifier.URL)
require.Equal(t, "grafana_instance_01", sensuNotifier.Source)
require.Equal(t, "myhandler", sensuNotifier.Handler)
})
})
}

View File

@ -6,69 +6,68 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func TestTeamsNotifier(t *testing.T) {
Convey("Teams notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("Parsing alert notification from settings", func(t *testing.T) {
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "teams",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "teams",
Settings: settingsJSON,
}
_, err := NewTeamsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err := NewTeamsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("from settings", func() {
json := `
t.Run("from settings", func(t *testing.T) {
json := `
{
"url": "http://google.com"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "teams",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "teams",
Settings: settingsJSON,
}
not, err := NewTeamsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
teamsNotifier := not.(*TeamsNotifier)
not, err := NewTeamsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
teamsNotifier := not.(*TeamsNotifier)
So(err, ShouldBeNil)
So(teamsNotifier.Name, ShouldEqual, "ops")
So(teamsNotifier.Type, ShouldEqual, "teams")
So(teamsNotifier.URL, ShouldEqual, "http://google.com")
})
require.Nil(t, err)
require.Equal(t, "ops", teamsNotifier.Name)
require.Equal(t, "teams", teamsNotifier.Type)
require.Equal(t, "http://google.com", teamsNotifier.URL)
})
Convey("from settings with Recipient and Mention", func() {
json := `
t.Run("from settings with Recipient and Mention", func(t *testing.T) {
json := `
{
"url": "http://google.com"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "teams",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "ops",
Type: "teams",
Settings: settingsJSON,
}
not, err := NewTeamsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
teamsNotifier := not.(*TeamsNotifier)
not, err := NewTeamsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
teamsNotifier := not.(*TeamsNotifier)
So(err, ShouldBeNil)
So(teamsNotifier.Name, ShouldEqual, "ops")
So(teamsNotifier.Type, ShouldEqual, "teams")
So(teamsNotifier.URL, ShouldEqual, "http://google.com")
})
require.Nil(t, err)
require.Equal(t, "ops", teamsNotifier.Name)
require.Equal(t, "teams", teamsNotifier.Type)
require.Equal(t, "http://google.com", teamsNotifier.URL)
})
})
}

View File

@ -9,51 +9,67 @@ import (
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func TestTelegramNotifier(t *testing.T) {
Convey("Telegram notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("Parsing alert notification from settings", func(t *testing.T) {
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "telegram_testing",
Type: "telegram",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "telegram_testing",
Type: "telegram",
Settings: settingsJSON,
}
_, err := NewTelegramNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err := NewTelegramNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("settings should trigger incident", func() {
json := `
t.Run("settings should trigger incident", func(t *testing.T) {
json := `
{
"bottoken": "abcdefgh0123456789",
"chatid": "-1234567890"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "telegram_testing",
Type: "telegram",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "telegram_testing",
Type: "telegram",
Settings: settingsJSON,
}
not, err := NewTelegramNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
telegramNotifier := not.(*TelegramNotifier)
not, err := NewTelegramNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
telegramNotifier := not.(*TelegramNotifier)
So(err, ShouldBeNil)
So(telegramNotifier.Name, ShouldEqual, "telegram_testing")
So(telegramNotifier.Type, ShouldEqual, "telegram")
So(telegramNotifier.BotToken, ShouldEqual, "abcdefgh0123456789")
So(telegramNotifier.ChatID, ShouldEqual, "-1234567890")
})
require.Nil(t, err)
require.Equal(t, "telegram_testing", telegramNotifier.Name)
require.Equal(t, "telegram", telegramNotifier.Type)
require.Equal(t, "abcdefgh0123456789", telegramNotifier.BotToken)
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(),
&alerting.Rule{
Name: "This is an alarm",
@ -61,65 +77,48 @@ func TestTelegramNotifier(t *testing.T) {
State: models.AlertStateOK,
}, &validations.OSSPluginRequestValidator{})
caption := generateImageCaption(evalContext, "http://grafa.url/abcdef", "")
So(len(caption), ShouldBeLessThanOrEqualTo, 1024)
So(caption, ShouldContainSubstring, "Some kind of message.")
So(caption, ShouldContainSubstring, "[OK] This is an alarm")
So(caption, ShouldContainSubstring, "http://grafa.url/abcdef")
caption := generateImageCaption(evalContext,
"http://grafa.url/abcdefaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"foo bar")
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, "foo bar")
require.NotContains(t, caption, "http")
})
Convey("When generating a message", func() {
Convey("URL should be skipped if it's too long", func() {
evalContext := alerting.NewEvalContext(context.Background(),
&alerting.Rule{
Name: "This is an alarm",
Message: "Some kind of message.",
State: models.AlertStateOK,
}, &validations.OSSPluginRequestValidator{})
t.Run("Message should be trimmed if it's too long", func(t *testing.T) {
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 scelerisque. Nulla ipsum ex, iaculis vitae vehicula sit amet, fermentum eu eros.",
State: models.AlertStateOK,
}, &validations.OSSPluginRequestValidator{})
caption := generateImageCaption(evalContext,
"http://grafa.url/abcdefaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"foo bar")
So(len(caption), ShouldBeLessThanOrEqualTo, 1024)
So(caption, ShouldContainSubstring, "Some kind of message.")
So(caption, ShouldContainSubstring, "[OK] This is an alarm")
So(caption, ShouldContainSubstring, "foo bar")
So(caption, ShouldNotContainSubstring, "http")
})
caption := generateImageCaption(evalContext,
"http://grafa.url/foo",
"")
require.LessOrEqual(t, len(caption), 1024)
require.Contains(t, caption, "[OK] This is an alarm")
require.NotContains(t, caption, "http")
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")
})
Convey("Message should be trimmed if it's too long", 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 scelerisque. Nulla ipsum ex, iaculis vitae vehicula sit amet, fermentum eu eros.",
State: models.AlertStateOK,
}, &validations.OSSPluginRequestValidator{})
t.Run("Metrics should be skipped if they don't fit", func(t *testing.T) {
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",
"")
So(len(caption), ShouldBeLessThanOrEqualTo, 1024)
So(caption, ShouldContainSubstring, "[OK] This is an alarm")
So(caption, ShouldNotContainSubstring, "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")
})
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")
})
caption := generateImageCaption(evalContext,
"http://grafa.url/foo",
"foo bar long song")
require.LessOrEqual(t, len(caption), 1024)
require.Contains(t, caption, "[OK] This is an alarm")
require.NotContains(t, caption, "http")
require.NotContains(t, caption, "foo bar")
})
})
})

View File

@ -8,118 +8,117 @@ import (
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func TestThreemaNotifier(t *testing.T) {
Convey("Threema notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("Parsing alert notification from settings", func(t *testing.T) {
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "threema_testing",
Type: "threema",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "threema_testing",
Type: "threema",
Settings: settingsJSON,
}
_, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("valid settings should be parsed successfully", func() {
json := `
t.Run("valid settings should be parsed successfully", func(t *testing.T) {
json := `
{
"gateway_id": "*3MAGWID",
"recipient_id": "ECHOECHO",
"api_secret": "1234"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "threema_testing",
Type: "threema",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "threema_testing",
Type: "threema",
Settings: settingsJSON,
}
not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil)
threemaNotifier := not.(*ThreemaNotifier)
not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Nil(t, err)
threemaNotifier := not.(*ThreemaNotifier)
So(err, ShouldBeNil)
So(threemaNotifier.Name, ShouldEqual, "threema_testing")
So(threemaNotifier.Type, ShouldEqual, "threema")
So(threemaNotifier.GatewayID, ShouldEqual, "*3MAGWID")
So(threemaNotifier.RecipientID, ShouldEqual, "ECHOECHO")
So(threemaNotifier.APISecret, ShouldEqual, "1234")
})
require.Nil(t, err)
require.Equal(t, "threema_testing", threemaNotifier.Name)
require.Equal(t, "threema", threemaNotifier.Type)
require.Equal(t, "*3MAGWID", threemaNotifier.GatewayID)
require.Equal(t, "ECHOECHO", threemaNotifier.RecipientID)
require.Equal(t, "1234", threemaNotifier.APISecret)
})
Convey("invalid Threema Gateway IDs should be rejected (prefix)", func() {
json := `
t.Run("invalid Threema Gateway IDs should be rejected (prefix)", func(t *testing.T) {
json := `
{
"gateway_id": "ECHOECHO",
"recipient_id": "ECHOECHO",
"api_secret": "1234"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "threema_testing",
Type: "threema",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "threema_testing",
Type: "threema",
Settings: settingsJSON,
}
not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(not, ShouldBeNil)
var valErr alerting.ValidationError
So(errors.As(err, &valErr), ShouldBeTrue)
So(valErr.Reason, ShouldEqual, "Invalid Threema Gateway ID: Must start with a *")
})
not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Nil(t, not)
var valErr alerting.ValidationError
require.True(t, errors.As(err, &valErr))
require.Equal(t, "Invalid Threema Gateway ID: Must start with a *", valErr.Reason)
})
Convey("invalid Threema Gateway IDs should be rejected (length)", func() {
json := `
t.Run("invalid Threema Gateway IDs should be rejected (length)", func(t *testing.T) {
json := `
{
"gateway_id": "*ECHOECHO",
"recipient_id": "ECHOECHO",
"api_secret": "1234"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "threema_testing",
Type: "threema",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "threema_testing",
Type: "threema",
Settings: settingsJSON,
}
not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(not, ShouldBeNil)
var valErr alerting.ValidationError
So(errors.As(err, &valErr), ShouldBeTrue)
So(valErr.Reason, ShouldEqual, "Invalid Threema Gateway ID: Must be 8 characters long")
})
not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Nil(t, not)
var valErr alerting.ValidationError
require.True(t, errors.As(err, &valErr))
require.Equal(t, "Invalid Threema Gateway ID: Must be 8 characters long", valErr.Reason)
})
Convey("invalid Threema Recipient IDs should be rejected (length)", func() {
json := `
t.Run("invalid Threema Recipient IDs should be rejected (length)", func(t *testing.T) {
json := `
{
"gateway_id": "*3MAGWID",
"recipient_id": "ECHOECH",
"api_secret": "1234"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "threema_testing",
Type: "threema",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "threema_testing",
Type: "threema",
Settings: settingsJSON,
}
not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(not, ShouldBeNil)
var valErr alerting.ValidationError
So(errors.As(err, &valErr), ShouldBeTrue)
So(valErr.Reason, ShouldEqual, "Invalid Threema Recipient ID: Must be 8 characters long")
})
not, err := NewThreemaNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Nil(t, not)
var valErr alerting.ValidationError
require.True(t, errors.As(err, &valErr))
require.Equal(t, "Invalid Threema Recipient ID: Must be 8 characters long", valErr.Reason)
})
})
}

View File

@ -10,7 +10,8 @@ import (
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/validations"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/require"
)
func presenceComparerInt(a, b int64) bool {
@ -23,140 +24,138 @@ func presenceComparerInt(a, b int64) bool {
return a == b
}
func TestVictoropsNotifier(t *testing.T) {
Convey("Victorops notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
t.Run("Parsing alert notification from settings", func(t *testing.T) {
t.Run("empty settings should return error", func(t *testing.T) {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "victorops_testing",
Type: "victorops",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "victorops_testing",
Type: "victorops",
Settings: settingsJSON,
}
_, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldNotBeNil)
})
_, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Error(t, err)
})
Convey("from settings", func() {
json := `
t.Run("from settings", func(t *testing.T) {
json := `
{
"url": "http://google.com"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "victorops_testing",
Type: "victorops",
Settings: settingsJSON,
}
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &models.AlertNotification{
Name: "victorops_testing",
Type: "victorops",
Settings: settingsJSON,
}
not, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
victoropsNotifier := not.(*VictoropsNotifier)
not, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
victoropsNotifier := not.(*VictoropsNotifier)
So(err, ShouldBeNil)
So(victoropsNotifier.Name, ShouldEqual, "victorops_testing")
So(victoropsNotifier.Type, ShouldEqual, "victorops")
So(victoropsNotifier.URL, ShouldEqual, "http://google.com")
})
require.Nil(t, err)
require.Equal(t, "victorops_testing", victoropsNotifier.Name)
require.Equal(t, "victorops", victoropsNotifier.Type)
require.Equal(t, "http://google.com", victoropsNotifier.URL)
})
Convey("should return properly formatted event payload when using severity override tag", func() {
json := `
t.Run("should return properly formatted event payload when using severity override tag", func(t *testing.T) {
json := `
{
"url": "http://google.com"
}`
settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil)
settingsJSON, err := simplejson.NewJson([]byte(json))
require.Nil(t, err)
model := &models.AlertNotification{
Name: "victorops_testing",
Type: "victorops",
Settings: settingsJSON,
}
model := &models.AlertNotification{
Name: "victorops_testing",
Type: "victorops",
Settings: settingsJSON,
}
not, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil)
not, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Nil(t, err)
victoropsNotifier := not.(*VictoropsNotifier)
victoropsNotifier := not.(*VictoropsNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: []*models.Tag{
{Key: "keyOnly"},
{Key: "severity", Value: "warning"},
},
}, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateAlerting,
AlertRuleTags: []*models.Tag{
{Key: "keyOnly"},
{Key: "severity", Value: "warning"},
},
}, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true
payload, err := victoropsNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil)
payload, err := victoropsNotifier.buildEventPayload(evalContext)
require.Nil(t, err)
diff := cmp.Diff(map[string]interface{}{
"alert_url": "",
"entity_display_name": "[Alerting] someRule",
"entity_id": "someRule",
"message_type": "WARNING",
"metrics": map[string]interface{}{},
"monitoring_tool": "Grafana v",
"state_message": "someMessage",
"state_start_time": int64(-1),
"timestamp": int64(-1),
}, payload.Interface(), cmp.Comparer(presenceComparerInt))
So(diff, ShouldBeEmpty)
})
Convey("resolving with severity works properly", func() {
json := `
diff := cmp.Diff(map[string]interface{}{
"alert_url": "",
"entity_display_name": "[Alerting] someRule",
"entity_id": "someRule",
"message_type": "WARNING",
"metrics": map[string]interface{}{},
"monitoring_tool": "Grafana v",
"state_message": "someMessage",
"state_start_time": int64(-1),
"timestamp": int64(-1),
}, payload.Interface(), cmp.Comparer(presenceComparerInt))
require.Empty(t, diff)
})
t.Run("resolving with severity works properly", func(t *testing.T) {
json := `
{
"url": "http://google.com"
}`
settingsJSON, err := simplejson.NewJson([]byte(json))
So(err, ShouldBeNil)
settingsJSON, err := simplejson.NewJson([]byte(json))
require.Nil(t, err)
model := &models.AlertNotification{
Name: "victorops_testing",
Type: "victorops",
Settings: settingsJSON,
}
model := &models.AlertNotification{
Name: "victorops_testing",
Type: "victorops",
Settings: settingsJSON,
}
not, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
So(err, ShouldBeNil)
not, err := NewVictoropsNotifier(model, ossencryption.ProvideService().GetDecryptedValue)
require.Nil(t, err)
victoropsNotifier := not.(*VictoropsNotifier)
victoropsNotifier := not.(*VictoropsNotifier)
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateOK,
AlertRuleTags: []*models.Tag{
{Key: "keyOnly"},
{Key: "severity", Value: "warning"},
},
}, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true
evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{
ID: 0,
Name: "someRule",
Message: "someMessage",
State: models.AlertStateOK,
AlertRuleTags: []*models.Tag{
{Key: "keyOnly"},
{Key: "severity", Value: "warning"},
},
}, &validations.OSSPluginRequestValidator{})
evalContext.IsTestRun = true
payload, err := victoropsNotifier.buildEventPayload(evalContext)
So(err, ShouldBeNil)
payload, err := victoropsNotifier.buildEventPayload(evalContext)
require.Nil(t, err)
diff := cmp.Diff(map[string]interface{}{
"alert_url": "",
"entity_display_name": "[OK] someRule",
"entity_id": "someRule",
"message_type": "RECOVERY",
"metrics": map[string]interface{}{},
"monitoring_tool": "Grafana v",
"state_message": "someMessage",
"state_start_time": int64(-1),
"timestamp": int64(-1),
}, payload.Interface(), cmp.Comparer(presenceComparerInt))
So(diff, ShouldBeEmpty)
})
diff := cmp.Diff(map[string]interface{}{
"alert_url": "",
"entity_display_name": "[OK] someRule",
"entity_id": "someRule",
"message_type": "RECOVERY",
"metrics": map[string]interface{}{},
"monitoring_tool": "Grafana v",
"state_message": "someMessage",
"state_start_time": int64(-1),
"timestamp": int64(-1),
}, payload.Interface(), cmp.Comparer(presenceComparerInt))
require.Empty(t, diff)
})
})
}