-
Notifications
You must be signed in to change notification settings - Fork 56
/
govultr_test.go
319 lines (249 loc) · 7.2 KB
/
govultr_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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package govultr
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"reflect"
"strings"
"testing"
"time"
)
var (
mux *http.ServeMux
ctx = context.TODO()
client *Client
server *httptest.Server
)
func setup() {
mux = http.NewServeMux()
server = httptest.NewServer(mux)
client = NewClient(nil)
thisURL, _ := url.Parse(server.URL)
client.BaseURL = thisURL
}
func teardown() {
server.Close()
}
func TestNewClient(t *testing.T) {
setup()
defer teardown()
if client.BaseURL == nil || client.BaseURL.String() != server.URL {
t.Errorf("NewClient BaseURL = %v, expected %v", client.BaseURL, server.URL)
}
if client.UserAgent != userAgent {
t.Errorf("NewClient UserAgent = %v, expected %v", client.UserAgent, userAgent)
}
services := []string{
"Account",
}
copied := reflect.ValueOf(client)
copyValue := reflect.Indirect(copied)
for _, s := range services {
if copyValue.FieldByName(s).IsNil() {
t.Errorf("c.%s shouldn't be nil", s)
}
}
}
func TestClient_DoWithContext(t *testing.T) {
setup()
defer teardown()
type vultr struct {
Bird string
}
mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
if method := http.MethodGet; method != request.Method {
t.Errorf("Request method = %v, expecting %v", request.Method, method)
}
fmt.Fprint(writer, `{"Bird":"vultr"}`)
})
req, _ := client.NewRequest(ctx, http.MethodGet, "/", nil)
data := new(vultr)
_, err := client.DoWithContext(context.Background(), req, data)
if err != nil {
t.Fatalf("DoWithContext(): %v", err)
}
expected := &vultr{"vultr"}
if !reflect.DeepEqual(data, expected) {
t.Errorf("Response body = %v, expected %v", data, expected)
}
}
func TestClient_DoWithContextFailure(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
if method := http.MethodGet; method != request.Method {
t.Errorf("Request method = %v, expecting %v", request.Method, method)
}
writer.WriteHeader(500)
fmt.Fprint(writer, `{Error}`)
})
req, _ := client.NewRequest(ctx, http.MethodGet, "/", nil)
_, err := client.DoWithContext(context.Background(), req, nil)
if !strings.Contains(err.Error(), "gave up after") || !strings.Contains(err.Error(), "last error") {
t.Fatalf("DoWithContext(): %v: expected 'gave up after ..., last error ...'", err)
}
}
type errRoundTripper struct{}
func (errRoundTripper) RoundTrip(*http.Request) (*http.Response, error) {
return nil, errors.New("fake error")
}
func TestClient_DoWithContextError(t *testing.T) {
setup()
defer teardown()
client = NewClient(&http.Client{
Transport: errRoundTripper{},
})
req, _ := client.NewRequest(ctx, http.MethodGet, "/", nil)
var panicked string
func() {
defer func() {
if err := recover(); err != nil {
panicked = fmt.Sprint(err)
}
}()
client.DoWithContext(context.Background(), req, nil)
}()
if panicked != "" {
t.Errorf("unexpected panic: %s", panicked)
}
}
func TestClient_NewRequest(t *testing.T) {
c := NewClient(nil)
in := "/unit"
out := defaultBase + "/unit"
inRequest := RequestBody{"balance": 500}
outRequest := `{"balance":500}` + "\n"
req, _ := c.NewRequest(ctx, http.MethodPost, in, inRequest)
if req.URL.String() != out {
t.Errorf("NewRequest(%v) URL = %v, expected %v", in, req.URL, out)
}
body, _ := io.ReadAll(req.Body)
if string(body) != outRequest {
t.Errorf("NewRequest(%v)Body = %v, expected %v", inRequest, string(body), outRequest)
}
userAgent := req.Header.Get("User-Agent")
if c.UserAgent != userAgent {
t.Errorf("NewRequest() User-Agent = %v, expected %v", userAgent, c.UserAgent)
}
contentType := req.Header.Get("Content-Type")
if contentType != "application/json" {
t.Errorf("NewRequest() Header Content Type = %v, expected %v", contentType, "application/x-www-form-urlencoded")
}
}
func TestClient_SetBaseUrl(t *testing.T) {
setup()
defer teardown()
base := "http://localhost/vultr"
err := client.SetBaseURL(base)
if err != nil {
t.Fatalf("SetBaseUrl unexpected error: %v", err)
}
if client.BaseURL.String() != base {
t.Errorf("NewClient BaseUrl = %v, expected %v", client.BaseURL, base)
}
if err := client.SetBaseURL(":"); err == nil {
t.Error("Expected invalid BaseURL to fail")
}
}
func TestClient_SetUserAgent(t *testing.T) {
setup()
defer teardown()
ua := "vultr/testing"
client.SetUserAgent(ua)
if client.UserAgent != ua {
t.Errorf("NewClient UserAgent = %v, expected %v", client.UserAgent, userAgent)
}
}
func TestClient_SetRateLimit(t *testing.T) {
setup()
defer teardown()
tTime := 600 * time.Millisecond
client.SetRateLimit(tTime)
if client.client.RetryWaitMax != tTime {
t.Errorf("NewClient max RateLimit = %v, expected %v", client.client.RetryWaitMax, tTime)
}
}
func TestClient_OnRequestCompleted(t *testing.T) {
setup()
defer teardown()
var completedReq *http.Request
var completedRes string
type Vultr struct {
Bird string
}
mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
fmt.Fprint(writer, `{"Vultr":"bird"}`)
})
req, _ := client.NewRequest(ctx, http.MethodGet, "/", nil)
data := new(Vultr)
client.OnRequestCompleted(func(request *http.Request, response *http.Response) {
completedReq = req
dump, err := httputil.DumpResponse(response, true)
if err != nil {
t.Errorf("Failed to dump response: %s", err)
}
completedRes = string(dump)
})
_, err := client.DoWithContext(context.Background(), req, data)
if err != nil {
t.Fatalf("Do(): %v", err)
}
if !reflect.DeepEqual(req, completedReq) {
t.Errorf("Completed request = %v, expected %v", completedReq, req)
}
expected := `{"Vultr":"bird"}`
if !strings.Contains(completedRes, expected) {
t.Errorf("expected response to contain %v, Response = %v", expected, completedRes)
}
}
func TestClient_SetRetryLimit(t *testing.T) {
setup()
defer teardown()
client.SetRetryLimit(4)
if client.client.RetryMax != 4 {
t.Errorf("NewClient RateLimit = %v, expected %v", client.client.RetryMax, 4)
}
}
func TestNewRequest_badURI(t *testing.T) {
c := NewClient(nil)
_, err := c.NewRequest(ctx, http.MethodGet, ":/1.", nil)
if err == nil {
t.Error("expected invalid URI to fail")
}
}
func TestNewRequest_badBody(t *testing.T) {
c := NewClient(nil)
_, err := c.NewRequest(ctx, http.MethodGet, "/", make(chan int))
if err == nil {
t.Error("expected invalid Body to fail")
}
}
func TestRequest_InvalidCall(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/wrong", func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusBadRequest)
fmt.Fprint(writer, nil)
})
req, _ := client.NewRequest(ctx, http.MethodGet, "/wrong", nil)
if _, err := client.DoWithContext(ctx, req, nil); err == nil {
t.Error("Expected invalid status code to bad request")
}
}
func TestRequest_InvalidResponseBody(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/wrong", func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusOK)
fmt.Fprint(writer, `{`)
})
req, _ := client.NewRequest(ctx, http.MethodGet, "/wrong", nil)
if _, err := client.DoWithContext(ctx, req, struct{}{}); err == nil {
t.Error("Expected response body to be invalid")
}
}