Skip to content

Commit af6a40c

Browse files
committed
Add additional test coverage for helper functions in Util
Currently helper functions in Util lacks test coverage This commit fixes the following functions by addressing the review feedback. - TestExpandFileArgs: Removed os.RemoveAll(testDir) line - Changed name to setEnvVar and fixed all references - TestGetGrpcConnection: use setEnvVar to set env variable - TestGetJsonFromProto: Normalize json to handle empty space - remved helper function createTestServer Signed-off-by: Kugamoorthy Gajananan <[email protected]>
1 parent 7a03106 commit af6a40c

File tree

1 file changed

+35
-58
lines changed

1 file changed

+35
-58
lines changed

internal/util/helpers_test.go

+35-58
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import (
99
"io"
1010
"net/http"
1111
"net/http/httptest"
12-
"net/url"
1312
"os"
1413
"path/filepath"
1514
"slices"
@@ -35,16 +34,17 @@ var (
3534
envLock = &sync.Mutex{}
3635
)
3736

38-
func SetEnvVar(t *testing.T, env string, value string) {
37+
func setEnvVar(t *testing.T, env string, value string) {
3938
t.Helper() // Keep golangci-lint happy
4039
envLock.Lock()
4140
t.Cleanup(envLock.Unlock)
4241

42+
originalEnvToken := os.Getenv(env)
4343
err := os.Setenv(env, value)
4444
if err != nil {
4545
t.Errorf("error setting %v: %v", env, err)
4646
}
47-
47+
defer os.Setenv(env, originalEnvToken)
4848
}
4949

5050
// TestGetConfigDirPath tests the GetConfigDirPath function
@@ -73,7 +73,7 @@ func TestGetConfigDirPath(t *testing.T) {
7373
for _, tt := range tests {
7474
t.Run(tt.name, func(t *testing.T) {
7575
t.Parallel()
76-
SetEnvVar(t, "XDG_CONFIG_HOME", tt.envVar)
76+
setEnvVar(t, "XDG_CONFIG_HOME", tt.envVar)
7777
path, err := util.GetConfigDirPath()
7878
if (err != nil) != tt.expectingError {
7979
t.Errorf("expected error: %v, got: %v", tt.expectingError, err)
@@ -163,13 +163,8 @@ func TestGetGrpcConnection(t *testing.T) {
163163
for _, tt := range tests {
164164
t.Run(tt.name, func(t *testing.T) {
165165
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)
173168

174169
conn, err := util.GetGrpcConnection(tt.grpcHost, tt.grpcPort, tt.allowInsecure, tt.issuerUrl, tt.clientId)
175170
if (err != nil) != tt.expectedError {
@@ -199,42 +194,31 @@ func TestSaveCredentials(t *testing.T) {
199194
// Create a temporary directory
200195
testDir := t.TempDir()
201196

202-
SetEnvVar(t, "XDG_CONFIG_HOME", testDir)
197+
setEnvVar(t, "XDG_CONFIG_HOME", testDir)
203198

204199
cfgPath := filepath.Join(testDir, "minder")
205200

206201
expectedFilePath := filepath.Join(cfgPath, "credentials.json")
207202

208203
filePath, err := util.SaveCredentials(tokens)
209-
if err != nil {
210-
t.Fatalf("expected no error, got %v", err)
211-
}
204+
require.NoError(t, err)
212205

213206
if filePath != expectedFilePath {
214207
t.Errorf("expected file path %v, got %v", expectedFilePath, filePath)
215208
}
216209

217210
// Verify the file content
218211
credsJSON, err := json.Marshal(tokens)
219-
if err != nil {
220-
t.Fatalf("error marshaling credentials: %v", err)
221-
}
212+
require.NoError(t, err)
222213

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)
228217

229218
if string(content) != string(credsJSON) {
230219
t.Errorf("expected file content %v, got %v", string(credsJSON), string(content))
231220
}
232221

233-
// Clean up
234-
err = os.Remove(filePath)
235-
if err != nil {
236-
t.Fatalf("error removing file: %v", err)
237-
}
238222
}
239223

240224
// TestRemoveCredentials tests the RemoveCredentials function
@@ -244,7 +228,7 @@ func TestRemoveCredentials(t *testing.T) {
244228
// Create a temporary directory
245229
testDir := t.TempDir()
246230

247-
SetEnvVar(t, "XDG_CONFIG_HOME", testDir)
231+
setEnvVar(t, "XDG_CONFIG_HOME", testDir)
248232
xdgConfigHome := os.Getenv("XDG_CONFIG_HOME")
249233

250234
filePath := filepath.Join(xdgConfigHome, "minder", "credentials.json")
@@ -278,7 +262,7 @@ func TestRefreshCredentials(t *testing.T) {
278262
// Create a temporary directory
279263
testDir := t.TempDir()
280264

281-
SetEnvVar(t, "XDG_CONFIG_HOME", testDir)
265+
setEnvVar(t, "XDG_CONFIG_HOME", testDir)
282266
tests := []struct {
283267
name string
284268
refreshToken string
@@ -291,7 +275,6 @@ func TestRefreshCredentials(t *testing.T) {
291275
{
292276
name: "Successful refresh with local server",
293277
refreshToken: "valid_refresh_token",
294-
issuerUrl: "http://localhost:8081",
295278
clientId: "minder-cli",
296279
responseBody: `{"access_token":"new_access_token","refresh_token":"new_refresh_token","expires_in":3600}`,
297280
expectedResult: util.OpenIdCredentials{
@@ -303,22 +286,19 @@ func TestRefreshCredentials(t *testing.T) {
303286
{
304287
name: "Error fetching new credentials (responseBody is missing) rwith local server",
305288
refreshToken: "valid_refresh_token",
306-
issuerUrl: "http://localhost:8081",
307289
clientId: "minder-cli",
308290
expectedError: "error unmarshaling credentials: EOF",
309291
},
310292
{
311293
name: "Error unmarshaling credentials with local server",
312294
refreshToken: "valid_refresh_token",
313-
issuerUrl: "http://localhost:8081",
314295
clientId: "minder-cli",
315296
responseBody: `invalid_json`,
316297
expectedError: "error unmarshaling credentials: invalid character 'i' looking for beginning of value",
317298
},
318299
{
319300
name: "Error refreshing credentials with local server",
320301
refreshToken: "valid_refresh_token",
321-
issuerUrl: "http://localhost:8081",
322302
clientId: "minder-cli",
323303
responseBody: `{"error":"invalid_grant","error_description":"Invalid refresh token"}`,
324304
expectedError: "error refreshing credentials: invalid_grant: Invalid refresh token",
@@ -335,8 +315,7 @@ func TestRefreshCredentials(t *testing.T) {
335315
}))
336316
defer server.Close()
337317

338-
parsedURL, _ := url.Parse(server.URL)
339-
tt.issuerUrl = parsedURL.String()
318+
tt.issuerUrl = server.URL
340319

341320
result, err := util.RefreshCredentials(tt.refreshToken, tt.issuerUrl, tt.clientId)
342321
if tt.expectedError != "" {
@@ -391,7 +370,7 @@ func TestLoadCredentials(t *testing.T) {
391370
t.Run(tt.name, func(t *testing.T) {
392371
t.Parallel()
393372
testDir := t.TempDir()
394-
SetEnvVar(t, "XDG_CONFIG_HOME", testDir)
373+
setEnvVar(t, "XDG_CONFIG_HOME", testDir)
395374
// Create the minder directory inside the temp directory
396375
minderDir := filepath.Join(testDir, "minder")
397376
err := os.MkdirAll(minderDir, 0750)
@@ -403,10 +382,7 @@ func TestLoadCredentials(t *testing.T) {
403382

404383
if tt.fileContent != "" {
405384
// 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))
410386
// Print the file path and content for debugging
411387
t.Logf("Test %s: written file path %s with content: %s", tt.name, filePath, tt.fileContent)
412388
} else {
@@ -433,6 +409,7 @@ func TestLoadCredentials(t *testing.T) {
433409
}
434410
}
435411

412+
// TestCase struct for holding test case data
436413
type TestCase struct {
437414
name string
438415
token string
@@ -444,18 +421,6 @@ type TestCase struct {
444421
createServer func(t *testing.T, tt TestCase) *httptest.Server
445422
}
446423

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-
459424
// TestRevokeToken tests the RevokeToken function
460425
func TestRevokeToken(t *testing.T) {
461426
t.Parallel()
@@ -468,7 +433,16 @@ func TestRevokeToken(t *testing.T) {
468433
tokenHint: "refresh_token",
469434
expectedPath: "/realms/stacklok/protocol/openid-connect/revoke",
470435
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+
},
472446
},
473447
{
474448
name: "Invalid issuer URL",
@@ -499,7 +473,6 @@ func TestRevokeToken(t *testing.T) {
499473
}
500474
})
501475
}
502-
503476
}
504477

505478
// TestGetJsonFromProto tests the GetJsonFromProto function
@@ -540,8 +513,13 @@ func TestGetJsonFromProto(t *testing.T) {
540513
t.Errorf("GetJsonFromProto() error = %v, expectedError %v", err, tt.expectedError)
541514
return
542515
}
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)
545523
}
546524
})
547525
}
@@ -724,7 +702,6 @@ func TestExpandFileArgs(t *testing.T) {
724702
}) {
725703
t.Errorf("ExpandFileArgs() = %v, want %v", got, tt.expected)
726704
}
727-
defer os.RemoveAll(testDir)
728705
})
729706
}
730707
}

0 commit comments

Comments
 (0)