generated from hashicorp/terraform-provider-scaffolding
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient_test.go
193 lines (185 loc) · 5.39 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
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/hashicorp/go-retryablehttp"
"github.com/stretchr/testify/assert"
"io"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"testing"
"time"
)
var retryCounter int = 0
func TestGetBaseURL(t *testing.T) {
cases := map[string]struct {
C *Credentials
Expected string
}{
"without-realm": {
C: &Credentials{},
Expected: "https://api.access.proofpoint.com",
},
"with-us-realm": {
C: &Credentials{Realm: "us"},
Expected: "https://api.us.access.proofpoint.com",
},
"with-eu-realm": {
C: &Credentials{Realm: "eu"},
Expected: "https://api.eu.access.proofpoint.com",
},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
assert.Equal(t, tc.Expected, getBaseURL(tc.C))
})
}
}
func TestParseHttpError(t *testing.T) {
errorResponse := &ErrorResponse{
"",
"",
"error details",
403,
"title",
"type",
}
endpoint, _ := url.Parse("https://example.com")
bytesRes, _ := json.Marshal(errorResponse)
res := &http.Response{
Body: io.NopCloser(bytes.NewReader(bytesRes)),
Request: &http.Request{
Method: http.MethodPost,
URL: endpoint,
},
}
formattedError := parseHttpError(res)
assert.EqualError(t, formattedError, "POST request to https://example.com failed with status code 403: title - error details")
}
func TestSendRequest(t *testing.T) {
server := configureServer(t)
client := &Client{
HTTP: retryablehttp.NewClient(),
BaseURL: server.URL,
Credentials: &Credentials{},
}
client.HTTP.HTTPClient = &http.Client{
Transport: &http.Transport{MaxIdleConnsPerHost: maxIdleConnections},
Timeout: time.Duration(requestTimeout) * time.Second,
}
req, _ := http.NewRequest(http.MethodGet, server.URL+"/v1/test", nil)
t.Run("check-token-loaded-on-first-request", func(t *testing.T) {
// Asserting token struct is empty before request
assert.Nil(t, client.Token)
_, err := client.SendRequest(req)
assert.Nil(t, err)
// Asserting token struct is not empty after request
assert.NotNil(t, client.Token)
//Asserting token was created for the first time
assert.Equal(t, "token-1", client.Token.Token)
})
t.Run("check-token-reused-before-expiration", func(t *testing.T) {
_, err := client.SendRequest(req)
assert.Nil(t, err)
//Asserting token was created for the second time
assert.Equal(t, "token-1", client.Token.Token)
})
t.Run("check-token-refreshed-on-expiration", func(t *testing.T) {
client.TokenCreationTime = time.Now().Unix() - 60*5
_, err := client.SendRequest(req)
assert.Nil(t, err)
//Asserting token was created for the second time
assert.Equal(t, "token-2", client.Token.Token)
})
t.Run("check-with-timeout-context", func(t *testing.T) {
ctx, _ := context.WithTimeout(context.Background(), time.Second)
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, server.URL+"/v1/context", nil)
resp, err := client.SendRequest(req)
assert.Contains(t, err.Error(), "context deadline exceeded")
assert.Nil(t, resp)
})
}
func TestRetry(t *testing.T) {
server := configureServer(t)
client := &Client{
HTTP: retryablehttp.NewClient(),
BaseURL: server.URL,
Credentials: &Credentials{},
}
client.HTTP.HTTPClient = &http.Client{
Transport: &http.Transport{MaxIdleConnsPerHost: maxIdleConnections},
Timeout: time.Duration(requestTimeout) * time.Second,
}
client.HTTP.CheckRetry = RetryPolicy
client.HTTP.Backoff = func(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
return time.Duration(1)
}
req, _ := http.NewRequest(http.MethodGet, server.URL+"/v1/patch_200", nil)
resp, err := client.SendRequest(req)
assert.Nil(t, err)
assert.Equal(t, 1, retryCounter)
req, _ = http.NewRequest(http.MethodGet, server.URL+"/v1/patch_400", nil)
resp, err = client.SendRequest(req)
assert.Nil(t, resp)
assert.NotNil(t, err)
assert.Equal(t, 2, retryCounter)
req, _ = http.NewRequest(http.MethodGet, server.URL+"/v1/patch_409", nil)
resp, err = client.SendRequest(req)
assert.Nil(t, resp)
assert.NotNil(t, err)
assert.Equal(t, 7, retryCounter)
}
func configureServer(t *testing.T) *httptest.Server {
tokenCounter := 1
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
accessToken := fmt.Sprintf("token-%d", tokenCounter)
switch req.URL.String() {
case "/v1/oauth/token":
tokenCounter++
defer req.Body.Close()
token := &Token{
Token: accessToken,
Expiry: 300,
TokenType: "access token",
}
response, _ := json.Marshal(token)
rw.Write(response)
case "/v1/test":
assert.Regexp(t, regexp.MustCompile("Bearer token-[\\d]"), req.Header.Get("Authorization"))
rw.Write([]byte("ok"))
case "/v1/patch_409":
errorResponse := &ErrorResponse{
Detail: "error details",
Status: 409,
Title: "title",
Type: "type",
}
bytesRes, _ := json.Marshal(errorResponse)
retryCounter++
rw.WriteHeader(http.StatusConflict)
rw.Write(bytesRes)
case "/v1/patch_200":
retryCounter++
rw.Write([]byte("ok"))
case "/v1/patch_400":
errorResponse := &ErrorResponse{
Detail: "error details",
Status: 400,
Title: "title",
Type: "type",
}
bytesRes, _ := json.Marshal(errorResponse)
retryCounter++
rw.WriteHeader(http.StatusBadRequest)
rw.Write(bytesRes)
case "/v1/context":
time.Sleep(time.Minute)
rw.Write([]byte("ok"))
}
}))
return server
}