Easily set temporary environment variables and commandline flags, usually within a testing environment.
SetEnvVar
, SetEnvVars
and AppendOSArgs
all return a single func
, which when executed will reset the given variables to their previous state.
Important note - Things may not work as expected if you run your tests in parallel!
func TestSomething(t *testing.T) {
log.Println(os.Getenv("A")) // ""
t.Run("test one", func(t *testing.T) {
resetEnvVars := tmpenv.SetEnvVars(map[string]string{
"A": "123",
})
defer resetEnvVars()
log.Println(os.Getenv("A")) // "123"
})
log.Println(os.Getenv("A")) // ""
t.Run("test two", func(t *testing.T) {
resetEnvVars := tmpenv.SetEnvVars(map[string]string{
"A": "456",
})
defer resetEnvVars()
log.Println(os.Getenv("A")) // "456"
})
log.Println(os.Getenv("A")) // ""
}