9
9
"io"
10
10
"net/http"
11
11
"net/http/httptest"
12
- "net/url"
13
12
"os"
14
13
"path/filepath"
15
14
"slices"
@@ -35,16 +34,17 @@ var (
35
34
envLock = & sync.Mutex {}
36
35
)
37
36
38
- func SetEnvVar (t * testing.T , env string , value string ) {
37
+ func setEnvVar (t * testing.T , env string , value string ) {
39
38
t .Helper () // Keep golangci-lint happy
40
39
envLock .Lock ()
41
40
t .Cleanup (envLock .Unlock )
42
41
42
+ originalEnvToken := os .Getenv (env )
43
43
err := os .Setenv (env , value )
44
44
if err != nil {
45
45
t .Errorf ("error setting %v: %v" , env , err )
46
46
}
47
-
47
+ defer os . Setenv ( env , originalEnvToken )
48
48
}
49
49
50
50
// TestGetConfigDirPath tests the GetConfigDirPath function
@@ -73,7 +73,7 @@ func TestGetConfigDirPath(t *testing.T) {
73
73
for _ , tt := range tests {
74
74
t .Run (tt .name , func (t * testing.T ) {
75
75
t .Parallel ()
76
- SetEnvVar (t , "XDG_CONFIG_HOME" , tt .envVar )
76
+ setEnvVar (t , "XDG_CONFIG_HOME" , tt .envVar )
77
77
path , err := util .GetConfigDirPath ()
78
78
if (err != nil ) != tt .expectingError {
79
79
t .Errorf ("expected error: %v, got: %v" , tt .expectingError , err )
@@ -163,13 +163,8 @@ func TestGetGrpcConnection(t *testing.T) {
163
163
for _ , tt := range tests {
164
164
t .Run (tt .name , func (t * testing.T ) {
165
165
t .Parallel ()
166
- originalEnvToken := os .Getenv (util .MinderAuthTokenEnvVar )
167
- err := os .Setenv (util .MinderAuthTokenEnvVar , tt .envToken )
168
- if err != nil {
169
- t .Errorf ("error setting %v: %v" , util .MinderAuthTokenEnvVar , err )
170
- }
171
- // reset this the environment variable when complete.
172
- defer os .Setenv (util .MinderAuthTokenEnvVar , originalEnvToken )
166
+
167
+ setEnvVar (t , util .MinderAuthTokenEnvVar , tt .envToken )
173
168
174
169
conn , err := util .GetGrpcConnection (tt .grpcHost , tt .grpcPort , tt .allowInsecure , tt .issuerUrl , tt .clientId )
175
170
if (err != nil ) != tt .expectedError {
@@ -199,42 +194,31 @@ func TestSaveCredentials(t *testing.T) {
199
194
// Create a temporary directory
200
195
testDir := t .TempDir ()
201
196
202
- SetEnvVar (t , "XDG_CONFIG_HOME" , testDir )
197
+ setEnvVar (t , "XDG_CONFIG_HOME" , testDir )
203
198
204
199
cfgPath := filepath .Join (testDir , "minder" )
205
200
206
201
expectedFilePath := filepath .Join (cfgPath , "credentials.json" )
207
202
208
203
filePath , err := util .SaveCredentials (tokens )
209
- if err != nil {
210
- t .Fatalf ("expected no error, got %v" , err )
211
- }
204
+ require .NoError (t , err )
212
205
213
206
if filePath != expectedFilePath {
214
207
t .Errorf ("expected file path %v, got %v" , expectedFilePath , filePath )
215
208
}
216
209
217
210
// Verify the file content
218
211
credsJSON , err := json .Marshal (tokens )
219
- if err != nil {
220
- t .Fatalf ("error marshaling credentials: %v" , err )
221
- }
212
+ require .NoError (t , err )
222
213
223
- fpath := filepath .Clean (filePath )
224
- content , err := os .ReadFile (fpath )
225
- if err != nil {
226
- t .Fatalf ("error reading file: %v" , err )
227
- }
214
+ cleanPath := filepath .Clean (filePath )
215
+ content , err := os .ReadFile (cleanPath )
216
+ require .NoError (t , err )
228
217
229
218
if string (content ) != string (credsJSON ) {
230
219
t .Errorf ("expected file content %v, got %v" , string (credsJSON ), string (content ))
231
220
}
232
221
233
- // Clean up
234
- err = os .Remove (filePath )
235
- if err != nil {
236
- t .Fatalf ("error removing file: %v" , err )
237
- }
238
222
}
239
223
240
224
// TestRemoveCredentials tests the RemoveCredentials function
@@ -244,7 +228,7 @@ func TestRemoveCredentials(t *testing.T) {
244
228
// Create a temporary directory
245
229
testDir := t .TempDir ()
246
230
247
- SetEnvVar (t , "XDG_CONFIG_HOME" , testDir )
231
+ setEnvVar (t , "XDG_CONFIG_HOME" , testDir )
248
232
xdgConfigHome := os .Getenv ("XDG_CONFIG_HOME" )
249
233
250
234
filePath := filepath .Join (xdgConfigHome , "minder" , "credentials.json" )
@@ -278,7 +262,7 @@ func TestRefreshCredentials(t *testing.T) {
278
262
// Create a temporary directory
279
263
testDir := t .TempDir ()
280
264
281
- SetEnvVar (t , "XDG_CONFIG_HOME" , testDir )
265
+ setEnvVar (t , "XDG_CONFIG_HOME" , testDir )
282
266
tests := []struct {
283
267
name string
284
268
refreshToken string
@@ -291,7 +275,6 @@ func TestRefreshCredentials(t *testing.T) {
291
275
{
292
276
name : "Successful refresh with local server" ,
293
277
refreshToken : "valid_refresh_token" ,
294
- issuerUrl : "http://localhost:8081" ,
295
278
clientId : "minder-cli" ,
296
279
responseBody : `{"access_token":"new_access_token","refresh_token":"new_refresh_token","expires_in":3600}` ,
297
280
expectedResult : util.OpenIdCredentials {
@@ -303,22 +286,19 @@ func TestRefreshCredentials(t *testing.T) {
303
286
{
304
287
name : "Error fetching new credentials (responseBody is missing) rwith local server" ,
305
288
refreshToken : "valid_refresh_token" ,
306
- issuerUrl : "http://localhost:8081" ,
307
289
clientId : "minder-cli" ,
308
290
expectedError : "error unmarshaling credentials: EOF" ,
309
291
},
310
292
{
311
293
name : "Error unmarshaling credentials with local server" ,
312
294
refreshToken : "valid_refresh_token" ,
313
- issuerUrl : "http://localhost:8081" ,
314
295
clientId : "minder-cli" ,
315
296
responseBody : `invalid_json` ,
316
297
expectedError : "error unmarshaling credentials: invalid character 'i' looking for beginning of value" ,
317
298
},
318
299
{
319
300
name : "Error refreshing credentials with local server" ,
320
301
refreshToken : "valid_refresh_token" ,
321
- issuerUrl : "http://localhost:8081" ,
322
302
clientId : "minder-cli" ,
323
303
responseBody : `{"error":"invalid_grant","error_description":"Invalid refresh token"}` ,
324
304
expectedError : "error refreshing credentials: invalid_grant: Invalid refresh token" ,
@@ -335,8 +315,7 @@ func TestRefreshCredentials(t *testing.T) {
335
315
}))
336
316
defer server .Close ()
337
317
338
- parsedURL , _ := url .Parse (server .URL )
339
- tt .issuerUrl = parsedURL .String ()
318
+ tt .issuerUrl = server .URL
340
319
341
320
result , err := util .RefreshCredentials (tt .refreshToken , tt .issuerUrl , tt .clientId )
342
321
if tt .expectedError != "" {
@@ -391,7 +370,7 @@ func TestLoadCredentials(t *testing.T) {
391
370
t .Run (tt .name , func (t * testing.T ) {
392
371
t .Parallel ()
393
372
testDir := t .TempDir ()
394
- SetEnvVar (t , "XDG_CONFIG_HOME" , testDir )
373
+ setEnvVar (t , "XDG_CONFIG_HOME" , testDir )
395
374
// Create the minder directory inside the temp directory
396
375
minderDir := filepath .Join (testDir , "minder" )
397
376
err := os .MkdirAll (minderDir , 0750 )
@@ -403,10 +382,7 @@ func TestLoadCredentials(t *testing.T) {
403
382
404
383
if tt .fileContent != "" {
405
384
// Create a temporary file with the specified content
406
- err := os .WriteFile (filePath , []byte (tt .fileContent ), 0600 )
407
- if err != nil {
408
- t .Fatalf ("failed to write test file: %v" , err )
409
- }
385
+ require .NoError (t , os .WriteFile (filePath , []byte (tt .fileContent ), 0600 ))
410
386
// Print the file path and content for debugging
411
387
t .Logf ("Test %s: written file path %s with content: %s" , tt .name , filePath , tt .fileContent )
412
388
} else {
@@ -433,6 +409,7 @@ func TestLoadCredentials(t *testing.T) {
433
409
}
434
410
}
435
411
412
+ // TestCase struct for holding test case data
436
413
type TestCase struct {
437
414
name string
438
415
token string
@@ -444,18 +421,6 @@ type TestCase struct {
444
421
createServer func (t * testing.T , tt TestCase ) * httptest.Server
445
422
}
446
423
447
- func createTestServer (t * testing.T , tt TestCase ) * httptest.Server {
448
- t .Helper ()
449
- return httptest .NewServer (http .HandlerFunc (func (_ http.ResponseWriter , r * http.Request ) {
450
- err := r .ParseForm ()
451
- require .NoError (t , err , "error parsing form" )
452
-
453
- require .Equal (t , tt .clientId , r .Form .Get ("client_id" ))
454
- require .Equal (t , tt .token , r .Form .Get ("token" ))
455
- require .Equal (t , tt .tokenHint , r .Form .Get ("token_type_hint" ))
456
- }))
457
- }
458
-
459
424
// TestRevokeToken tests the RevokeToken function
460
425
func TestRevokeToken (t * testing.T ) {
461
426
t .Parallel ()
@@ -468,7 +433,16 @@ func TestRevokeToken(t *testing.T) {
468
433
tokenHint : "refresh_token" ,
469
434
expectedPath : "/realms/stacklok/protocol/openid-connect/revoke" ,
470
435
expectError : false ,
471
- createServer : createTestServer ,
436
+ createServer : func (t * testing.T , tt TestCase ) * httptest.Server {
437
+ t .Helper ()
438
+ return httptest .NewServer (http .HandlerFunc (func (_ http.ResponseWriter , r * http.Request ) {
439
+ err := r .ParseForm ()
440
+ require .NoError (t , err , "error parsing form" )
441
+ require .Equal (t , tt .clientId , r .Form .Get ("client_id" ))
442
+ require .Equal (t , tt .token , r .Form .Get ("token" ))
443
+ require .Equal (t , tt .tokenHint , r .Form .Get ("token_type_hint" ))
444
+ }))
445
+ },
472
446
},
473
447
{
474
448
name : "Invalid issuer URL" ,
@@ -499,7 +473,6 @@ func TestRevokeToken(t *testing.T) {
499
473
}
500
474
})
501
475
}
502
-
503
476
}
504
477
505
478
// TestGetJsonFromProto tests the GetJsonFromProto function
@@ -540,8 +513,13 @@ func TestGetJsonFromProto(t *testing.T) {
540
513
t .Errorf ("GetJsonFromProto() error = %v, expectedError %v" , err , tt .expectedError )
541
514
return
542
515
}
543
- if strings .TrimSpace (jsonStr ) != strings .TrimSpace (tt .expectedJson ) {
544
- t .Errorf ("GetJsonFromProto() = %v, expected %v" , jsonStr , tt .expectedJson )
516
+
517
+ // Normalize JSON strings by removing all whitespaces and new lines
518
+ normalizedResult := strings .Join (strings .Fields (jsonStr ), "" )
519
+ normalizedExpected := strings .Join (strings .Fields (tt .expectedJson ), "" )
520
+
521
+ if normalizedResult != normalizedExpected {
522
+ t .Errorf ("GetJsonFromProto() = %v, expected %v" , normalizedResult , normalizedExpected )
545
523
}
546
524
})
547
525
}
@@ -724,7 +702,6 @@ func TestExpandFileArgs(t *testing.T) {
724
702
}) {
725
703
t .Errorf ("ExpandFileArgs() = %v, want %v" , got , tt .expected )
726
704
}
727
- defer os .RemoveAll (testDir )
728
705
})
729
706
}
730
707
}
0 commit comments