-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoptions_test.go
262 lines (242 loc) · 8.69 KB
/
options_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
// Copyright 2015-2025 Bleemeo
//
// bleemeo.com an infrastructure monitoring solution in the Cloud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bleemeo
import (
"bufio"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"testing"
"time"
"unsafe"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"golang.org/x/oauth2"
)
const oauthMockResponse = `HTTP/1.1 200 OK
{"access_token": "access", "expires_in": 36000, "token_type":` +
` "Bearer", "scope": "read write", "refresh_token": "refresh"}`
type oauthMockTransport struct{}
func (omt oauthMockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return http.ReadResponse(bufio.NewReader(strings.NewReader(oauthMockResponse)), req) //nolint:wrapcheck
}
func mustParseURL(t *testing.T, s string) *url.URL {
t.Helper()
u, err := url.Parse(s)
if err != nil {
t.Fatalf("Could not parse URL %q: %v", s, err)
}
return u
}
func TestOptions(t *testing.T) {
creds := WithCredentials("u", "")
oauthMockClient := &http.Client{Transport: oauthMockTransport{}}
defaultEndpointURL := mustParseURL(t, defaultEndpoint)
newOAuthTkCb := func(*oauth2.Token) {}
cases := []struct {
name string
env map[string]string
options []ClientOption
expectedError error
expectedClient *Client
}{
{
name: "no options",
expectedError: ErrNoAuthMeanProvided,
},
{
name: "no (optional) options",
options: []ClientOption{creds},
expectedClient: &Client{
username: "u",
endpoint: defaultEndpoint,
oAuthClientID: defaultOAuthClientID,
client: oauthMockClient,
headers: map[string]string{"User-Agent": defaultUserAgent},
throttleMaxAutoRetryDelay: defaultThrottleMaxAutoRetryDelay,
epURL: defaultEndpointURL,
},
},
{
name: "with credentials",
options: []ClientOption{WithCredentials("usr", "pwd")},
expectedClient: &Client{
username: "usr",
password: "pwd",
endpoint: defaultEndpoint,
oAuthClientID: defaultOAuthClientID,
client: oauthMockClient,
headers: map[string]string{"User-Agent": defaultUserAgent},
throttleMaxAutoRetryDelay: defaultThrottleMaxAutoRetryDelay,
epURL: defaultEndpointURL,
},
},
{
name: "with endpoint",
options: []ClientOption{WithEndpoint("http://my-proxy.internal"), creds},
expectedClient: &Client{
username: "u",
endpoint: "http://my-proxy.internal",
oAuthClientID: defaultOAuthClientID,
client: oauthMockClient,
headers: map[string]string{"User-Agent": defaultUserAgent},
throttleMaxAutoRetryDelay: defaultThrottleMaxAutoRetryDelay,
epURL: mustParseURL(t, "http://my-proxy.internal"),
},
},
{
name: "invalid endpoint",
options: []ClientOption{WithEndpoint(":"), creds},
expectedError: fmt.Errorf("invalid endpoint URL: %w", &url.Error{
Op: "parse",
URL: ":",
Err: errors.New("missing protocol scheme"), //nolint:err113
}),
},
{
name: "with OAuth client ID",
options: []ClientOption{WithOAuthClient("123456789", "53CR37"), creds},
expectedClient: &Client{
username: "u",
endpoint: defaultEndpoint,
oAuthClientID: "123456789",
oAuthClientSecret: "53CR37",
client: oauthMockClient,
headers: map[string]string{"User-Agent": defaultUserAgent},
throttleMaxAutoRetryDelay: defaultThrottleMaxAutoRetryDelay,
epURL: defaultEndpointURL,
},
},
{
name: "with Bleemeo account header",
options: []ClientOption{WithBleemeoAccountHeader("eea5c1dd-2edf-47b2-9ef6-7b239e16a5c3"), creds},
expectedClient: &Client{
username: "u",
endpoint: defaultEndpoint,
oAuthClientID: defaultOAuthClientID,
client: oauthMockClient,
headers: map[string]string{
"User-Agent": defaultUserAgent,
"X-Bleemeo-Account": "eea5c1dd-2edf-47b2-9ef6-7b239e16a5c3",
},
throttleMaxAutoRetryDelay: defaultThrottleMaxAutoRetryDelay,
epURL: defaultEndpointURL,
},
},
{
name: "with initial OAuth refresh token",
options: []ClientOption{WithInitialOAuthRefreshToken("initial")},
expectedClient: &Client{
endpoint: defaultEndpoint,
oAuthClientID: defaultOAuthClientID,
oAuthInitialRefresh: "initial",
client: oauthMockClient,
headers: map[string]string{"User-Agent": defaultUserAgent},
throttleMaxAutoRetryDelay: defaultThrottleMaxAutoRetryDelay,
epURL: defaultEndpointURL,
},
},
{
name: "with configuration from environment",
env: map[string]string{
"BLEEMEO_USER": "u",
"BLEEMEO_PASSWORD": "p",
"BLEEMEO_API_URL": "http://my-proxy.internal",
"BLEEMEO_OAUTH_CLIENT_ID": "123456789",
"BLEEMEO_OAUTH_CLIENT_SECRET": "53CR37",
"BLEEMEO_ACCOUNT_ID": "eea5c1dd-2edf-47b2-9ef6-7b239e16a5c3",
"BLEEMEO_OAUTH_INITIAL_REFRESH_TOKEN": "refresh-token",
},
options: []ClientOption{WithConfigurationFromEnv()},
expectedClient: &Client{
username: "u",
password: "p",
endpoint: "http://my-proxy.internal",
oAuthClientID: "123456789",
oAuthClientSecret: "53CR37",
oAuthInitialRefresh: "refresh-token",
client: oauthMockClient,
headers: map[string]string{
"User-Agent": defaultUserAgent,
"X-Bleemeo-Account": "eea5c1dd-2edf-47b2-9ef6-7b239e16a5c3",
},
throttleMaxAutoRetryDelay: defaultThrottleMaxAutoRetryDelay,
epURL: mustParseURL(t, "http://my-proxy.internal"),
},
},
{
name: "with new oAuth token callback",
options: []ClientOption{WithNewOAuthTokenCallback(newOAuthTkCb), creds},
expectedClient: &Client{
username: "u",
endpoint: defaultEndpoint,
oAuthClientID: defaultOAuthClientID,
client: oauthMockClient,
newOAuthTokenCallback: newOAuthTkCb,
headers: map[string]string{"User-Agent": defaultUserAgent},
throttleMaxAutoRetryDelay: defaultThrottleMaxAutoRetryDelay,
epURL: defaultEndpointURL,
},
},
{
name: "with throttle max auto retry delay",
options: []ClientOption{WithThrottleMaxAutoRetryDelay(20 * time.Second), creds},
expectedClient: &Client{
username: "u",
endpoint: defaultEndpoint,
oAuthClientID: defaultOAuthClientID,
client: oauthMockClient,
headers: map[string]string{"User-Agent": defaultUserAgent},
throttleMaxAutoRetryDelay: 20 * time.Second,
epURL: defaultEndpointURL,
},
},
// We can assume that WithHTTPClient() works since it is used in all the above cases.
}
for _, testCase := range cases {
tc := testCase
t.Run(tc.name, func(t *testing.T) {
for k, v := range tc.env {
t.Setenv(k, v)
}
client, err := NewClient(append(tc.options, WithHTTPClient(oauthMockClient))...)
if diff := cmp.Diff(tc.expectedError, err, cmp.Comparer(errorComparer)); diff != "" {
t.Fatalf("Client initialization: unexpected error (-want +got):\n%s", diff)
}
if err != nil {
return
}
cmpOpts := cmp.Options{
cmp.AllowUnexported(Client{}),
cmpopts.IgnoreFields(Client{}, "authProvider", "l"),
cmp.Comparer(tokenCallbackComparer),
}
if diff := cmp.Diff(tc.expectedClient, client, cmpOpts); diff != "" {
t.Fatalf("Unexpected client: (-want +got)\n%s", diff)
}
})
}
}
func errorComparer(x, y error) bool {
return x.Error() == y.Error()
}
func tokenCallbackComparer(x, y func(*oauth2.Token)) bool {
px := *(*unsafe.Pointer)(unsafe.Pointer(&x))
py := *(*unsafe.Pointer)(unsafe.Pointer(&y))
return px == py
}