Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add additional test coverage for helper functions in Util #4651

Open
wants to merge 15 commits into
base: main
Choose a base branch
from

Conversation

gajananan
Copy link
Contributor

@gajananan gajananan commented Oct 5, 2024

Summary

Currently helper functions in Util lacks test coverage

This commit adds test coverage helper functions in Util

Ref #4380

Change Type

Mark the type of change your PR introduces:

  • Bug fix (resolves an issue without affecting existing features)
  • Feature (adds new functionality without breaking changes)
  • Breaking change (may impact existing functionalities or require documentation updates)
  • Documentation (updates or additions to documentation)
  • Refactoring or test improvements (no bug fixes or new functionality)

Testing

Outline how the changes were tested, including steps to reproduce and any relevant configurations.
Attach screenshots if helpful.

Review Checklist:

  • Reviewed my own code for quality and clarity.
  • Added comments to complex or tricky code sections.
  • Updated any affected documentation.
  • Included tests that validate the fix or feature.
  • Checked that related changes are merged.

@coveralls
Copy link

coveralls commented Oct 5, 2024

Coverage Status

coverage: 53.769% (+0.5%) from 53.264%
when pulling 00dd4ba on gajananan:improve-test-coverage-util-helpers
into 49f192a on stacklok:main.

@gajananan gajananan marked this pull request as ready for review October 8, 2024 12:15
t.Parallel()

// Create a unique directory for each test
testDir := fmt.Sprintf("testdir_%s", sanitizeTestName(tt.name))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could probably leverage golang's utilities instead: https://pkg.go.dev/testing#B.TempDir

This will create a temporary directory for tests and even clean up afterwards.

wdyt?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thank you. I agree. that is a clean approach.

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
err := os.Setenv("XDG_CONFIG_HOME", tt.envVar)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doing this in t.Parallel may cause interference with other tests.

What I've done in the past is to put some explicit locks on these tests; without that, these tests will tend to be flaky when running on multiple cores at the same time.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additionally, you'll want to reset the value of XDG_CONFIG_HOME after this test. You can use t.Setenv() to do this.

Copy link
Contributor Author

@gajananan gajananan Jan 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will add explicit locks and reset the value of XDG_CONFIG_HOME

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw the lock (which you might want to call envLock rather than mu, to make it clear as to why we are locking), but I don't see the call to t.Setenv() or otherwise resetting the environment variables.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(This still needs to clean up after the os.Setenv)

Comment on lines 232 to 236
xdgConfigHome := os.Getenv("XDG_CONFIG_HOME")
if xdgConfigHome == "" {
homeDir, err := os.UserHomeDir()
if err != nil {
t.Fatalf("error getting home directory: %v", err)
}
xdgConfigHome = filepath.Join(homeDir, ".config")
}

filePath := filepath.Join(xdgConfigHome, "minder", "credentials.json")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This environment-related stuff is going to conflict with TestGetGrpcConnection; it will also end up touching the user's actual home directory.

What I would do:

  1. Use t.TempDir() to create a temp directory.
  2. Set XDG_CONFIG_HOME to point at the directory from (1).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you. it is good to learn about the impact to other tests.

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
err := os.Setenv(MinderAuthTokenEnvVar, tt.envToken)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, this use of env vars is likely to cause trouble. At a minimum, you should restore the previous value of the environment variable at the end of the t.Run() function (e.g. with defer)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will do reset the env at the end of test run.

parsedURL, _ := url.Parse(server.URL)
tt.issuerUrl = parsedURL.String()

result, err := RefreshCredentials(tt.refreshToken, tt.issuerUrl, tt.clientId)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this function is not side-effect-free, you may need to again set XDG_CONFIG_HOME to point to a different location.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@evankanderson , could you confirm we still need to do this after my latest change?

internal/util/helpers_test.go Outdated Show resolved Hide resolved

