Add test for telegram notifier

This test will make sure we're properly escaping the message and
constructing the URL correctly.

Signed-off-by: Max Jonas Werner <max.werner@associmates.eu>
This commit is contained in:
Max Jonas Werner 2024-06-20 19:37:32 +02:00
parent 0f8ff3c0d8
commit e70166d5e3
No known key found for this signature in database
GPG Key ID: EB525E0F02B52140
2 changed files with 57 additions and 1 deletions

View File

@ -13,6 +13,7 @@ import (
type Telegram struct {
Channel string
Token string
send func(url string, message string) error // this allows the send function to be overridden for testing
}
func NewTelegram(channel, token string) (*Telegram, error) {
@ -23,6 +24,7 @@ func NewTelegram(channel, token string) (*Telegram, error) {
return &Telegram{
Channel: channel,
Token: token,
send: shoutrrr.Send,
}, nil
}
@ -45,7 +47,7 @@ func (t *Telegram) Post(ctx context.Context, event eventv1.Event) error {
}
message := fmt.Sprintf("*%s*\n%s\n%s", escapeString(heading), escapeString(event.Message), metadata)
url := fmt.Sprintf("telegram://%s@telegram?channels=%s&parseMode=markDownv2", t.Token, t.Channel)
err := shoutrrr.Send(url, message)
err := t.send(url, message)
return err
}

View File

@ -0,0 +1,54 @@
/*
Copyright 2024 The Flux authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package notifier
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestTelegram_Post(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, err := io.ReadAll(r.Body)
require.NoError(t, err)
var payload = WebexPayload{}
err = json.Unmarshal(b, &payload)
require.NoError(t, err)
}))
defer ts.Close()
telegram, err := NewTelegram("channel", "token")
require.NoError(t, err)
telegram.send = func(url, message string) error {
require.Equal(t, "telegram://token@telegram?channels=channel&parseMode=markDownv2", url)
require.Equal(t, "*💫 gitrepository/webapp/gitops\\-system*\nmessage\n\\- *test*: metadata\n\\- *kubernetes\\.io/somekey*: some\\.value\n", message)
return nil
}
ev := testEvent()
ev.Metadata["kubernetes.io/somekey"] = "some.value"
err = telegram.Post(context.TODO(), ev)
require.NoError(t, err)
}