1
2
3
4
5
6
7
8
9
10
11
12
13
14 package webhook
15
16 import (
17 "bytes"
18 "fmt"
19 "io"
20 "net/http"
21 "net/url"
22 "testing"
23
24 "github.com/go-kit/log"
25 commoncfg "github.com/prometheus/common/config"
26 "github.com/stretchr/testify/require"
27
28 "github.com/prometheus/alertmanager/config"
29 "github.com/prometheus/alertmanager/notify/test"
30 "github.com/prometheus/alertmanager/types"
31 )
32
33 func TestWebhookRetry(t *testing.T) {
34 u, err := url.Parse("http://example.com")
35 if err != nil {
36 require.NoError(t, err)
37 }
38 notifier, err := New(
39 &config.WebhookConfig{
40 URL: &config.URL{URL: u},
41 HTTPConfig: &commoncfg.HTTPClientConfig{},
42 },
43 test.CreateTmpl(t),
44 log.NewNopLogger(),
45 )
46 if err != nil {
47 require.NoError(t, err)
48 }
49
50 t.Run("test retry status code", func(t *testing.T) {
51 for statusCode, expected := range test.RetryTests(test.DefaultRetryCodes()) {
52 actual, _ := notifier.retrier.Check(statusCode, nil)
53 require.Equal(t, expected, actual, fmt.Sprintf("error on status %d", statusCode))
54 }
55 })
56
57 t.Run("test retry error details", func(t *testing.T) {
58 for _, tc := range []struct {
59 status int
60 body io.Reader
61
62 exp string
63 }{
64 {
65 status: http.StatusBadRequest,
66 body: bytes.NewBuffer([]byte(
67 `{"status":"invalid event"}`,
68 )),
69
70 exp: fmt.Sprintf(`unexpected status code %d: %s: {"status":"invalid event"}`, http.StatusBadRequest, u.String()),
71 },
72 {
73 status: http.StatusBadRequest,
74
75 exp: fmt.Sprintf(`unexpected status code %d: %s`, http.StatusBadRequest, u.String()),
76 },
77 } {
78 t.Run("", func(t *testing.T) {
79 _, err = notifier.retrier.Check(tc.status, tc.body)
80 require.Equal(t, tc.exp, err.Error())
81 })
82 }
83 })
84 }
85
86 func TestWebhookTruncateAlerts(t *testing.T) {
87 alerts := make([]*types.Alert, 10)
88
89 truncatedAlerts, numTruncated := truncateAlerts(0, alerts)
90 require.Len(t, truncatedAlerts, 10)
91 require.EqualValues(t, numTruncated, 0)
92
93 truncatedAlerts, numTruncated = truncateAlerts(4, alerts)
94 require.Len(t, truncatedAlerts, 4)
95 require.EqualValues(t, numTruncated, 6)
96
97 truncatedAlerts, numTruncated = truncateAlerts(100, alerts)
98 require.Len(t, truncatedAlerts, 10)
99 require.EqualValues(t, numTruncated, 0)
100 }
101
View as plain text