Merge pull request #37 from pavanGorti/add-mastodon-tests

chore(tests): add tests for mastodon service
pull/43/head
Khaliq 4 years ago committed by GitHub
commit 65daa77273
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -19,6 +19,20 @@ type Mastodon struct {
Message string
}
// HTTPClient interface
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
var Client HTTPClient
func initialize() {
// create a new http client
Client = &http.Client{
Timeout: 10 * time.Second,
}
}
// Send parse values from *cli.context and return *cli.Command
// and sets a status message for mastodon.
func Send() *cli.Command {
@ -62,6 +76,7 @@ func Send() *cli.Command {
},
},
Action: func(ctx *cli.Context) error {
initialize()
endPointURL := "https://" + mastodonOpts.ServerURL + "/api/v1/statuses/"
// Create a Bearer string by appending string access token
@ -98,9 +113,8 @@ func sendMastodon(url string, token string, msg string) 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)
// send request to server
resp, err := Client.Do(req)
if err != nil {
return err
}

@ -0,0 +1,81 @@
package mastodon
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
const url, token = "server-url", "token"
// MockClient is the mock client
type MockClient struct {
MockDo func(req *http.Request) (*http.Response, error)
}
// Do function implements HTTPClient
func (m *MockClient) Do(req *http.Request) (*http.Response, error) {
return m.MockDo(req)
}
func TestSendMessage_Success(t *testing.T) {
successResponse, _ := json.Marshal(map[string]interface{}{
"success": true,
})
r := ioutil.NopCloser(bytes.NewReader(successResponse))
Client = &MockClient{
MockDo: func(req *http.Request) (*http.Response, error) {
assert.Equal(t, url, req.URL.Path)
assert.Equal(t, token, req.Header.Get("Authorization"))
return &http.Response{
StatusCode: 200,
Body: r,
}, nil
},
}
m := Mastodon{
ServerURL: url,
Token: token,
Message: "message",
}
err := sendMastodon(m.ServerURL, m.Token, m.Message)
assert.Nil(t, err)
}
func TestSendMessage_Failure(t *testing.T) {
successResponse, _ := json.Marshal(map[string]interface{}{
"error": true,
})
r := ioutil.NopCloser(bytes.NewReader(successResponse))
Client = &MockClient{
MockDo: func(req *http.Request) (*http.Response, error) {
assert.Equal(t, url, req.URL.Path)
assert.Equal(t, token, req.Header.Get("Authorization"))
return &http.Response{
StatusCode: 400,
Body: r,
}, nil
},
}
m := Mastodon{
ServerURL: url,
Token: token,
Message: "message",
}
err := sendMastodon(m.ServerURL, m.Token, m.Message)
assert.NotNil(t, err)
}
Loading…
Cancel
Save