-
Notifications
You must be signed in to change notification settings - Fork 42
/
client_test.go
111 lines (86 loc) · 2.42 KB
/
client_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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package testrail
import (
"bytes"
"io/ioutil"
"net/http"
"testing"
)
// NewTestClient returns a mocked http.Client
func NewTestClient(replyResp *http.Response, err error) *http.Client {
client := &http.Client{}
client.Transport = &MockTransport{
resp: replyResp,
err: err,
}
return client
}
type MockTransport struct {
req *http.Request
resp *http.Response
err error
}
func (b *MockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
b.req = req
return b.resp, b.err
}
func newResponse(body string) *http.Response {
return &http.Response{Body: ioutil.NopCloser(bytes.NewBuffer([]byte(body)))}
}
// TestSendRequest tests all the client functionalities
func TestSendRequest(t *testing.T) {
testClient(t)
c := NewCustomClient("http://example.com", "testUsername", "testPassword", NewTestClient(newResponse(`{ "status_id": 1 }`), nil))
testValidGetRequest(t, c)
testInvalidGetRequest(t, c)
testValidPostRequest(t, c)
}
// testClient tests the NewClient method
func testClient(t *testing.T) {
c1 := NewClient("http://example.com", "testUsername", "testPassword")
if c1.url != "http://example.com/index.php?/api/v2/" {
t.Fatal("Expected valid url but got ", c1.url)
}
c2 := NewClient("http://example.com/", "testUsername", "testPassword")
if c2.url != "http://example.com/index.php?/api/v2/" {
t.Fatal("Expected valid url but got ", c2.url)
}
if c2.useBetaApi {
t.Fatal("Expected useBetaApi ´false´ but got ", c2.useBetaApi)
}
c3 := NewClient("http://example.com/", "testUsername", "testPassword", true)
if !c3.useBetaApi {
t.Fatal("Expected useBetaApi ´true´ but got ", c2.useBetaApi)
}
}
// testValidGetRequest tests the sendRequest method for a GET
func testValidGetRequest(t *testing.T, c *Client) {
var v struct {
StatusID int `json:"status_id"`
}
err := c.sendRequest("GET", "test", nil, &v)
if err != nil {
t.Fatal("Expected no error but got ", err)
}
if v.StatusID != 1 {
t.Fatal("Expected StatusID to be 1, was ", v.StatusID)
}
}
func testValidPostRequest(t *testing.T, c *Client) {
var v struct {
Title string `json:"title"`
}
v.Title = "test"
err := c.sendRequest("POST", "test", v, nil)
if err != nil {
t.Fatal("Expected no error but got ", err)
}
}
func testInvalidGetRequest(t *testing.T, c *Client) {
var v struct {
Status int `json:"status"`
}
err := c.sendRequest("GET", "test", nil, &v)
if err == nil {
t.Fatal("Expected error but got none")
}
}