Add a test for `Notify` of the Discord integration (#4082)

Just to ensure this works correclty as expected, I originally thought there was a bug with the shadowing of the `content` varible but there isn't - to avoid further confusion I have followed up on this document left by George: https://github.com/prometheus/alertmanager/pull/3555#discussion_r1398448423

Signed-off-by: gotjosh <josue.abreu@gmail.com>
This commit is contained in:
gotjosh 2024-10-24 20:55:35 +01:00 committed by GitHub
parent 6b77acd166
commit 615d5ffa30
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 63 additions and 2 deletions

View File

@ -137,11 +137,11 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error)
if n.conf.WebhookURL != nil {
url = n.conf.WebhookURL.String()
} else {
content, err := os.ReadFile(n.conf.WebhookURLFile)
b, err := os.ReadFile(n.conf.WebhookURLFile)
if err != nil {
return false, fmt.Errorf("read webhook_url_file: %w", err)
}
url = strings.TrimSpace(string(content))
url = strings.TrimSpace(string(b))
}
w := webhook{

View File

@ -17,6 +17,7 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
@ -168,3 +169,63 @@ func TestDiscordReadingURLFromFile(t *testing.T) {
test.AssertNotifyLeaksNoSecret(ctx, t, notifier, u.String())
}
func TestDiscord_Notify(t *testing.T) {
// Create a fake HTTP server to simulate the Discord webhook
var resp string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Read the request as a string
body, err := io.ReadAll(r.Body)
require.NoError(t, err, "reading request body failed")
// Store the request body in the response
resp = string(body)
w.WriteHeader(http.StatusOK)
}))
// Create a temporary file to simulate the WebhookURLFile
tempFile, err := os.CreateTemp("", "webhook_url")
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, os.Remove(tempFile.Name()))
})
// Write the fake webhook URL to the temp file
_, err = tempFile.WriteString(srv.URL)
require.NoError(t, err)
// Create a DiscordConfig with the WebhookURLFile set
cfg := &config.DiscordConfig{
WebhookURLFile: tempFile.Name(),
HTTPConfig: &commoncfg.HTTPClientConfig{},
Title: "Test Title",
Message: "Test Message",
Content: "Test Content",
}
// Create a new Discord notifier
notifier, err := New(cfg, test.CreateTmpl(t), log.NewNopLogger())
require.NoError(t, err)
// Create a context and alerts
ctx := context.Background()
ctx = notify.WithGroupKey(ctx, "1")
alerts := []*types.Alert{
{
Alert: model.Alert{
Labels: model.LabelSet{
"lbl1": "val1",
},
StartsAt: time.Now(),
EndsAt: time.Now().Add(time.Hour),
},
},
}
// Call the Notify method
ok, err := notifier.Notify(ctx, alerts...)
require.NoError(t, err)
require.False(t, ok)
require.Equal(t, "{\"content\":\"Test Content\",\"embeds\":[{\"title\":\"Test Title\",\"description\":\"Test Message\",\"color\":10038562}]}\n", resp)
}