forked from linode/linodego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors_test.go
88 lines (77 loc) · 2.32 KB
/
errors_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
package linodego
import (
"bytes"
"context"
"errors"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/go-resty/resty/v2"
"github.com/google/go-cmp/cmp"
)
func createTestServer(method, route, contentType, body string, statusCode int) (*httptest.Server, *Client) {
h := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if r.Method == method && r.URL.Path == route {
rw.Header().Add("Content-Type", contentType)
rw.WriteHeader(statusCode)
rw.Write([]byte(body))
return
}
rw.WriteHeader(http.StatusNotImplemented)
})
ts := httptest.NewServer(h)
client := NewClient(nil)
client.SetBaseURL(ts.URL)
return ts, &client
}
func TestCoupleAPIErrors_genericHtmlError(t *testing.T) {
rawResponse := `<html>
<head><title>500 Internal Server Error</title></head>
<body bgcolor="white">
<center><h1>500 Internal Server Error</h1></center>
<hr><center>nginx</center>
</body>
</html>`
route := "/v4/linode/instances/123"
ts, client := createTestServer(http.MethodGet, route, "text/html", rawResponse, http.StatusInternalServerError)
client.SetDebug(true)
defer ts.Close()
expectedError := Error{
Code: http.StatusInternalServerError,
Message: "Unexpected Content-Type: Expected: application/json, Received: text/html\nResponse body: " + rawResponse,
}
_, err := coupleAPIErrors(client.R(context.Background()).SetResult(&Instance{}).Get(ts.URL + route))
if diff := cmp.Diff(expectedError, err); diff != "" {
t.Errorf("expected error to match but got diff:\n%s", diff)
}
}
func TestCoupleAPIErrors_badGatewayError(t *testing.T) {
rawResponse := []byte(`<html>
<head><title>502 Bad Gateway</title></head>
<body bgcolor="white">
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx</center>
</body>
</html>`)
buf := ioutil.NopCloser(bytes.NewBuffer(rawResponse))
resp := &resty.Response{
Request: &resty.Request{
Error: errors.New("Bad Gateway"),
},
RawResponse: &http.Response{
Header: http.Header{
"Content-Type": []string{"text/html"},
},
StatusCode: http.StatusBadGateway,
Body: buf,
},
}
expectedError := Error{
Code: http.StatusBadGateway,
Message: http.StatusText(http.StatusBadGateway),
}
if _, err := coupleAPIErrors(resp, nil); !cmp.Equal(err, expectedError) {
t.Errorf("expected error %#v to match error %#v", err, expectedError)
}
}