package config import ( "os" "strings" "testing" ) // ClearEnvForTest unsets every variable in the process environment // for the rest of the test and puts each back when the test ends, so // a test sees only the variables it sets itself, not whatever the // developer's shell exports. func ClearEnvForTest(t *testing.T) { t.Helper() for _, entry := range os.Environ() { key, _, _ := strings.Cut(entry, "=") // t.Setenv registers the restore; the Unsetenv after it is // what makes the key absent, since a key set to the empty // string is still present, and godotenv will not overwrite a // present key. t.Setenv(key, "") err := os.Unsetenv(key) if err != nil { t.Fatalf("unsetting %s: %v", key, err) } } }