This repository has been archived on 2023-04-18. You can view files and clone it, but cannot push or open issues or pull requests.
notificationarr/internal/service/ntfy_test.go

99 lines
2.3 KiB
Go

package service_test
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"gitea.dwysokinski.me/Kichiyaki/notificationarr/internal/domain"
"gitea.dwysokinski.me/Kichiyaki/notificationarr/internal/service"
"github.com/stretchr/testify/assert"
)
func TestNtfy_Publish(t *testing.T) {
t.Parallel()
t.Run("OK", func(t *testing.T) {
tests := []struct {
name string
topic string
title string
message string
username string
password string
}{
{
name: "without authorization",
topic: "topicc",
title: "title",
message: "msg",
username: "",
password: "",
},
{
name: "with authorization",
topic: "topicc",
title: "title",
message: "msg",
username: "uname",
password: "pwd",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path[1:] != tt.topic {
w.WriteHeader(http.StatusNotFound)
return
}
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if r.Header.Get("Title") != tt.title {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte("invalid title"))
return
}
if uname, pwd, _ := r.BasicAuth(); uname != tt.username || pwd != tt.password {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte("invalid username or password"))
return
}
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
err := service.NewNtfy(srv.Client(), srv.URL, tt.topic, tt.username, tt.password).
Publish(context.Background(), tt.title, tt.message)
assert.NoError(t, err)
})
}
})
t.Run("ERR: status code != 200", func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotImplemented)
}))
defer srv.Close()
err := service.NewNtfy(srv.Client(), srv.URL, "topic", "", "").
Publish(context.Background(), "title", "msg")
assert.ErrorIs(t, err, domain.NewError(
domain.WithCode(domain.ErrorCodeIO),
domain.WithMessagef("ntfy returned unexpected status code: %d", http.StatusNotImplemented),
))
})
}