gmon/alert/gotifyClient_test.go

66 lines
1.5 KiB
Go
Raw Permalink Normal View History

2020-11-02 15:41:02 +01:00
package alert
import (
"bytes"
"io/ioutil"
"net/http"
"testing"
2020-11-05 13:42:36 +01:00
"github.com/stretchr/testify/require"
2020-11-02 15:41:02 +01:00
)
type mockHTTPClient struct {
response string
statusCode int
req http.Request
}
func (mhc *mockHTTPClient) Do(req *http.Request) (*http.Response, error) {
mhc.req = *req
response := http.Response{
Body: ioutil.NopCloser(bytes.NewBufferString(mhc.response)),
StatusCode: mhc.statusCode,
}
return &response, nil
}
func getMockClientWithValidResponse() mockHTTPClient {
2020-11-05 13:42:36 +01:00
responseJSON := ""
2020-11-02 15:41:02 +01:00
return mockHTTPClient{response: responseJSON, statusCode: 200}
}
func TestGotifyClientRequestBuilding(t *testing.T) {
2020-11-02 15:41:02 +01:00
data := Data{
Title: "title",
Message: "message",
Priority: 0,
2020-11-02 15:41:02 +01:00
}
t.Run("should build url with the token as header", func(t *testing.T) {
mockClient := getMockClientWithValidResponse()
token := "xxx"
simpleClient := NewGotifyClient(token, "https://example.com")
2020-11-02 15:41:02 +01:00
simpleClient = simpleClient.WithHTTPClient(&mockClient)
err := simpleClient.Notify(data)
require.Nil(t, err)
2020-11-02 15:41:02 +01:00
require.Equal(t, token, mockClient.req.Header.Get("X-Gotify-Key"))
2020-11-02 15:41:02 +01:00
})
t.Run("should return error if url could not be parse", func(t *testing.T) {
mockClient := &mockHTTPClient{}
token := "xxx"
simpleClient := NewGotifyClient(token, " https:")
2020-11-02 15:41:02 +01:00
simpleClient = simpleClient.WithHTTPClient(mockClient)
err := simpleClient.Notify(data)
require.NotNil(t, err)
2020-11-02 15:41:02 +01:00
2020-11-05 13:42:36 +01:00
want := "parse \" https:\": first path segment in URL cannot contain colon"
2020-11-02 15:41:02 +01:00
require.Equal(t, want, err.Error())
2020-11-02 15:41:02 +01:00
})
}