Merge pull request #35 from puneeth8994/mattermost-tests

Adds mattermost tests
pull/36/head
Khaliq 4 years ago committed by GitHub
commit 14f5a03201
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -49,6 +49,21 @@ type matterMostResponse struct {
Metadata struct{} `json:"metadata"`
}
// HTTPClient interface
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
var (
Client HTTPClient
)
func initialize() {
Client = &http.Client{
Timeout: 10 * time.Second,
}
}
// Send parse values from *cli.context and return *cli.Command
// and send messages to target channels.
// If multiple channel ids are provided then the string is split with "," separator and
@ -118,6 +133,7 @@ You can specify multiple channels by separating the value with ','.`,
},
},
Action: func(ctx *cli.Context) error {
initialize()
endPointURL := mattermostOpts.Scheme + "://" + mattermostOpts.ServerURL + mattermostOpts.APIURL
// Create a Bearer string by appending string access token
@ -173,9 +189,7 @@ func sendMattermost(url string, token string, jsonPayload []byte) error {
req.Header.Set("Authorization", token)
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
// create a new http client and send request to server
c := &http.Client{Timeout: 10 * time.Second}
resp, err := c.Do(req)
resp, err := Client.Do(req)
if err != nil {
return err
}

@ -0,0 +1,73 @@
package mattermost
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
// MockDoType
type MockDoType func(req *http.Request) (*http.Response, error)
// MockClient is the mock client
type MockClient struct {
MockDo MockDoType
}
// Overriding what the Do function should "do" in our MockClient
func (m *MockClient) Do(req *http.Request) (*http.Response, error) {
return m.MockDo(req)
}
func TestSendMessage_Success(t *testing.T) {
// build our response JSON
successResponse, _ := json.Marshal(matterMostResponse{
ID: "1",
Message: "Success",
})
// create a new reader with that JSON
r := ioutil.NopCloser(bytes.NewReader(successResponse))
Client = &MockClient{
MockDo: func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
Body: r,
}, nil
},
}
mattermostOpts := matterMost{
Title: "title",
Token: "token",
ServerURL: "url",
Scheme: "https",
APIURL: "api-url",
Message: "hello",
ChanIDs: "1",
}
endPointURL := mattermostOpts.Scheme + "://" + mattermostOpts.ServerURL + mattermostOpts.APIURL
// Create a Bearer string by appending string access token
bearer := "Bearer " + mattermostOpts.Token
fullMessage := mattermostOpts.Title + "\n" + mattermostOpts.Message
ids := strings.Split(mattermostOpts.ChanIDs, ",")
for _, v := range ids {
assert.Equal(t, 1, len(v))
jsonData, err := toJSON(v, fullMessage)
assert.Nil(t, err)
err = sendMattermost(endPointURL, bearer, jsonData)
assert.Nil(t, err)
}
}
Loading…
Cancel
Save