Repository navigation
Expand file tree
/
Copy pathclient_test.go
More file actions
81 lines (67 loc) · 1.67 KB
/
Copy pathclient_test.go
File metadata and controls
81 lines (67 loc) · 1.67 KB
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
package api
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewRequestSetsDefaultHeaders(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `ok`)
}))
defer ts.Close()
UserAgent = "BogusAgent"
testCases := []struct {
desc string
client *Client
auth string
contentType string
}{
{
desc: "User defaults",
client: &Client{},
auth: "",
contentType: "application/json",
},
{
desc: "Override defaults",
client: &Client{
Token: "abc123",
APIBaseURL: "http://example.com",
ContentType: "bogus",
},
auth: "Bearer abc123",
contentType: "bogus",
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
req, err := tc.client.NewRequest("GET", ts.URL, nil)
assert.NoError(t, err)
assert.Equal(t, "BogusAgent", req.Header.Get("User-Agent"))
assert.Equal(t, tc.contentType, req.Header.Get("Content-Type"))
assert.Equal(t, tc.auth, req.Header.Get("Authorization"))
})
}
}
func TestDo(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "GET", r.Method)
fmt.Fprint(w, `{"hello": "world"}`)
}))
defer ts.Close()
type payload struct {
Hello string `json:"hello"`
}
client := &Client{}
req, err := client.NewRequest("GET", ts.URL, nil)
assert.NoError(t, err)
res, err := client.Do(req)
assert.NoError(t, err)
var body payload
err = json.NewDecoder(res.Body).Decode(&body)
assert.NoError(t, err)
assert.Equal(t, "world", body.Hello)
}