I wish to have t.Unsetenv(key) that unsets environment variables and automatically restores their values using Cleanup, in a way similar to t.Setenv(key, value). Here is the hypothetical usage:
func TestNoValue(t *testing.T) {
// unset the environment variable ENV_KEY during the test
t.Unsetenv("ENV_KEY")
// ... more code here ...
}
A possible implementation:
func (c *common) Unsetenv(key string) {
c.checkFuzzFn("Unsetenv")
prevValue, prevSet := os.LookupEnv(key)
if err := os.Unsetenv(key); err != nil {
c.Fatalf("cannot unset environment variable: %v", err)
}
if prevSet {
c.Cleanup(func() { os.Setenv(key, prevValue) })
} else {
c.Cleanup(func() { os.Unsetenv(key) })
}
}
func (t *T) Unsetenv(key) {
if t.isParallel {
panic("testing: t.Unsetenv called after t.Parallel; cannot unset environment variables in parallel tests")
}
t.isEnvSet = true
t.common.Unsetenv(key)
}