// Create a temporary file for testing
if tc.filePath == "testfile.txt" {
err := os.WriteFile(tc.filePath, []byte(tc.expectedDesc), 0600)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should do this in t.TestDir()

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you. I assume, you were referring to t.TempDir()

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, thanks!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively, you could create testfile.txt once outside the t.Run(), since it shouldn't need to vary across the test cases.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(You probably still want to put it in t.TempDir(), though.)

@evankanderson
Copy link
Member

@gajananan

It looks like this is close to the finish line -- any chance you can incorporate the feedback (and fix conflicts) in the next week?

@evankanderson
Copy link
Member

Hi @gajananan,

We'd love to get this merged! If you don't have time to work on this, we'll probably have someone over here at Stacklok apply the requested changes and merge it.

@evankanderson
Copy link
Member

Hey @gajananan -- we'd love to get this PR in. I ran into one of your co-workers at KubeCon, and they said that your work schedule might be preventing you from updating. A quick note of "I can get to this within a week" or "please carry this forward, I'm busy now" would be handy.

Thanks again for your work so far!

Copy link
Contributor

This PR needs additional information before we can continue. It is now marked as stale because it has been open for 30 days with no activity. Please provide the necessary details to continue or it will be closed in 30 days.

@github-actions github-actions bot added the Stale label Dec 20, 2024
@gajananan
Copy link
Contributor Author

Hey @gajananan -- we'd love to get this PR in. I ran into one of your co-workers at KubeCon, and they said that your work schedule might be preventing you from updating. A quick note of "I can get to this within a week" or "please carry this forward, I'm busy now" would be handy.

Thanks again for your work so far!

My sincere apologies for long silence on this. I would take it forward with addressing the comments/feedback

Currently helper functions in Util lacks test coverage

This commit adds test coverage helper functions in Util

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
Currently helper functions in Util lacks test coverage

This commit fixes the lint errors and handles errors.

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
Currently helper functions in Util lacks test coverage

This commit
- fixes the lint errors and handles errors.
- adds test coverage for OpenFileArg, ExpandFileArgs,  functions

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
Currently helper functions in Util lacks test coverage.

This commit
- fixes the lint errors and handles errors.
- Adds test coverage for LoadCredentials function

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
Currently helper functions in Util lacks test coverage

This commit fixes the lint errors after fixing lint version.

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
Currently helper functions in Util lacks test coverage

This commit adds test coverage for RevokeToken function.

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
Currently helper functions in Util lacks test coverage

This commit adds test coverage for the following functions by addressing the review feedback
- GetConfigDirPath
- GetGrpcConnection
- SaveCredentials
- RemoveCredentials
- RefreshCredentials
- LoadCredentials
- RevokeToken
- GetJsonFromProto
- GetYamlFromProto
- TestOpenFileArg
- ExpandFileArgs
Signed-off-by: Kugamoorthy Gajananan <[email protected]>

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
@gajananan gajananan force-pushed the improve-test-coverage-util-helpers branch from c671a66 to 13fd878 Compare January 18, 2025 09:31
@gajananan gajananan requested a review from a team as a code owner January 18, 2025 09:31
@github-actions github-actions bot removed the Stale label Jan 19, 2025
Copy link
Member

@evankanderson evankanderson left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for getting back to this. Some of the comments are nit-picky, and you can add a comment saying "just trying to get this in", but since I thought part of your goal was learning the Go language, I figured I'd provide more extensive comments and pointers.

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
err := os.Setenv("XDG_CONFIG_HOME", tt.envVar)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw the lock (which you might want to call envLock rather than mu, to make it clear as to why we are locking), but I don't see the call to t.Setenv() or otherwise resetting the environment variables.

t.Errorf("error closing connection: %v", err)
}
}
defer os.Setenv(util.MinderAuthTokenEnvVar, originalEnvToken)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move this deferred call up next to the os.Setenv call, or use t.Setenv, which automatically undoes the environment variable setup during test teardown. (Otherwise, an early exit might not reach this defer statement.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved this deferred call up next to the os.Setenv call.

internal/util/helpers_test.go Outdated Show resolved Hide resolved
}

