-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathslack_test.go
84 lines (71 loc) · 2.19 KB
/
slack_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package backend
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"testing"
"time"
)
// TestCreateHTTPClient should test the behaviour of createHTTPClient
func TestCreateHTTPClient(t *testing.T) {
httpClient := createHTTPClient()
if httpClient.Timeout != 5*time.Second {
t.Errorf("http client timeout not set")
}
}
// TestSlackSendMessage tests the slack client behaviour
func TestSlackSendMessage(t *testing.T) {
slackEnabled = true
slackWebHooks = []string{"https://slack.linuxctl.com"}
// replace slackClient to avoid making a real http request
slackClient = NewTestClient(func(req *http.Request) *http.Response {
// Check the request params
if req.Method != "POST" {
t.Errorf("expected POST but sent %v", req.Method)
}
if req.URL.String() != slackWebHooks[0] {
t.Errorf("slack client sent to unexpected endpoint: %v", req.URL.String())
}
if fmt.Sprintf("%s", req.Body) != "{{\"text\":\"test data\"}}" {
t.Errorf("slack client sent unexpected request body: %v", req.Body)
}
// response to slack client
return &http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewBufferString(`ok`)),
// Must be set to non-nil value or it panics
Header: make(http.Header),
}
})
errs := slackSendMessage("test data")
if len(errs) > 0 {
t.Errorf("unexpected errors occured during slack client test: %v", errs)
}
// this time, we respond with a non-200 code
slackClient = NewTestClient(func(req *http.Request) *http.Response {
// respond to slack client with a 500
return &http.Response{
StatusCode: 500,
Body: ioutil.NopCloser(bytes.NewBufferString(`error`)),
// Must be set to non-nil value or it panics
Header: make(http.Header),
}
})
errs = slackSendMessage("test data")
if len(errs) != 1 {
t.Errorf("expected 1 error but got: %v", errs)
}
}
// RoundTripFunc .
type RoundTripFunc func(req *http.Request) *http.Response
// RoundTrip .
func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}
// NewTestClient returns *http.Client with Transport replaced to avoid making real calls
func NewTestClient(fn RoundTripFunc) *http.Client {
return &http.Client{
Transport: RoundTripFunc(fn),
}
}