test: use `T.Setenv` to set env vars in tests

This commit replaces `os.Setenv` with `t.Setenv` in tests. The
environment variable is automatically restored to its original value
when the test and all its subtests complete.

Reference: https://pkg.go.dev/testing#T.Setenv
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
pull/12009/head
Eng Zer Jun 4 years ago committed by Lucas Bajolet
parent f7ce79362d
commit f5ec0f1c57

@ -15,10 +15,7 @@ func init() {
func TestTest_noEnv(t *testing.T) {
// Unset the variable
if err := os.Setenv(TestEnvVar, ""); err != nil {
t.Fatalf("err: %s", err)
}
defer os.Setenv(TestEnvVar, "1")
t.Setenv(TestEnvVar, "")
mt := new(mockT)
Test(mt, TestCase{})

@ -798,8 +798,7 @@ func TestHCL2PostProcessorForceFlag(t *testing.T) {
UUID, _ := uuid.GenerateUUID()
// Manifest will only clean with force if the build's PACKER_RUN_UUID are different
os.Setenv("PACKER_RUN_UUID", UUID)
defer os.Unsetenv("PACKER_RUN_UUID")
t.Setenv("PACKER_RUN_UUID", UUID)
args := []string{
filepath.Join(testFixture("hcl"), "force.pkr.hcl"),
@ -833,7 +832,7 @@ func TestHCL2PostProcessorForceFlag(t *testing.T) {
// Second build should override previous manifest
UUID, _ = uuid.GenerateUUID()
os.Setenv("PACKER_RUN_UUID", UUID)
t.Setenv("PACKER_RUN_UUID", UUID)
args = []string{
"-force",

@ -328,7 +328,7 @@ func TestInitCommand_Run(t *testing.T) {
t.Cleanup(func() {
_ = os.RemoveAll(tt.packerUserFolder)
})
os.Setenv("PACKER_CONFIG_DIR", tt.packerConfigDir)
t.Setenv("PACKER_CONFIG_DIR", tt.packerConfigDir)
for _, init := range tt.setup {
init(t, tt)
if t.Skipped() {

@ -128,7 +128,7 @@ func TestPluginsInstallCommand_Run(t *testing.T) {
t.Cleanup(func() {
_ = os.RemoveAll(tt.packerConfigDir)
})
os.Setenv("PACKER_CONFIG_DIR", tt.packerConfigDir)
t.Setenv("PACKER_CONFIG_DIR", tt.packerConfigDir)
createFiles(tt.packerConfigDir, tt.inPluginFolder)
hash, err := dirhash.HashDir(tt.packerConfigDir, "", dirhash.DefaultHash)

@ -175,7 +175,7 @@ func TestPluginsRemoveCommand_Run(t *testing.T) {
t.Cleanup(func() {
_ = os.RemoveAll(tt.packerConfigDir)
})
os.Setenv("PACKER_CONFIG_DIR", tt.packerConfigDir)
t.Setenv("PACKER_CONFIG_DIR", tt.packerConfigDir)
createFiles(tt.packerConfigDir, tt.inPluginFolder)
hash, err := dirhash.HashDir(tt.packerConfigDir, "", dirhash.DefaultHash)

@ -1,7 +1,6 @@
package command
import (
"os"
"testing"
"github.com/google/go-cmp/cmp"
@ -410,13 +409,8 @@ func TestRegistrySetup(t *testing.T) {
func runRegistryTest(t *testing.T, args registryTestArgs) {
for evar, val := range args.envvars {
os.Setenv(evar, val)
t.Setenv(evar, val)
}
defer func() {
for evar := range args.envvars {
os.Setenv(evar, "")
}
}()
defaultMeta := TestMetaFile(t)

@ -1,7 +1,6 @@
package hcl2template
import (
"os"
"path/filepath"
"testing"
@ -11,8 +10,7 @@ import (
)
func Test_ParseHCPPackerRegistryBlock(t *testing.T) {
os.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "hcp-par-test")
defer os.Unsetenv("HCP_PACKER_BUILD_FINGERPRINT")
t.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "hcp-par-test")
defaultParser := getBasicParser()

@ -2,16 +2,13 @@ package registry
import (
"context"
"os"
"testing"
"github.com/hashicorp/hcp-sdk-go/clients/cloud-packer-service/stable/2021-04-30/models"
)
func TestInitialize_NewBucketNewIteration(t *testing.T) {
//nolint:errcheck
os.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "testnumber")
defer os.Unsetenv("HCP_PACKER_BUILD_FINGERPRINT")
t.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "testnumber")
mockService := NewMockPackerClientService()
b := &Bucket{
@ -65,9 +62,7 @@ func TestInitialize_NewBucketNewIteration(t *testing.T) {
}
func TestInitialize_ExistingBucketNewIteration(t *testing.T) {
//nolint:errcheck
os.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "testnumber")
defer os.Unsetenv("HCP_PACKER_BUILD_FINGERPRINT")
t.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "testnumber")
mockService := NewMockPackerClientService()
mockService.BucketAlreadyExist = true
@ -122,9 +117,7 @@ func TestInitialize_ExistingBucketNewIteration(t *testing.T) {
}
func TestInitialize_ExistingBucketExistingIteration(t *testing.T) {
//nolint:errcheck
os.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "testnumber")
defer os.Unsetenv("HCP_PACKER_BUILD_FINGERPRINT")
t.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "testnumber")
mockService := NewMockPackerClientService()
mockService.BucketAlreadyExist = true
mockService.IterationAlreadyExist = true
@ -194,9 +187,7 @@ func TestInitialize_ExistingBucketExistingIteration(t *testing.T) {
}
func TestInitialize_ExistingBucketCompleteIteration(t *testing.T) {
//nolint:errcheck
os.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "testnumber")
defer os.Unsetenv("HCP_PACKER_BUILD_FINGERPRINT")
t.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "testnumber")
mockService := NewMockPackerClientService()
mockService.BucketAlreadyExist = true
mockService.IterationAlreadyExist = true
@ -242,9 +233,7 @@ func TestInitialize_ExistingBucketCompleteIteration(t *testing.T) {
}
func TestUpdateBuildStatus(t *testing.T) {
//nolint:errcheck
os.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "testnumber")
defer os.Unsetenv("HCP_PACKER_BUILD_FINGERPRINT")
t.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "testnumber")
mockService := NewMockPackerClientService()
mockService.BucketAlreadyExist = true
mockService.IterationAlreadyExist = true
@ -299,9 +288,7 @@ func TestUpdateBuildStatus(t *testing.T) {
}
func TestUpdateBuildStatus_DONENoImages(t *testing.T) {
//nolint:errcheck
os.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "testnumber")
defer os.Unsetenv("HCP_PACKER_BUILD_FINGERPRINT")
t.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "testnumber")
mockService := NewMockPackerClientService()
mockService.BucketAlreadyExist = true
mockService.IterationAlreadyExist = true

@ -2,7 +2,6 @@ package registry
import (
"context"
"os"
"strconv"
"testing"
@ -10,11 +9,7 @@ import (
)
func createInitialTestBucket(t testing.TB) *Bucket {
oldEnv := os.Getenv("HCP_PACKER_BUILD_FINGERPRINT")
os.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "no-fingerprint-here")
defer func() {
os.Setenv("HCP_PACKER_BUILD_FINGERPRINT", oldEnv)
}()
t.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "no-fingerprint-here")
t.Helper()
bucket, err := NewBucketWithIteration(IterationOptions{})
@ -283,8 +278,7 @@ func TestBucket_PopulateIteration(t *testing.T) {
tt := tt
t.Run(tt.desc, func(t *testing.T) {
os.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "test-run-"+strconv.Itoa(i))
defer os.Unsetenv("HCP_PACKER_BUILD_FINGERPRINT")
t.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "test-run-"+strconv.Itoa(i))
mockService := NewMockPackerClientService()
mockService.BucketAlreadyExist = true

@ -13,17 +13,14 @@ func TestNewIteration(t *testing.T) {
name string
fingerprint string
opts IterationOptions
setupFn func() func()
setupFn func(t *testing.T)
errorExpected bool
}{
{
name: "using fingerprint env variable",
fingerprint: "6825d1ad0d5e",
setupFn: func() func() {
os.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "6825d1ad0d5e")
return func() {
os.Unsetenv("HCP_PACKER_BUILD_FINGERPRINT")
}
setupFn: func(t *testing.T) {
t.Setenv("HCP_PACKER_BUILD_FINGERPRINT", "6825d1ad0d5e")
},
},
{
@ -32,7 +29,7 @@ func TestNewIteration(t *testing.T) {
opts: IterationOptions{
TemplateBaseDir: tempdir("4ec004e18e"),
},
setupFn: func() func() {
setupFn: func(t *testing.T) {
//nolint:errcheck
git.PlainClone(tempdir("4ec004e18e"), false, &git.CloneOptions{
// Archived repo
@ -40,10 +37,10 @@ func TestNewIteration(t *testing.T) {
Depth: 1,
})
return func() {
t.Cleanup(func() {
//nolint:errcheck
os.RemoveAll(tempdir("4ec004e18e"))
}
})
},
},
{
@ -51,13 +48,13 @@ func TestNewIteration(t *testing.T) {
opts: IterationOptions{
TemplateBaseDir: tempdir("empty-init"),
},
setupFn: func() func() {
setupFn: func(t *testing.T) {
//nolint:errcheck
git.PlainInit(tempdir("empty-init"), false)
return func() {
t.Cleanup(func() {
//nolint:errcheck
os.RemoveAll(tempdir("empty-init"))
}
})
},
errorExpected: true,
},
@ -74,8 +71,7 @@ func TestNewIteration(t *testing.T) {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if tt.setupFn != nil {
cleanup := tt.setupFn()
defer cleanup()
tt.setupFn(t)
}
i, err := NewIteration(tt.opts)

@ -116,8 +116,7 @@ func TestCoreBuild_basicInterpolated(t *testing.T) {
}
func TestCoreBuild_env(t *testing.T) {
os.Setenv("PACKER_TEST_ENV", "test")
defer os.Setenv("PACKER_TEST_ENV", "")
t.Setenv("PACKER_TEST_ENV", "test")
config := TestCoreConfig(t)
testCoreTemplate(t, config, fixtureDir("build-env.json"))
@ -148,8 +147,7 @@ func TestCoreBuild_env(t *testing.T) {
}
func TestCoreBuild_IgnoreTemplateVariables(t *testing.T) {
os.Setenv("PACKER_TEST_ENV", "test")
defer os.Setenv("PACKER_TEST_ENV", "")
t.Setenv("PACKER_TEST_ENV", "test")
config := TestCoreConfig(t)
testCoreTemplate(t, config, fixtureDir("build-ignore-template-variable.json"))
@ -733,10 +731,10 @@ func TestIsDoneInterpolating(t *testing.T) {
}
func TestEnvAndFileVars(t *testing.T) {
os.Setenv("INTERPOLATE_TEST_ENV_1", "bulbasaur")
os.Setenv("INTERPOLATE_TEST_ENV_3", "/path/to/nowhere")
os.Setenv("INTERPOLATE_TEST_ENV_2", "5")
os.Setenv("INTERPOLATE_TEST_ENV_4", "bananas")
t.Setenv("INTERPOLATE_TEST_ENV_1", "bulbasaur")
t.Setenv("INTERPOLATE_TEST_ENV_3", "/path/to/nowhere")
t.Setenv("INTERPOLATE_TEST_ENV_2", "5")
t.Setenv("INTERPOLATE_TEST_ENV_4", "bananas")
f, err := os.Open(fixtureDir("complex-recursed-env-user-var-file.json"))
if err != nil {
@ -778,12 +776,6 @@ func TestEnvAndFileVars(t *testing.T) {
expected[k], k, v)
}
}
// Clean up env vars
os.Unsetenv("INTERPOLATE_TEST_ENV_1")
os.Unsetenv("INTERPOLATE_TEST_ENV_3")
os.Unsetenv("INTERPOLATE_TEST_ENV_2")
os.Unsetenv("INTERPOLATE_TEST_ENV_4")
}
func testCoreTemplate(t *testing.T, c *CoreConfig, p string) {

@ -27,8 +27,7 @@ func newPluginConfig() PluginConfig {
func TestDiscoverReturnsIfMagicCookieSet(t *testing.T) {
config := newPluginConfig()
os.Setenv(pluginsdk.MagicCookieKey, pluginsdk.MagicCookieValue)
defer os.Unsetenv(pluginsdk.MagicCookieKey)
t.Setenv(pluginsdk.MagicCookieKey, pluginsdk.MagicCookieValue)
err := config.Discover()
if err != nil {
@ -51,8 +50,7 @@ func TestEnvVarPackerPluginPath(t *testing.T) {
defer cleanUpFunc()
// Add temp dir to path.
os.Setenv("PACKER_PLUGIN_PATH", dir)
defer os.Unsetenv("PACKER_PLUGIN_PATH")
t.Setenv("PACKER_PLUGIN_PATH", dir)
config := newPluginConfig()
@ -94,8 +92,7 @@ func TestEnvVarPackerPluginPath_MultiplePaths(t *testing.T) {
pluginPath := dir + pathsep + decoyDir
// Add temp dir to path.
os.Setenv("PACKER_PLUGIN_PATH", pluginPath)
defer os.Unsetenv("PACKER_PLUGIN_PATH")
t.Setenv("PACKER_PLUGIN_PATH", pluginPath)
config := newPluginConfig()
@ -137,8 +134,7 @@ func TestDiscoverDatasource(t *testing.T) {
pluginPath := dir + pathsep + decoyDir
// Add temp dir to path.
os.Setenv("PACKER_PLUGIN_PATH", pluginPath)
defer os.Unsetenv("PACKER_PLUGIN_PATH")
t.Setenv("PACKER_PLUGIN_PATH", pluginPath)
config := newPluginConfig()
@ -293,7 +289,7 @@ func createMockPlugins(t *testing.T, plugins map[string]pluginsdk.Set) {
}
}
}
os.Setenv("PACKER_PLUGIN_PATH", pluginDir)
t.Setenv("PACKER_PLUGIN_PATH", pluginDir)
}
func createMockChecksumFile(t testing.TB, filePath string) {
@ -366,7 +362,7 @@ func createMockInstalledPlugins(t *testing.T, plugins map[string]pluginsdk.Set,
}
}
}
os.Setenv("PACKER_PLUGIN_PATH", pluginDir)
t.Setenv("PACKER_PLUGIN_PATH", pluginDir)
}
func getFormattedInstalledPluginSuffix() string {

@ -2,7 +2,6 @@ package packer
import (
"bytes"
"os"
"strings"
"testing"
@ -86,9 +85,7 @@ func TestColoredUi_noColorEnv(t *testing.T) {
ui := &ColoredUi{UiColorYellow, UiColorRed, bufferUi, &UiProgressBar{}}
// Set the env var to get rid of the color
oldenv := os.Getenv("PACKER_NO_COLOR")
os.Setenv("PACKER_NO_COLOR", "1")
defer os.Setenv("PACKER_NO_COLOR", oldenv)
t.Setenv("PACKER_NO_COLOR", "1")
ui.Say("foo")
result := readWriter(bufferUi)

Loading…
Cancel
Save