for _, tt := range tests {
tt := tt // capture range variable
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is no longer needed since Go 1.22.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, no longer need. I removed it.

Comment on lines 373 to 378
// Create a unique temporary directory for the test
// tempDir, err := os.MkdirTemp("", "test_load_credentials_"+tt.name)
// if err != nil {
// t.Fatalf("failed to create temp directory: %v", err)
// }
// defer os.RemoveAll(tempDir)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this commented out?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should be removed. I will do that.

Comment on lines 492 to 495
issuerUrl := tt.issuerUrl
if tt.name != "Invalid issuer URL" {
issuerUrl = server.URL
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since most of the body of this test is conditional on the test name, I wonder if using two tests (rather than a data-driven test) would simplify things here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I significantly changed the test function, I guess this comment has been addressed with latest change.


// Create a temporary file for testing
if tc.filePath == "testfile.txt" {
err := os.WriteFile(tc.filePath, []byte(tc.expectedDesc), 0600)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively, you could create testfile.txt once outside the t.Run(), since it shouldn't need to vary across the test cases.


// Create a temporary file for testing
if tc.filePath == "testfile.txt" {
err := os.WriteFile(tc.filePath, []byte(tc.expectedDesc), 0600)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(You probably still want to put it in t.TempDir(), though.)

assert.Error(t, err)
} else {
assert.NoError(t, err)
if tc.filePath == "-" || tc.filePath != "-" {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't this if cover all cases?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Else condition covers the case:
{
name: "Dash as file path",
filePath: "-",
dashOpen: strings.NewReader("dash input"),
expectedDesc: "dash input",
expectError: false,
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Alternatively, you could create testfile.txt once outside the t.Run()"

testfile.txt is required only in one case, so it is created only for that case.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, the comment here is that this line says:

Suggested change
if tc.filePath == "-" || tc.filePath != "-" {
path := tc.filePath
if path == "-" || path != "-" {

It should always be true that a string is either equal to a constant, or not equal to the same constant.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Alternatively, you could create testfile.txt once outside the t.Run()"

testfile.txt is required only in one case, so it is created only for that case.

(This was from a different comment.)

While it's true that testfile.txt is only needed in one case, it doesn't hurt the other cases, and could end up simplifying the setup logic. On the other hand, I don't feel strongly about it being one place or the other.

Copy link
Contributor Author

@gajananan gajananan Jan 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, the comment here is that this line says:

It should always be true that a string is either equal to a constant, or not equal to the same constant.

I got it, I will fix it.

Comment on lines 730 to 740
func compareExpandedFiles(got, expected []util.ExpandedFile) bool {
if len(got) != len(expected) {
return false
}
for i := range got {
if got[i].Path != expected[i].Path || got[i].Expanded != expected[i].Expanded {
return false
}
}
return true
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using slices.Equal, or slices.EqualFunc with an anonymous function if you need to.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will use slices.EqualFunc with an anonymous function

Currently helper functions in Util lacks test coverage

This commit fixes the following functions by addressing the review feedback.
- TestGetConfigDirPath; Change from mu to envLock
- TestGetGrpcConnection: Moved deferred call up next to the os.Setenv call to reset env variable.
- TestSaveCredentials: Add lock so that config dir path is retrieved correctly.
- TestRemoveCredentials: Added deferred call up next to the os.Setenv call to reset env variable.
- TestLoadCredentials: Removed the statement that capture range variable and removed commented code, moved the deferred call up next to the resource it creates.
- TestOpenFileArg: Add t.TempDir() to create test the file.
- TestRevokeToken: Add a func(t *testing.T) *httptest.Server in the test cases which constructs the server.
- ExpandFileArgs: Using slices.EqualFunc with an anonymous function

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
// TestGetConfigDirPath tests the GetConfigDirPath function
func TestGetConfigDirPath(t *testing.T) {
t.Parallel()
var envLock sync.Mutex
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you want envLock to be at the file level, e.g. on line 32 before this function, because you have multiple tests all trying to set the environment, and you don't want any of them conflicting with each other.

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
err := os.Setenv("XDG_CONFIG_HOME", tt.envVar)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(This still needs to clean up after the os.Setenv)

Comment on lines 154 to 158
t.Parallel()
originalEnvToken := os.Getenv(util.MinderAuthTokenEnvVar)
err := os.Setenv(util.MinderAuthTokenEnvVar, tt.envToken)
// reset this the environment variable when complete.
defer os.Setenv(util.MinderAuthTokenEnvVar, originalEnvToken)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You'll want to protect this with a mutex as well. Given the likely test execution time, I'd probably be lazy and re-use envLock from TestGetConfigDirPath, but you could also use separate locks for each environment variable if you're feeling particularly ambitious (i wouldn't recommend it, though).

Comment on lines 180 to 182
var envLock sync.Mutex
envLock.Lock()
defer envLock.Unlock()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declaring a new sync.Mutex here and then acquiring it doesn't do much, because the mutex isn't shared across multiple goroutines (e.g. t.Run() spawns a new goroutine, but this doesn't call t.Run).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed now.

t.Run(tt.name, func(t *testing.T) {
t.Parallel()
tempDir := t.TempDir()
defer os.RemoveAll(tempDir)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You shouldn't need this if you use t.TempDir():

The directory is automatically removed when the test and all its subtests complete.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed

Comment on lines 406 to 413
// Temporarily override the environment variable for the test
originalEnv := os.Getenv("XDG_CONFIG_HOME")
err = os.Setenv("XDG_CONFIG_HOME", tempDir)
if err != nil {
t.Errorf("error setting XDG_CONFIG_HOME: %v", err)
}
// reset this the environment variable when complete.
defer os.Setenv("XDG_CONFIG_HOME", originalEnv)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You'll want to grab envLock here for the rest of the test, too.

internal/util/helpers_test.go Outdated Show resolved Hide resolved
tempFilePath = filepath.Join(testDir, tc.filePath)
err := os.WriteFile(tempFilePath, []byte(tc.expectedDesc), 0600)
assert.NoError(t, err)
defer os.Remove(tempFilePath)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since you're putting tempFilePath in a directory from t.TempDir, you shouldn't need to delete it yourself later; t.TempDir will delete the directory and its contents at the end of the test.

Comment on lines 632 to 640
if tc.filePath == "testfile.txt" {
tempFilePath = filepath.Join(testDir, tc.filePath)
err := os.WriteFile(tempFilePath, []byte(tc.expectedDesc), 0600)
assert.NoError(t, err)
defer os.Remove(tempFilePath)
} else {
// When handling the dash (-) as a file path, it should read from the provided io.Reader (tc.dashOpen) instead of trying to open a file
tempFilePath = tc.filePath
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you create testfile.txt outside the test case code, you can avoid needing as much conditional logic in the test. Compare:

func TestOpenFileArg(t *testing.T) {
	t.Parallel()
	testDir := t.TempDir()
	// Create one test file for the file input case
	tempFilePath := filepath.Join(testDir, "testfile.txt")
	assert.NoError(os.WriteFile(tempFilePath, []byte("test content"), 0600))

	...
		filePath: tempFilePath

(vs the current 11 lines with if/else)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thank you, I fixed it.

Currently helper functions in Util lacks test coverage

This commit fixes the following functions by addressing the review feedback.
- Add envLock mutex to ensure that all the tests that run t.SetEnv("XDG_CONFIG...") need to be prevented from running at the same time as each other.
- TestGetConfigDirPath:  Added deferred call up next to the os.Setenv call to reset env variable.
- TestOpenFileArg* Removed if condition.

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
Currently helper functions in Util lacks test coverage

This commit fixes the following functions by addressing the review feedback.
- Add a helper function SetEnvVar just to make sure that mutex lock handle things consistently
- Fix all test functions that require mutex with above helper function

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
Currently helper functions in Util lacks test coverage

This commit fixes the following functions by addressing the review feedback.
- Fix lint errors

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
Currently helper functions in Util lacks test coverage

This commit fixes the following functions by addressing the review feedback.
- Remove the line tt := tt to capture the range variable in the functions.
- Normalize JSON strings by removing all whitespaces and new lines in TestGetYamlFromProto

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
Currently helper functions in Util lacks test coverage

This commit fixes the following functions by addressing the review feedback.
- TestOpenFileArg: create testfile.txt outside the test case code, to avoid needing as much conditional logic in the test.

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
evankanderson
evankanderson previously approved these changes Jan 27, 2025
Copy link
Member

@evankanderson evankanderson left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few more small nits, but this is looking very close! In particular, I think you want SetEnvVar to take care of restoring the environment variable; the other fixes are purely your choice / passing along some experience maintaining Go code.

internal/util/helpers_test.go Show resolved Hide resolved
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
originalEnvToken := os.Getenv(util.MinderAuthTokenEnvVar)
err := os.Setenv(util.MinderAuthTokenEnvVar, tt.envToken)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you want to use SetEnvVar here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes,

envLock = &sync.Mutex{}
)

func SetEnvVar(t *testing.T, env string, value string) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if you want this capitalized (exported). It shouldn't be a big issue, since it's in a _test.go file anyway.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I fix it.

t.Errorf("error setting %v: %v", util.MinderAuthTokenEnvVar, err)
}
// reset this the environment variable when complete.
defer os.Setenv(util.MinderAuthTokenEnvVar, originalEnvToken)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should put this cleanup in SetEnvVar, so it's applied consistently.

t.Fatalf("error marshaling credentials: %v", err)
}

fpath := filepath.Clean(filePath)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you need to run filepath.Clean here?

Copy link
Contributor Author

@gajananan gajananan Jan 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I remember that I got lint error : G304: Potential file inclusion via variable (gosec)

which required that line.

Comment on lines 209 to 211
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Slight preference for require.NoError(t, err) here and below, to break up the common-case flow of the test a bit less.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will do that.

Comment on lines 233 to 237
// Clean up
err = os.Remove(filePath)
if err != nil {
t.Fatalf("error removing file: %v", err)
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need this since your files are in t.TempDir(); the test will do it for you automatically.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I removed that.

Comment on lines 338 to 339
parsedURL, _ := url.Parse(server.URL)
tt.issuerUrl = parsedURL.String()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do this, rather than simply:

tt.issuerUrl = server.URL

(or simply use server.URL below, and don't make the issuerUrl a field in the testcase struct, since it is never used...)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes. I can simplify as suggested.

Comment on lines 406 to 409
err := os.WriteFile(filePath, []byte(tt.fileContent), 0600)
if err != nil {
t.Fatalf("failed to write test file: %v", err)
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, prefer require.NoError():

Suggested change
err := os.WriteFile(filePath, []byte(tt.fileContent), 0600)
if err != nil {
t.Fatalf("failed to write test file: %v", err)
}
require.NoError(t, os.WriteFile(filePath, []byte(tt.fileContent), 0600))

tokenHint: "refresh_token",
expectedPath: "/realms/stacklok/protocol/openid-connect/revoke",
expectError: false,
createServer: createTestServer,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another option here is to make createTestServer an anonymous function, which avoids needing to declare it or TestCase outside this function:

Suggested change
createServer: createTestServer,
createServer: func(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
require.NoError(t, r.ParseForm())
require.Equal(t, "minder-cli", r.Form.Get("client_id"))
require.Equal(t, "test-token", r.Form.Get("token"))
require.Equal(t, "refresh_token", r.Form.Get("token_type_hint"))
}))
},

@gajananan
Copy link
Contributor Author

A few more small nits, but this is looking very close! In particular, I think you want SetEnvVar to take care of restoring the environment variable; the other fixes are purely your choice / passing along some experience maintaining Go code.

Thank you for your detailed feedback which helped a lot to learn the code base. I addressed the remainder of the comments as well.

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]>
evankanderson
evankanderson previously approved these changes Jan 27, 2025
Currently helper functions in Util lacks test coverage

This commit fixes the following functions by addressing the review feedback.
- setEnvVar:  Fixed setting env to original value using t.Cleanup()

Signed-off-by: Kugamoorthy Gajananan <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants