Files
uptimesebi/internal/notify/providers_test.go
T
Sebastian UnterschützandClaude Opus 5.5 a0a67ec5f8 feat(notify): chat, push and paging providers
Slack, Discord, Microsoft Teams, Google Chat, Mattermost, Rocket.Chat,
Telegram, Matrix, ntfy, Gotify, Pushover, Pushbullet, Signal (signal-cli
REST API), PagerDuty and Opsgenie natively, and every service Apprise
supports through an Apprise API server. Each provider declares its
settings and how it sends; PagerDuty and Opsgenie pair trigger and
resolve by incident. Requests go through the network guard, and errors
name only the host, since URLs may carry tokens.

Refs #92

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 16:07:24 +01:00

135 lines
6.8 KiB
Go

package notify
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/google/uuid"
)
// recorded is a request a fake service received.
type recorded struct {
Method, Path, Query string
Header http.Header
Body string
}
func fakeService(t *testing.T) (*httptest.Server, func() recorded) {
t.Helper()
var mu sync.Mutex
var last recorded
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
last = recorded{r.Method, r.URL.Path, r.URL.RawQuery, r.Header.Clone(), string(b)}
mu.Unlock()
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(srv.Close)
return srv, func() recorded { mu.Lock(); defer mu.Unlock(); return last }
}
func TestProviders(t *testing.T) {
srv, last := fakeService(t)
pushoverURL, pushbulletURL, pagerdutyURL = srv.URL+"/pushover", srv.URL+"/pushbullet", srv.URL+"/pagerduty"
opsgenieURL = map[string]string{"us": srv.URL + "/opsgenie", "eu": srv.URL + "/opsgenie-eu"}
key := uuid.MustParse("00000000-0000-0000-0000-0000000000aa")
opened := Message{Event: Opened, Title: "Shop is down", Body: "unexpected status 502", URL: "https://uptime.example/monitors/1", Key: key}
resolved := opened
resolved.Event, resolved.Title = Resolved, "Shop is up again"
for _, tc := range []struct {
typ string
cfg map[string]string
msg Message
check func(r recorded) bool
}{
{"slack", map[string]string{"webhook_url": srv.URL + "/slack"}, opened, func(r recorded) bool { return strings.Contains(r.Body, `"text":"Shop is down`) }},
{"discord", map[string]string{"webhook_url": srv.URL + "/discord"}, opened, func(r recorded) bool { return strings.Contains(r.Body, `"content":"Shop is down`) }},
{"teams", map[string]string{"webhook_url": srv.URL + "/teams"}, opened, func(r recorded) bool {
return strings.Contains(r.Body, "application/vnd.microsoft.card.adaptive") && strings.Contains(r.Body, "Action.OpenUrl")
}},
{"telegram", map[string]string{"bot_token": "123:abc", "chat_id": "-100", "thread_id": "7", "api_url": srv.URL}, opened, func(r recorded) bool {
return r.Path == "/bot123:abc/sendMessage" && strings.Contains(r.Body, `"chat_id":"-100"`) && strings.Contains(r.Body, `"message_thread_id":7`)
}},
{"matrix", map[string]string{"homeserver_url": srv.URL, "access_token": "tok", "room_id": "!room:example.org"}, opened, func(r recorded) bool {
return r.Method == http.MethodPut && strings.HasPrefix(r.Path, "/_matrix/client/v3/rooms/!room:example.org/send/m.room.message/") && r.Header.Get("Authorization") == "Bearer tok"
}},
{"ntfy", map[string]string{"server_url": srv.URL, "topic": "ops", "priority": "5", "access_token": "tk"}, opened, func(r recorded) bool {
return r.Path == "/ops" && r.Header.Get("Title") == "Shop is down" && r.Header.Get("Priority") == "5" && r.Header.Get("Click") != ""
}},
{"ntfy", map[string]string{"server_url": srv.URL, "topic": "ops", "priority": "5"}, resolved, func(r recorded) bool { return r.Header.Get("Priority") == "3" }},
{"gotify", map[string]string{"server_url": srv.URL, "app_token": "gk", "priority": "8"}, opened, func(r recorded) bool {
return r.Path == "/message" && r.Header.Get("X-Gotify-Key") == "gk" && strings.Contains(r.Body, `"priority":8`)
}},
{"pushover", map[string]string{"user_key": "u", "app_token": "a", "priority": "1"}, opened, func(r recorded) bool {
return r.Path == "/pushover" && strings.Contains(r.Body, "user=u") && strings.Contains(r.Body, "token=a")
}},
{"pushbullet", map[string]string{"access_token": "pb"}, opened, func(r recorded) bool { return r.Header.Get("Access-Token") == "pb" }},
{"signal", map[string]string{"api_url": srv.URL, "number": "+49", "recipients": "+491, group.abc"}, opened, func(r recorded) bool {
return r.Path == "/v2/send" && strings.Contains(r.Body, `"recipients":["+491","group.abc"]`)
}},
{"pagerduty", map[string]string{"routing_key": "rk", "severity": "critical"}, opened, func(r recorded) bool {
return strings.Contains(r.Body, `"event_action":"trigger"`) && strings.Contains(r.Body, `"dedup_key":"`+key.String()+`"`)
}},
{"pagerduty", map[string]string{"routing_key": "rk"}, resolved, func(r recorded) bool {
return strings.Contains(r.Body, `"event_action":"resolve"`) && !strings.Contains(r.Body, "payload")
}},
{"opsgenie", map[string]string{"api_key": "ok", "region": "eu", "priority": "P1"}, opened, func(r recorded) bool {
return r.Path == "/opsgenie-eu" && r.Header.Get("Authorization") == "GenieKey ok" && strings.Contains(r.Body, `"alias":"`+key.String()+`"`)
}},
{"opsgenie", map[string]string{"api_key": "ok"}, resolved, func(r recorded) bool {
return r.Path == "/opsgenie/"+key.String()+"/close" && r.Query == "identifierType=alias"
}},
{"apprise", map[string]string{"api_url": srv.URL, "urls": "tgram://bot/chat"}, opened, func(r recorded) bool {
return r.Path == "/notify" && strings.Contains(r.Body, `"type":"failure"`) && strings.Contains(r.Body, "tgram://")
}},
{"apprise", map[string]string{"api_url": srv.URL, "config_key": "ops team"}, resolved, func(r recorded) bool {
return r.Path == "/notify/ops team" && strings.Contains(r.Body, `"type":"success"`)
}},
} {
p, ok := Lookup(tc.typ)
if !ok {
t.Fatalf("no provider %s", tc.typ)
}
if err := p.Send(context.Background(), tc.cfg, tc.msg, true); err != nil {
t.Errorf("%s: Send() = %v", tc.typ, err)
continue
}
if r := last(); !tc.check(r) {
t.Errorf("%s: unexpected request %s %s?%s %v %s", tc.typ, r.Method, r.Path, r.Query, r.Header, r.Body)
}
}
}
func TestProviderErrorsQuoteTheService(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
_ = json.NewEncoder(w).Encode(map[string]string{"description": "Unauthorized: invalid token"})
}))
defer srv.Close()
p, _ := Lookup("slack")
err := p.Send(context.Background(), map[string]string{"webhook_url": srv.URL}, Message{Title: "t"}, true)
if err == nil || !strings.Contains(err.Error(), "401") || !strings.Contains(err.Error(), "invalid token") {
t.Errorf("Send() = %v, want the status and the service's reason", err)
}
// Services on private networks are refused unless allowed.
if err := p.Send(context.Background(), map[string]string{"webhook_url": srv.URL}, Message{Title: "t"}, false); err == nil {
t.Error("a private address was reached without permission")
}
}
func TestProviderErrorsHideSecretURLs(t *testing.T) {
p, _ := Lookup("telegram")
err := p.Send(context.Background(), map[string]string{"bot_token": "123:secret", "chat_id": "1", "api_url": "http://127.0.0.1:1"}, Message{Title: "t"}, true)
if err == nil || strings.Contains(err.Error(), "secret") {
t.Errorf("Send() = %v, want an error without the token", err)
}
}