-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_test.go
115 lines (91 loc) · 2.43 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
112
113
114
115
package healthcheck
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestClient_DiskUsage(t *testing.T) {
var (
ctx = context.Background()
httpClient = &http.Client{}
)
const host = "http://10.1.1.1"
t.Run("happy path", func(t *testing.T) {
client := NewClient(httpClient)
require.NotNil(t, client.httpDo)
want := []DiskUsageResponse{
{
Dir: "/test",
AllBytes: 100,
FreeBytes: 10,
},
}
client.httpDo = func(req *http.Request) (*http.Response, error) {
require.Equal(t, "http://10.1.1.1:1251/disk", req.URL.String())
require.Equal(t, "GET", req.Method)
b, err := json.Marshal(want)
if err != nil {
panic(err)
}
return &http.Response{Body: io.NopCloser(bytes.NewReader(b))}, nil
}
got, err := client.DiskUsage(ctx, host)
require.NoError(t, err)
require.Equal(t, want, got)
})
t.Run("request error", func(t *testing.T) {
client := NewClient(httpClient)
client.httpDo = func(req *http.Request) (*http.Response, error) {
return nil, errors.New("boom")
}
_, err := client.DiskUsage(ctx, host)
require.Error(t, err)
require.EqualError(t, err, "http do: boom")
})
t.Run("error in response", func(t *testing.T) {
client := NewClient(httpClient)
stub := []DiskUsageResponse{
{Error: "something bad happened"},
}
client.httpDo = func(req *http.Request) (*http.Response, error) {
b, err := json.Marshal(stub)
if err != nil {
panic(err)
}
return &http.Response{
Body: io.NopCloser(bytes.NewReader(b)),
}, nil
}
_, err := client.DiskUsage(ctx, host)
require.Error(t, err)
require.EqualError(t, err, "no disk usage data")
})
t.Run("invalid JSON", func(t *testing.T) {
client := NewClient(httpClient)
client.httpDo = func(req *http.Request) (*http.Response, error) {
return &http.Response{
Body: io.NopCloser(strings.NewReader("{")),
}, nil
}
_, err := client.DiskUsage(ctx, host)
require.Error(t, err)
require.EqualError(t, err, "malformed json: unexpected EOF")
})
t.Run("zero values", func(t *testing.T) {
client := NewClient(httpClient)
client.httpDo = func(req *http.Request) (*http.Response, error) {
return &http.Response{
Body: io.NopCloser(strings.NewReader(`[]`)),
}, nil
}
_, err := client.DiskUsage(ctx, host)
require.Error(t, err)
require.EqualError(t, err, "no disk usage data")
})
}