DEV Community

loading...
Cover image for Auto-reset environment variables when testing in Go

Auto-reset environment variables when testing in Go

Pavel Kutáč
・1 min read

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 defer

In Go, it can be done with a simple helper, which will return a callback. That is then called with defer to automatically be called when the test ends.

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)
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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",
    })
    defer closer()
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)