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
|
|
|
|
2020-11-17 17:23:54 +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}
|
|
|
|
}
|
|
|
|
|
2020-11-05 14:33:01 +01:00
|
|
|
func TestGotifyClientRequestBuilding(t *testing.T) {
|
2020-11-02 15:41:02 +01:00
|
|
|
|
|
|
|
data := Data{
|
|
|
|
Title: "title",
|
|
|
|
Message: "message",
|
2020-11-05 14:21:21 +01:00
|
|
|
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"
|
2020-11-05 14:33:01 +01:00
|
|
|
simpleClient := NewGotifyClient(token, "https://example.com")
|
2020-11-02 15:41:02 +01:00
|
|
|
simpleClient = simpleClient.WithHTTPClient(&mockClient)
|
|
|
|
|
2020-11-05 14:21:21 +01:00
|
|
|
err := simpleClient.Notify(data)
|
2020-11-17 17:23:54 +01:00
|
|
|
require.Nil(t, err)
|
2020-11-02 15:41:02 +01:00
|
|
|
|
2020-11-17 17:23:54 +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"
|
2020-11-05 14:33:01 +01:00
|
|
|
simpleClient := NewGotifyClient(token, " https:")
|
2020-11-02 15:41:02 +01:00
|
|
|
simpleClient = simpleClient.WithHTTPClient(mockClient)
|
|
|
|
|
2020-11-05 14:21:21 +01:00
|
|
|
err := simpleClient.Notify(data)
|
2020-11-17 17:23:54 +01:00
|
|
|
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
|
|
|
|
2020-11-17 17:23:54 +01:00
|
|
|
require.Equal(t, want, err.Error())
|
2020-11-02 15:41:02 +01:00
|
|
|
})
|
|
|
|
}
|