forked from convox/rack
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client_test.go
94 lines (67 loc) · 1.92 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
package client
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/convox/rack/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testClient(t *testing.T, serverUrl string) *Client {
u, _ := url.Parse(serverUrl)
client := New(u.Host, "test", "test")
require.NotNil(t, client, "client should not be nil")
return client
}
func testServer(t *testing.T, stubs ...test.Http) *httptest.Server {
stubs = append(stubs, test.Http{Method: "GET", Path: "/system", Code: 200, Response: System{
Version: "test",
}})
return test.Server(t, stubs...)
}
type ErrorReader struct {
Error string
}
func (er ErrorReader) Read(buf []byte) (int, error) {
return 0, fmt.Errorf(er.Error)
}
func (er ErrorReader) Close() error {
return nil
}
func TestClientErrorReading(t *testing.T) {
er := ErrorReader{Error: "error reading"}
res := &http.Response{StatusCode: 400, Body: er}
err := responseError(res)
assert.NotNil(t, err, "err is not nil")
assert.Equal(t, "error reading response body: error reading", err.Error(), "err text is valid")
}
func TestClientNonJson(t *testing.T) {
ts := testServer(t,
test.Http{Method: "GET", Path: "/", Code: 503, Response: "not-json"},
)
defer ts.Close()
var err Error
testClient(t, ts.URL).Get("/", &err)
}
func TestClientGetErrors(t *testing.T) {
client := New("", "", "")
err := client.Get("", nil)
assert.NotNil(t, err)
assert.Equal(t, "Get https://: http: no Host in request URL", err.Error())
err = client.Get("/%", nil)
assert.NotNil(t, err)
assert.Equal(t, "parse https:///%: invalid URL escape \"%\"", err.Error())
}
func TestClientGet(t *testing.T) {
ts := testServer(t,
test.Http{Method: "GET", Path: "/", Code: 200, Response: "this is data"},
)
defer ts.Close()
client := testClient(t, ts.URL)
w := bytes.NewBuffer([]byte{})
client.Get("/", w)
assert.Equal(t, "\"this is data\"", w.String())
}