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

test: use t.Setenv to set env vars in tests #1940

Merged
merged 2 commits into from
Dec 19, 2023
Merged

test: use t.Setenv to set env vars in tests #1940

merged 2 commits into from
Dec 19, 2023

Conversation

Juneezee
Copy link
Contributor

@Juneezee Juneezee commented Dec 9, 2023

Starting from Go 1.17, we can use t.Setenv to set environment variable in test. The environment variable is automatically restored to its original value when the test and all its subtests complete. This ensures that each test does not start with leftover environment variables from previous completed tests.

Reference: https://pkg.go.dev/testing#T.Setenv

func TestFoo(t *testing.T) {
	// before
	os.Setenv(key, "new value")
	defer os.Unsetenv(key)
	
	// after
	t.Setenv(key, "new value")
}

This PR also splits large test cases into subtests. This is useful because VSCode is able to run subtest separately

image

@hairyhenderson
Copy link
Owner

Hi @Juneezee, thanks for working on this. Most of these tests pre-date Go 1.17, which is why I didn't use t.Setenv (though you'll see that I have started using it in some newer tests in certain packages!).

I would have preferred to see the t.Setenv changes happen separately from the t.Run changes - as it is this is a fairly complex PR to review, and it will take some time, especially given that I want to make sure the test logic is entirely unchanged. But, I will review in depth when I have some time.

@Juneezee
Copy link
Contributor Author

Hi @hairyhenderson. No worries 😄

Copy link
Owner

@hairyhenderson hairyhenderson left a comment

Choose a reason for hiding this comment

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

Thanks @Juneezee! I've made some minor adjustments and rebased, otherwise this LGTM.

Juneezee and others added 2 commits December 18, 2023 20:57
This commit replaces `os.Setenv` with `t.Setenv` in tests. The
environment variable is automatically restored to its original value
when the test and all its subtests complete.

Reference: https://pkg.go.dev/testing#T.Setenv
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
Signed-off-by: Dave Henderson <dhenderson@gmail.com>
@hairyhenderson hairyhenderson enabled auto-merge (squash) December 19, 2023 01:57
@hairyhenderson hairyhenderson merged commit 483af65 into hairyhenderson:main Dec 19, 2023
13 checks passed
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.

None yet

2 participants