...

Source file src/github.com/prometheus/alertmanager/notify/telegram/telegram_test.go

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

     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 telegram
    15  
    16  import (
    17  	"context"
    18  	"encoding/json"
    19  	"fmt"
    20  	"io"
    21  	"net/http"
    22  	"net/http/httptest"
    23  	"net/url"
    24  	"testing"
    25  	"time"
    26  
    27  	"github.com/go-kit/log"
    28  	commoncfg "github.com/prometheus/common/config"
    29  	"github.com/prometheus/common/model"
    30  	"github.com/stretchr/testify/require"
    31  	"gopkg.in/yaml.v2"
    32  
    33  	"github.com/prometheus/alertmanager/config"
    34  	"github.com/prometheus/alertmanager/notify"
    35  	"github.com/prometheus/alertmanager/notify/test"
    36  	"github.com/prometheus/alertmanager/types"
    37  )
    38  
    39  func TestTelegramUnmarshal(t *testing.T) {
    40  	in := `
    41  route:
    42    receiver: test
    43  receivers:
    44  - name: test
    45    telegram_configs:
    46    - chat_id: 1234
    47      bot_token: secret
    48  `
    49  	var c config.Config
    50  	err := yaml.Unmarshal([]byte(in), &c)
    51  	require.NoError(t, err)
    52  
    53  	require.Len(t, c.Receivers, 1)
    54  	require.Len(t, c.Receivers[0].TelegramConfigs, 1)
    55  
    56  	require.Equal(t, "https://api.telegram.org", c.Receivers[0].TelegramConfigs[0].APIUrl.String())
    57  	require.Equal(t, config.Secret("secret"), c.Receivers[0].TelegramConfigs[0].BotToken)
    58  	require.Equal(t, int64(1234), c.Receivers[0].TelegramConfigs[0].ChatID)
    59  	require.Equal(t, "HTML", c.Receivers[0].TelegramConfigs[0].ParseMode)
    60  }
    61  
    62  func TestTelegramRetry(t *testing.T) {
    63  	// Fake url for testing purposes
    64  	fakeURL := config.URL{
    65  		URL: &url.URL{
    66  			Scheme: "https",
    67  			Host:   "FAKE_API",
    68  		},
    69  	}
    70  	notifier, err := New(
    71  		&config.TelegramConfig{
    72  			HTTPConfig: &commoncfg.HTTPClientConfig{},
    73  			APIUrl:     &fakeURL,
    74  		},
    75  		test.CreateTmpl(t),
    76  		log.NewNopLogger(),
    77  	)
    78  	require.NoError(t, err)
    79  
    80  	for statusCode, expected := range test.RetryTests(test.DefaultRetryCodes()) {
    81  		actual, _ := notifier.retrier.Check(statusCode, nil)
    82  		require.Equal(t, expected, actual, fmt.Sprintf("error on status %d", statusCode))
    83  	}
    84  }
    85  
    86  func TestTelegramNotify(t *testing.T) {
    87  	for _, tc := range []struct {
    88  		name    string
    89  		cfg     config.TelegramConfig
    90  		expText string
    91  	}{
    92  		{
    93  			name: "No escaping by default",
    94  			cfg: config.TelegramConfig{
    95  				Message:    "<code>x < y</code>",
    96  				HTTPConfig: &commoncfg.HTTPClientConfig{},
    97  			},
    98  			expText: "<code>x < y</code>",
    99  		},
   100  		{
   101  			name: "Characters escaped in HTML mode",
   102  			cfg: config.TelegramConfig{
   103  				ParseMode:  "HTML",
   104  				Message:    "<code>x < y</code>",
   105  				HTTPConfig: &commoncfg.HTTPClientConfig{},
   106  			},
   107  			expText: "<code>x &lt; y</code>",
   108  		},
   109  	} {
   110  		t.Run(tc.name, func(t *testing.T) {
   111  			var out []byte
   112  			srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   113  				var err error
   114  				out, err = io.ReadAll(r.Body)
   115  				require.NoError(t, err)
   116  				w.Write([]byte(`{"ok":true,"result":{"chat":{}}}`))
   117  			}))
   118  			defer srv.Close()
   119  			u, _ := url.Parse(srv.URL)
   120  
   121  			tc.cfg.APIUrl = &config.URL{URL: u}
   122  
   123  			notifier, err := New(&tc.cfg, test.CreateTmpl(t), log.NewNopLogger())
   124  			require.NoError(t, err)
   125  
   126  			ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
   127  			defer cancel()
   128  			ctx = notify.WithGroupKey(ctx, "1")
   129  
   130  			retry, err := notifier.Notify(ctx, []*types.Alert{
   131  				{
   132  					Alert: model.Alert{
   133  						Labels: model.LabelSet{
   134  							"lbl1": "val1",
   135  							"lbl3": "val3",
   136  						},
   137  						StartsAt: time.Now(),
   138  						EndsAt:   time.Now().Add(time.Hour),
   139  					},
   140  				},
   141  			}...)
   142  
   143  			require.False(t, retry)
   144  			require.NoError(t, err)
   145  
   146  			req := map[string]string{}
   147  			err = json.Unmarshal(out, &req)
   148  			require.NoError(t, err)
   149  			require.Equal(t, tc.expText, req["text"])
   150  		})
   151  	}
   152  }
   153  

View as plain text