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 PR replaces
os.Setenv
witht.Setenv
. Starting from Go 1.17, we can uset.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.
Checklist