forked from hashicorp/vault-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors_test.go
81 lines (73 loc) · 2.16 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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package vault
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_isResponseError(t *testing.T) {
cases := map[string]struct {
statusCode int
body string
expectedError bool
expectedErrors []string
expectedRawResponseBytes []byte
}{
"non-error": {
statusCode: http.StatusOK,
body: "",
expectedError: false,
},
"response-with-errors": {
statusCode: http.StatusInternalServerError,
body: `{"errors":["error1", "error2"]}`,
expectedError: true,
expectedErrors: []string{"error1", "error2"},
},
"response-with-error": {
statusCode: http.StatusGone,
body: `{"error":"single error"}`,
expectedError: true,
expectedErrors: []string{"single error"},
},
"json-response-without-errors": {
statusCode: http.StatusNotFound,
body: `{"data":{"key1":"value1","key2":"value2"}}`,
expectedError: true,
expectedErrors: nil,
expectedRawResponseBytes: []byte(`{"data":{"key1":"value1","key2":"value2"}}`),
},
"non-json-response": {
statusCode: http.StatusTeapot,
body: `this is just a string`,
expectedError: true,
expectedErrors: nil,
expectedRawResponseBytes: []byte(`this is just a string`),
},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
err := isResponseError(
httptest.NewRequest(http.MethodGet, "http://localhost:8200/v1/foo", nil),
&http.Response{
StatusCode: tc.statusCode,
Body: io.NopCloser(strings.NewReader(tc.body)),
},
)
if !tc.expectedError {
require.Nil(t, err)
return
}
var responseError *ResponseError
require.ErrorAs(t, err, &responseError)
assert.Equal(t, tc.statusCode, responseError.StatusCode)
assert.Equal(t, tc.expectedErrors, responseError.Errors)
assert.Equal(t, tc.expectedRawResponseBytes, responseError.RawResponseBytes)
})
}
}