DEV Community

Cover image for Auto-reset environment variables when testing in Go
Pavel Kutáč
Pavel Kutáč

Posted on • Edited on

5 1

Auto-reset environment variables when testing in Go

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)
            }
        }
    }
}
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",
    })
    t.Cleanup(closer) // In Go 1.14+
    // defer closer() // Prior Go 1.14
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (3)

Collapse
 
maxmcd profile image
Max McDonnell

You want "t.Cleanup()", not defer

Collapse
 
arxeiss profile image
Pavel Kutáč

Thanks for the tip. Will look at it

Collapse
 
klaernie profile image
Andre Klärner

Since go1.17 there is a builtin: pkg.go.dev/testing#T.Setenv

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay