...

Source file src/github.com/prometheus/alertmanager/notify/webex/webex_test.go

Documentation: github.com/prometheus/alertmanager/notify/webex

     1  // Copyright 2022 Prometheus Team
     2  // Licensed under the Apache License, Version 2.0 (the "License");
     3  // you may not use this file except in compliance with the License.
     4  // You may obtain a copy of the License at
     5  //
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package webex
    15  
    16  import (
    17  	"context"
    18  	"fmt"
    19  	"io"
    20  	"net/http"
    21  	"net/http/httptest"
    22  	"net/url"
    23  	"testing"
    24  	"time"
    25  
    26  	"github.com/go-kit/log"
    27  	commoncfg "github.com/prometheus/common/config"
    28  	"github.com/prometheus/common/model"
    29  	"github.com/stretchr/testify/require"
    30  
    31  	"github.com/prometheus/alertmanager/config"
    32  	"github.com/prometheus/alertmanager/notify"
    33  	"github.com/prometheus/alertmanager/notify/test"
    34  	"github.com/prometheus/alertmanager/types"
    35  )
    36  
    37  func TestWebexRetry(t *testing.T) {
    38  	testWebhookURL, err := url.Parse("https://api.ciscospark.com/v1/message")
    39  	require.NoError(t, err)
    40  
    41  	notifier, err := New(
    42  		&config.WebexConfig{
    43  			HTTPConfig: &commoncfg.HTTPClientConfig{},
    44  			APIURL:     &config.URL{URL: testWebhookURL},
    45  		},
    46  		test.CreateTmpl(t),
    47  		log.NewNopLogger(),
    48  	)
    49  	require.NoError(t, err)
    50  
    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  func TestWebexTemplating(t *testing.T) {
    58  	tc := []struct {
    59  		name string
    60  
    61  		cfg       *config.WebexConfig
    62  		Message   string
    63  		expJSON   string
    64  		commonCfg *commoncfg.HTTPClientConfig
    65  
    66  		retry     bool
    67  		errMsg    string
    68  		expHeader string
    69  	}{
    70  		{
    71  			name: "with a valid message and a set http_config.authorization, it is formatted as expected",
    72  			cfg: &config.WebexConfig{
    73  				Message: `{{ template "webex.default.message" . }}`,
    74  			},
    75  			commonCfg: &commoncfg.HTTPClientConfig{
    76  				Authorization: &commoncfg.Authorization{Type: "Bearer", Credentials: "anewsecret"},
    77  			},
    78  
    79  			expJSON:   `{"markdown":"\n\nAlerts Firing:\nLabels:\n - lbl1 = val1\n - lbl3 = val3\nAnnotations:\nSource: \nLabels:\n - lbl1 = val1\n - lbl2 = val2\nAnnotations:\nSource: \n\n\n\n"}`,
    80  			retry:     false,
    81  			expHeader: "Bearer anewsecret",
    82  		},
    83  		{
    84  			name: "with templating errors, it fails.",
    85  			cfg: &config.WebexConfig{
    86  				Message: "{{ ",
    87  			},
    88  			commonCfg: &commoncfg.HTTPClientConfig{},
    89  			errMsg:    "template: :1: unclosed action",
    90  		},
    91  	}
    92  
    93  	for _, tt := range tc {
    94  		t.Run(tt.name, func(t *testing.T) {
    95  			var out []byte
    96  			var header http.Header
    97  			srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    98  				var err error
    99  				out, err = io.ReadAll(r.Body)
   100  				header = r.Header.Clone()
   101  				require.NoError(t, err)
   102  			}))
   103  			defer srv.Close()
   104  			u, _ := url.Parse(srv.URL)
   105  
   106  			tt.cfg.APIURL = &config.URL{URL: u}
   107  			tt.cfg.HTTPConfig = tt.commonCfg
   108  			notifierWebex, err := New(tt.cfg, test.CreateTmpl(t), log.NewNopLogger())
   109  			require.NoError(t, err)
   110  
   111  			ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
   112  			defer cancel()
   113  			ctx = notify.WithGroupKey(ctx, "1")
   114  
   115  			ok, err := notifierWebex.Notify(ctx, []*types.Alert{
   116  				{
   117  					Alert: model.Alert{
   118  						Labels: model.LabelSet{
   119  							"lbl1": "val1",
   120  							"lbl3": "val3",
   121  						},
   122  						StartsAt: time.Now(),
   123  						EndsAt:   time.Now().Add(time.Hour),
   124  					},
   125  				},
   126  				{
   127  					Alert: model.Alert{
   128  						Labels: model.LabelSet{
   129  							"lbl1": "val1",
   130  							"lbl2": "val2",
   131  						},
   132  						StartsAt: time.Now(),
   133  						EndsAt:   time.Now().Add(time.Hour),
   134  					},
   135  				},
   136  			}...)
   137  
   138  			if tt.errMsg == "" {
   139  				require.NoError(t, err)
   140  				require.Equal(t, tt.expHeader, header.Get("Authorization"))
   141  				require.JSONEq(t, tt.expJSON, string(out))
   142  			} else {
   143  				require.Error(t, err)
   144  				require.Contains(t, err.Error(), tt.errMsg)
   145  			}
   146  
   147  			require.Equal(t, tt.retry, ok)
   148  		})
   149  	}
   150  }
   151  

View as plain text