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

Merged
merged 1 commit into from
Oct 7, 2022
Merged

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

merged 1 commit into from
Oct 7, 2022

Conversation

Juneezee
Copy link
Contributor

@Juneezee Juneezee commented Sep 1, 2022

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 unsetting the env var) on every instance.

func TestFoo(t *testing.T) {
	// before
	key := "ENV"
	originalEnv := os.Getenv(key)
	
	if err := os.Setenv(key, "new value"); err != nil {
		t.Fatal(err)
	}
	defer func() {
		if err := os.Setenv(key, originalEnv); err != nil {
			t.Logf("failed to set env %s back to original value: %v", key, err)
		}
	}()
	
	// 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 <[email protected]>
Copy link
Member

@ARolek ARolek left a comment

Choose a reason for hiding this comment

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

@Juneezee cool feature! I was not aware of this addition to the test suite. Thanks for the submission.

@coveralls
Copy link

Pull Request Test Coverage Report for Build 52242403c-PR-882

  • 0 of 0 changed or added relevant lines in 0 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage remained the same at 45.315%

Totals Coverage Status
Change from base Build e41e1867c: 0.0%
Covered Lines: 5610
Relevant Lines: 12380

💛 - Coveralls

@ARolek ARolek merged commit a248796 into go-spatial:master Oct 7, 2022
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.

3 participants