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 #1398

Merged
merged 1 commit into from Dec 24, 2022
Merged

test: use T.Setenv to set env vars in tests #1398

merged 1 commit into from Dec 24, 2022

Conversation

Juneezee
Copy link
Contributor

A testing cleanup.

This PR replaces os.Setenv with t.Setenv. 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.

This saves us at least 2 lines (error check, and cleanup) on every instance.

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

func TestFoo(t *testing.T) {
	// before
	key := "ENV"
	originalEnv := os.Getenv(key)

	os.Setenv(key, "new value")
	defer os.Setenv(key, originalEnv)
	
	// after
	t.Setenv(key, "new value")
}

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>
Copy link
Owner

@shirou shirou left a comment

Choose a reason for hiding this comment

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

Indeed. Awesome contribution!

@shirou shirou merged commit f848ee3 into shirou:master Dec 24, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants