-
Notifications
You must be signed in to change notification settings - Fork 17.8k
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
proposal: testing: add Unsetenv to call os.Unsetenv and then restore the value using Cleanup #52817
Comments
Does |
@mvdan Thanks for your comment. I can find these lines in this repository that erase environment variables during testing: Lines 277 to 280 in 6fd0520
go/src/cmd/go/internal/generate/generate_test.go Lines 105 to 108 in 6fd0520
go/src/cmd/go/internal/work/security_test.go Line 258 in 6fd0520
I can't really say how common it is, but Go itself is using it for testing. |
This proposal has been added to the active column of the proposals project |
Honestly, most code (aside from reading configuration at application startup) probably shouldn't be reading from the environment anyway. It's the ultimate global variable. I'm not sure that adding test helpers for things you shouldn't usually do is the best idea. That being said, if we did want something like this, I think there's a simpler solution. The proposed function is doing two things, but only really needs to do one thing. Most of the time, test authors just want to ensure they leave the environment the way it was when the test started. This would do that, much more simply, IMO: // CleanupEnv reverts all changes to environment variables at the end of this test.
func (t *testing.T) CleanupEnv() {
vals := os.Environ()
t.Cleanup(func(){
os.Clearenv()
for _, v := range vals {
parts := strings.SplitN(v, "=", 2)
os.Setenv(parts[0], parts[1])
}
})
} (with probably better error handling) |
@natefinch you're not wrong, but given that we already have t.Setenv, adding t.CleanupEnv separately seems like having two confusingly similar ways to do something. I still don't think we need t.Unsetenv though. |
Based on the discussion above, this proposal seems like a likely decline. |
I agree that this isn't common enough to be that useful, especially as it's entirely trivial to do without the functionality built in:
|
@rogpeppe Thanks for the tip. Somehow I missed this. 😃 |
No change in consensus, so declined. |
I wish to have
t.Unsetenv(key)
that unsets environment variables and automatically restores their values usingCleanup
, in a way similar tot.Setenv(key, value)
. Here is the hypothetical usage:A possible implementation:
The text was updated successfully, but these errors were encountered: