During the testing, one of the hardest parts is to make tests isolated from others. And when setting environment variables in tests, they must be reset to original values. But developers must do it on their own.
🇨🇿 V češtině si lze článek přečíst na kutac.cz
Sometimes there is a need to set environment variable directly in the test. And tests should do clean-up after themselves, to not affect others. So also env vars should be reset to the original value, or deleted.
Helper and t.Cleanup()
/defer
In Go, it can be done with a simple helper, which will return a callback. Which is called with t.Cleanup() in Go 1.14+ or with defer
in older Go versions.
func envSetter(envs map[string]string) (closer func()) {
originalEnvs := map[string]string{}
for name, value := range envs {
if originalValue, ok := os.LookupEnv(name); ok {
originalEnvs[name] = originalValue
}
_ = os.Setenv(name, value)
}
return func() {
for name := range envs {
origValue, has := originalEnvs[name]
if has {
_ = os.Setenv(name, origValue)
} else {
_ = os.Unsetenv(name)
}
}
}
}
Usage
func TestFunctionWithEnvVars(t *testing.T) {
closer := envSetter(map[string]string{
"MY_ENV_VARS": "with some value",
"MY_ANOTHER_ENV_VARS": "again with some value",
})
t.Cleanup(closer) // In Go 1.14+
// defer closer() // Prior Go 1.14
// ...
}
Top comments (2)
You want "t.Cleanup()", not defer
Thanks for the tip. Will look at it