-
Notifications
You must be signed in to change notification settings - Fork 81
/
client_test.go
428 lines (347 loc) · 11.4 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
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
package linodego
import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/jarcoal/httpmock"
"github.com/linode/linodego/internal/testutil"
)
func TestClient_SetAPIVersion(t *testing.T) {
defaultURL := "https://api.linode.com/v4"
baseURL := "api.very.cool.com"
apiVersion := "v4beta"
expectedHost := fmt.Sprintf("https://%s/%s", baseURL, apiVersion)
updatedBaseURL := "api.more.cool.com"
updatedAPIVersion := "v4beta_changed"
updatedExpectedHost := fmt.Sprintf("https://%s/%s", updatedBaseURL, updatedAPIVersion)
protocolBaseURL := "http://api.more.cool.com"
protocolAPIVersion := "v4_http"
protocolExpectedHost := fmt.Sprintf("%s/%s", protocolBaseURL, protocolAPIVersion)
client := NewClient(nil)
if client.resty.BaseURL != defaultURL {
t.Fatal(cmp.Diff(client.resty.BaseURL, defaultURL))
}
client.SetBaseURL(baseURL)
client.SetAPIVersion(apiVersion)
if client.resty.BaseURL != expectedHost {
t.Fatal(cmp.Diff(client.resty.BaseURL, expectedHost))
}
// Ensure setting twice does not cause conflicts
client.SetBaseURL(updatedBaseURL)
client.SetAPIVersion(updatedAPIVersion)
if client.resty.BaseURL != updatedExpectedHost {
t.Fatal(cmp.Diff(client.resty.BaseURL, updatedExpectedHost))
}
// Revert
client.SetBaseURL(baseURL)
client.SetAPIVersion(apiVersion)
if client.resty.BaseURL != expectedHost {
t.Fatal(cmp.Diff(client.resty.BaseURL, expectedHost))
}
// Custom protocol
client.SetBaseURL(protocolBaseURL)
client.SetAPIVersion(protocolAPIVersion)
if client.resty.BaseURL != protocolExpectedHost {
t.Fatal(cmp.Diff(client.resty.BaseURL, expectedHost))
}
}
func TestClient_NewFromEnv(t *testing.T) {
file := createTestConfig(t, configNewFromEnv)
// This is cool
t.Setenv(APIEnvVar, "")
t.Setenv(APIConfigEnvVar, file.Name())
t.Setenv(APIConfigProfileEnvVar, "cool")
client, err := NewClientFromEnv(nil)
if err != nil {
t.Fatal(err)
}
if client.selectedProfile != "cool" {
t.Fatalf("mismatched profile: %s != %s", client.selectedProfile, "cool")
}
if client.loadedProfile != "" {
t.Fatal("expected empty loaded profile")
}
if err := client.UseProfile("cool"); err != nil {
t.Fatal(err)
}
if client.loadedProfile != "cool" {
t.Fatal("expected cool as loaded profile")
}
}
func TestClient_NewFromEnvToken(t *testing.T) {
t.Setenv(APIEnvVar, "blah")
client, err := NewClientFromEnv(nil)
if err != nil {
t.Fatal(err)
}
if client.resty.Header.Get("Authorization") != "Bearer blah" {
t.Fatal("token not found in auth header: blah")
}
}
func TestClient_UseURL(t *testing.T) {
client := NewClient(nil)
if _, err := client.UseURL("https://api.test1.linode.com/"); err != nil {
t.Fatal(err)
}
if client.baseURL != "api.test1.linode.com" {
t.Fatalf("mismatched base url: %s", client.baseURL)
}
if client.apiVersion != "v4" {
t.Fatalf("mismatched api version: %s", client.apiVersion)
}
if _, err := client.UseURL("https://api.test2.linode.com/v4beta"); err != nil {
t.Fatal(err)
}
if client.baseURL != "api.test2.linode.com" {
t.Fatalf("mismatched base url: %s", client.baseURL)
}
if client.apiVersion != "v4beta" {
t.Fatalf("mismatched api version: %s", client.apiVersion)
}
}
const configNewFromEnv = `
[default]
api_url = api.cool.linode.com
api_version = v4beta
[cool]
token = blah
`
func TestDebugLogSanitization(t *testing.T) {
type instanceResponse struct {
ID int `json:"id"`
Region string `json:"region"`
Label string `json:"label"`
}
testResp := instanceResponse{
ID: 100,
Region: "test-central",
Label: "this-is-a-test-linode",
}
var lgr bytes.Buffer
plainTextToken := "NOTANAPIKEY"
mockClient := testutil.CreateMockClient(t, NewClient)
logger := testutil.CreateLogger()
mockClient.SetLogger(logger)
logger.L.SetOutput(&lgr)
mockClient.SetDebug(true)
if !mockClient.resty.Debug {
t.Fatal("debug should be enabled")
}
mockClient.SetHeader("Authorization", fmt.Sprintf("Bearer %s", plainTextToken))
if mockClient.resty.Header.Get("Authorization") != fmt.Sprintf("Bearer %s", plainTextToken) {
t.Fatal("token not found in auth header")
}
httpmock.RegisterRegexpResponder("GET", testutil.MockRequestURL("/linode/instances"),
httpmock.NewJsonResponderOrPanic(200, &testResp))
result, err := doGETRequest[instanceResponse](
context.Background(),
mockClient,
"/linode/instances",
)
if err != nil {
t.Fatal(err)
}
logInfo := lgr.String()
if !strings.Contains(logInfo, "Bearer *******************************") {
t.Fatal("sanitized bearer token was expected")
}
if !reflect.DeepEqual(*result, testResp) {
t.Fatalf("actual response does not equal desired response: %s", cmp.Diff(result, testResponse))
}
}
func TestDoRequest_Success(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"message":"success"}`))
}
server := httptest.NewServer(http.HandlerFunc(handler))
defer server.Close()
client := &httpClient{
httpClient: server.Client(),
}
params := RequestParams{
Response: &map[string]string{},
}
err := client.doRequest(context.Background(), http.MethodGet, server.URL, params)
if err != nil {
t.Fatal(cmp.Diff(nil, err))
}
expected := "success"
actual := (*params.Response.(*map[string]string))["message"]
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("response mismatch (-expected +actual):\n%s", diff)
}
}
func TestDoRequest_FailedEncodeBody(t *testing.T) {
client := &httpClient{
httpClient: http.DefaultClient,
}
params := RequestParams{
Body: map[string]interface{}{
"invalid": func() {},
},
}
err := client.doRequest(context.Background(), http.MethodPost, "http://example.com", params)
expectedErr := "failed to encode body"
if err == nil || !strings.Contains(err.Error(), expectedErr) {
t.Fatalf("expected error %q, got: %v", expectedErr, err)
}
}
func TestDoRequest_FailedCreateRequest(t *testing.T) {
client := &httpClient{
httpClient: http.DefaultClient,
}
// Create a request with an invalid URL to simulate a request creation failure
err := client.doRequest(context.Background(), http.MethodGet, "http://invalid url", RequestParams{})
expectedErr := "failed to create request"
if err == nil || !strings.Contains(err.Error(), expectedErr) {
t.Fatalf("expected error %q, got: %v", expectedErr, err)
}
}
func TestDoRequest_Non2xxStatusCode(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "error", http.StatusInternalServerError)
}
server := httptest.NewServer(http.HandlerFunc(handler))
defer server.Close()
client := &httpClient{
httpClient: server.Client(),
}
err := client.doRequest(context.Background(), http.MethodGet, server.URL, RequestParams{})
if err == nil {
t.Fatal("expected error, got nil")
}
httpError, ok := err.(Error)
if !ok {
t.Fatalf("expected error to be of type Error, got %T", err)
}
if httpError.Code != http.StatusInternalServerError {
t.Fatalf("expected status code %d, got %d", http.StatusInternalServerError, httpError.Code)
}
if !strings.Contains(httpError.Message, "error") {
t.Fatalf("expected error message to contain %q, got %v", "error", httpError.Message)
}
}
func TestDoRequest_FailedDecodeResponse(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`invalid json`))
}
server := httptest.NewServer(http.HandlerFunc(handler))
defer server.Close()
client := &httpClient{
httpClient: server.Client(),
}
params := RequestParams{
Response: &map[string]string{},
}
err := client.doRequest(context.Background(), http.MethodGet, server.URL, params)
expectedErr := "failed to decode response"
if err == nil || !strings.Contains(err.Error(), expectedErr) {
t.Fatalf("expected error %q, got: %v", expectedErr, err)
}
}
func TestDoRequest_MutatorError(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"message":"success"}`))
}
server := httptest.NewServer(http.HandlerFunc(handler))
defer server.Close()
client := &httpClient{
httpClient: server.Client(),
}
mutator := func(req *http.Request) error {
return errors.New("mutator error")
}
err := client.doRequest(context.Background(), http.MethodGet, server.URL, RequestParams{}, mutator)
expectedErr := "failed to mutate request"
if err == nil || !strings.Contains(err.Error(), expectedErr) {
t.Fatalf("expected error %q, got: %v", expectedErr, err)
}
}
func TestDoRequestLogging_Success(t *testing.T) {
var logBuffer bytes.Buffer
logger := createLogger()
logger.l.SetOutput(&logBuffer) // Redirect log output to buffer
client := &httpClient{
httpClient: http.DefaultClient,
debug: true,
logger: logger,
}
handler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"message":"success"}`))
}
server := httptest.NewServer(http.HandlerFunc(handler))
defer server.Close()
params := RequestParams{
Response: &map[string]string{},
}
err := client.doRequest(context.Background(), http.MethodGet, server.URL, params)
if err != nil {
t.Fatal(cmp.Diff(nil, err))
}
logInfo := logBuffer.String()
logInfoWithoutTimestamps := removeTimestamps(logInfo)
// Expected logs with templates filled in
expectedRequestLog := "DEBUG RESTY Sending request:\nMethod: GET\nURL: " + server.URL + "\nHeaders: map[Accept:[application/json] Content-Type:[application/json]]\nBody: "
expectedResponseLog := "DEBUG RESTY Received response:\nStatus: 200 OK\nHeaders: map[Content-Length:[21] Content-Type:[text/plain; charset=utf-8]]\nBody: {\"message\":\"success\"}"
if !strings.Contains(logInfo, expectedRequestLog) {
t.Fatalf("expected log %q not found in logs", expectedRequestLog)
}
if !strings.Contains(logInfoWithoutTimestamps, expectedResponseLog) {
t.Fatalf("expected log %q not found in logs", expectedResponseLog)
}
}
func TestDoRequestLogging_Error(t *testing.T) {
var logBuffer bytes.Buffer
logger := createLogger()
logger.l.SetOutput(&logBuffer) // Redirect log output to buffer
client := &httpClient{
httpClient: http.DefaultClient,
debug: true,
logger: logger,
}
params := RequestParams{
Body: map[string]interface{}{
"invalid": func() {},
},
}
err := client.doRequest(context.Background(), http.MethodPost, "http://example.com", params)
expectedErr := "failed to encode body"
if err == nil || !strings.Contains(err.Error(), expectedErr) {
t.Fatalf("expected error %q, got: %v", expectedErr, err)
}
logInfo := logBuffer.String()
expectedLog := "ERROR RESTY failed to encode body"
if !strings.Contains(logInfo, expectedLog) {
t.Fatalf("expected log %q not found in logs", expectedLog)
}
}
func removeTimestamps(log string) string {
lines := strings.Split(log, "\n")
var filteredLines []string
for _, line := range lines {
// Find the index of the "Date:" substring
if index := strings.Index(line, "Date:"); index != -1 {
// Cut off everything after "Date:"
trimmedLine := strings.TrimSpace(line[:index])
filteredLines = append(filteredLines, trimmedLine+"]")
} else {
filteredLines = append(filteredLines, line)
}
}
return strings.Join(filteredLines, "\n")
}