-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient_test.go
82 lines (74 loc) · 1.54 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
package client
import (
"bytes"
"io/ioutil"
"net/http"
"testing"
)
func TestNew(t *testing.T) {
a := New("http://server", "123")
if a.Endpoint != "http://server" {
t.Fail()
}
if a.Key != "123" {
t.Fail()
}
if a.Client == nil {
t.Fail()
}
}
func TestAPINewRequest(t *testing.T) {
a := New("http://server", "123")
req, err := a.NewRequest("GET", "/", nil)
if err != nil {
t.Fail()
}
if req.Method != "GET" {
t.Fail()
}
if req.URL.String() != "http://server/" {
t.Fail()
}
if req.Header.Get("Authorization") != "Bearer 123" {
t.Fail()
}
if req.Header.Get("Content-Type") != "application/json; charset=utf-8" {
t.Fail()
}
payload := []int{1, 2, 3}
req, err = a.NewRequest("GET", "/", payload)
if err != nil {
t.Fail()
}
if body, err := ioutil.ReadAll(req.Body); err != nil || string(body) != "[1,2,3]\n" {
t.Fail()
}
}
type RoundTripFunc func(req *http.Request) *http.Response
func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}
func NewTestClient(f RoundTripFunc) *http.Client {
return &http.Client{
Transport: RoundTripFunc(f),
}
}
func TestAPIDo(t *testing.T) {
a := New("http://server", "123")
req, _ := a.NewRequest("GET", "/", nil)
a.Client = NewTestClient(func(req *http.Request) *http.Response {
return &http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewBufferString(`"OK"`)),
Header: make(http.Header),
}
})
var result string
err := a.Do(req, &result)
if err != nil {
t.Fail()
}
if result != "OK" {
t.Fail()
}
}