Go

Go

Made by DeepSource

Use t.Setenv and friends instead of os.Setenv for test file(s) GO-W1032

Bug risk
Major
Autofix

For tests, environment variables are sometimes temporarily set. It is also essential and even a good practice to unset those temporary values as they might interfere with others trying to use the same environment variable. It is recommended that for *_test.go file(s) one should use Setenv method from the "testing" package as it unsets the same after the test has concluded. Following Setenv calls os.Setenv(key, value) and uses Cleanup to restore the environment variable to its original value after the test.

Bad practice

func setup() {
    os.Setenv("a", "b")
}

func TestF(t *testing.T) {
    os.Setenv("a", "b")
}

func TB(tb testing.TB) {
    os.Setenv("a", "b")
}

func FuzzF(f *testing.F) {
    os.Setenv("a", "b")
}

Recommended

func setup() {
    testing.Setenv("a", "b")
}

func TestF(t *testing.T) {
    t.Setenv("a", "b")
}

func TB(tb testing.TB) {
    tb.Setenv("a", "b")
}

func FuzzF(f *testing.F) {
    f.Setenv("a", "b")
}