diff --git a/internal/backend/local/backend_test.go b/internal/backend/local/backend_test.go index d39890fa23..eff227466d 100644 --- a/internal/backend/local/backend_test.go +++ b/internal/backend/local/backend_test.go @@ -2,7 +2,6 @@ package local import ( "errors" - "io/ioutil" "os" "path/filepath" "reflect" @@ -21,7 +20,7 @@ func TestLocal_impl(t *testing.T) { } func TestLocal_backend(t *testing.T) { - defer testTmpDir(t)() + testTmpDir(t) b := New() backend.TestBackendStates(t, b) backend.TestBackendStateLocks(t, b, b) @@ -90,7 +89,7 @@ func TestLocal_StatePaths(t *testing.T) { } func TestLocal_addAndRemoveStates(t *testing.T) { - defer testTmpDir(t)() + testTmpDir(t) dflt := backend.DefaultStateName expectedStates := []string{dflt} @@ -226,12 +225,10 @@ func TestLocal_multiStateBackend(t *testing.T) { } } -// change into a tmp dir and return a deferable func to change back and cleanup -func testTmpDir(t *testing.T) func() { - tmp, err := ioutil.TempDir("", "tf") - if err != nil { - t.Fatal(err) - } +// testTmpDir changes into a tmp dir and change back automatically when the test +// and all its subtests complete. +func testTmpDir(t *testing.T) { + tmp := t.TempDir() old, err := os.Getwd() if err != nil { @@ -242,9 +239,8 @@ func testTmpDir(t *testing.T) func() { t.Fatal(err) } - return func() { + t.Cleanup(func() { // ignore errors and try to clean up os.Chdir(old) - os.RemoveAll(tmp) - } + }) } diff --git a/internal/cloud/e2e/main_test.go b/internal/cloud/e2e/main_test.go index 4bfe614291..ae78519b3a 100644 --- a/internal/cloud/e2e/main_test.go +++ b/internal/cloud/e2e/main_test.go @@ -87,19 +87,14 @@ func testRunner(t *testing.T, cases testCases, orgCount int, tfEnvFlags ...strin } defer exp.Close() - tmpDir, err := ioutil.TempDir("", "terraform-test") - if err != nil { - subtest.Fatal(err) - } - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() - tf := e2e.NewBinary(terraformBin, tmpDir) + tf := e2e.NewBinary(t, terraformBin, tmpDir) tfEnvFlags = append(tfEnvFlags, "TF_LOG=INFO") tfEnvFlags = append(tfEnvFlags, cliConfigFileEnv) for _, env := range tfEnvFlags { tf.AddEnv(env) } - defer tf.Close() var orgName string for index, op := range tc.operations { diff --git a/internal/command/apply_destroy_test.go b/internal/command/apply_destroy_test.go index f06ee6baa9..27aaff9017 100644 --- a/internal/command/apply_destroy_test.go +++ b/internal/command/apply_destroy_test.go @@ -18,9 +18,8 @@ import ( func TestApply_destroy(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := states.BuildState(func(s *states.SyncState) { @@ -123,9 +122,8 @@ func TestApply_destroy(t *testing.T) { func TestApply_destroyApproveNo(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Create some existing state @@ -192,9 +190,8 @@ func TestApply_destroyApproveNo(t *testing.T) { func TestApply_destroyApproveYes(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Create some existing state @@ -264,9 +261,8 @@ func TestApply_destroyApproveYes(t *testing.T) { func TestApply_destroyLockedState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := states.BuildState(func(s *states.SyncState) { @@ -288,7 +284,7 @@ func TestApply_destroyLockedState(t *testing.T) { }) statePath := testStateFile(t, originalState) - unlock, err := testLockState(testDataDir, statePath) + unlock, err := testLockState(t, testDataDir, statePath) if err != nil { t.Fatal(err) } @@ -323,9 +319,8 @@ func TestApply_destroyLockedState(t *testing.T) { func TestApply_destroyPlan(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() planPath := testPlanFileNoop(t) @@ -356,9 +351,8 @@ func TestApply_destroyPlan(t *testing.T) { func TestApply_destroyPath(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := applyFixtureProvider() @@ -391,9 +385,8 @@ func TestApply_destroyPath(t *testing.T) { // dependencies. func TestApply_destroyTargetedDependencies(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-destroy-targeted"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := states.BuildState(func(s *states.SyncState) { @@ -526,9 +519,8 @@ func TestApply_destroyTargetedDependencies(t *testing.T) { // leaf node, expecting the other resources to remain. func TestApply_destroyTargeted(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-destroy-targeted"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := states.BuildState(func(s *states.SyncState) { diff --git a/internal/command/apply_test.go b/internal/command/apply_test.go index b2306623cb..dba6599479 100644 --- a/internal/command/apply_test.go +++ b/internal/command/apply_test.go @@ -34,9 +34,8 @@ import ( func TestApply(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) @@ -73,9 +72,8 @@ func TestApply(t *testing.T) { func TestApply_path(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := applyFixtureProvider() @@ -104,9 +102,8 @@ func TestApply_path(t *testing.T) { func TestApply_approveNo(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) @@ -148,9 +145,8 @@ func TestApply_approveNo(t *testing.T) { func TestApply_approveYes(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) @@ -196,14 +192,13 @@ func TestApply_approveYes(t *testing.T) { // test apply with locked state func TestApply_lockedState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) - unlock, err := testLockState(testDataDir, statePath) + unlock, err := testLockState(t, testDataDir, statePath) if err != nil { t.Fatal(err) } @@ -236,14 +231,13 @@ func TestApply_lockedState(t *testing.T) { // test apply with locked state, waiting for unlock func TestApply_lockedStateWait(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) - unlock, err := testLockState(testDataDir, statePath) + unlock, err := testLockState(t, testDataDir, statePath) if err != nil { t.Fatal(err) } @@ -281,9 +275,8 @@ func TestApply_lockedStateWait(t *testing.T) { // concurrent calls to ApplyResourceChange. func TestApply_parallelism(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("parallelism"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) @@ -376,9 +369,8 @@ func TestApply_parallelism(t *testing.T) { func TestApply_configInvalid(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-config-invalid"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -403,9 +395,8 @@ func TestApply_configInvalid(t *testing.T) { func TestApply_defaultState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := filepath.Join(td, DefaultStateFilename) @@ -456,9 +447,8 @@ func TestApply_defaultState(t *testing.T) { func TestApply_error(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-error"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) @@ -534,9 +524,8 @@ func TestApply_error(t *testing.T) { func TestApply_input(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-input"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Disable test mode so input would be asked @@ -585,9 +574,8 @@ result = foo // should still ask for the unset ones by default (with -input=true) func TestApply_inputPartial(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-input-partial"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Disable test mode so input would be asked @@ -632,9 +620,8 @@ foo = foovalue func TestApply_noArgs(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) @@ -790,8 +777,7 @@ func TestApply_plan_remoteState(t *testing.T) { // Disable test mode so input would be asked test = false defer func() { test = true }() - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + tmp := testCwd(t) remoteStatePath := filepath.Join(tmp, DefaultDataDir, DefaultStateFilename) if err := os.MkdirAll(filepath.Dir(remoteStatePath), 0755); err != nil { t.Fatalf("err: %s", err) @@ -963,9 +949,8 @@ func TestApply_planNoModuleFiles(t *testing.T) { func TestApply_refresh(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := states.BuildState(func(s *states.SyncState) { @@ -1031,9 +1016,8 @@ func TestApply_refresh(t *testing.T) { func TestApply_refreshFalse(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := states.BuildState(func(s *states.SyncState) { @@ -1081,9 +1065,8 @@ func TestApply_refreshFalse(t *testing.T) { } func TestApply_shutdown(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-shutdown"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() cancelled := make(chan struct{}) @@ -1170,9 +1153,8 @@ func TestApply_shutdown(t *testing.T) { func TestApply_state(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := states.BuildState(func(s *states.SyncState) { @@ -1265,9 +1247,8 @@ func TestApply_state(t *testing.T) { func TestApply_stateNoExist(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := applyFixtureProvider() @@ -1291,9 +1272,8 @@ func TestApply_stateNoExist(t *testing.T) { func TestApply_sensitiveOutput(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-sensitive-output"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -1329,9 +1309,8 @@ func TestApply_sensitiveOutput(t *testing.T) { func TestApply_vars(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-vars"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) @@ -1387,9 +1366,8 @@ func TestApply_vars(t *testing.T) { func TestApply_varFile(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-vars"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() varFilePath := testTempFile(t) @@ -1450,9 +1428,8 @@ func TestApply_varFile(t *testing.T) { func TestApply_varFileDefault(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-vars"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() varFilePath := filepath.Join(td, "terraform.tfvars") @@ -1512,9 +1489,8 @@ func TestApply_varFileDefault(t *testing.T) { func TestApply_varFileDefaultJSON(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-vars"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() varFilePath := filepath.Join(td, "terraform.tfvars.json") @@ -1574,9 +1550,8 @@ func TestApply_varFileDefaultJSON(t *testing.T) { func TestApply_backup(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := states.BuildState(func(s *states.SyncState) { @@ -1652,9 +1627,8 @@ func TestApply_backup(t *testing.T) { func TestApply_disableBackup(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := testState() @@ -1732,9 +1706,8 @@ func TestApply_disableBackup(t *testing.T) { // Test that the Terraform env is passed through func TestApply_terraformEnv(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-terraform-env"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) @@ -1770,9 +1743,8 @@ output = default // Test that the Terraform env is passed through func TestApply_terraformEnvNonDefault(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-terraform-env"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Create new env @@ -1832,9 +1804,8 @@ output = test // Config with multiple resources, targeting apply of a subset func TestApply_targeted(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-targeted"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -1921,9 +1892,8 @@ func TestApply_targetFlagsDiags(t *testing.T) { } func TestApply_replace(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-replace"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := states.BuildState(func(s *states.SyncState) { @@ -2009,9 +1979,8 @@ func TestApply_replace(t *testing.T) { func TestApply_pluginPath(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) @@ -2050,9 +2019,8 @@ func TestApply_pluginPath(t *testing.T) { func TestApply_jsonGoldenReference(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) @@ -2166,9 +2134,8 @@ func TestApply_jsonGoldenReference(t *testing.T) { func TestApply_warnings(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() diff --git a/internal/command/autocomplete_test.go b/internal/command/autocomplete_test.go index 865afcbead..5f0c5ef916 100644 --- a/internal/command/autocomplete_test.go +++ b/internal/command/autocomplete_test.go @@ -12,9 +12,8 @@ import ( func TestMetaCompletePredictWorkspaceName(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() // make sure a vars file doesn't interfere diff --git a/internal/command/cliconfig/credentials_test.go b/internal/command/cliconfig/credentials_test.go index 22a9e3f830..f7c12ed0ad 100644 --- a/internal/command/cliconfig/credentials_test.go +++ b/internal/command/cliconfig/credentials_test.go @@ -1,9 +1,7 @@ package cliconfig import ( - "io/ioutil" "net/http" - "os" "path/filepath" "testing" @@ -88,11 +86,7 @@ func TestCredentialsForHost(t *testing.T) { } func TestCredentialsStoreForget(t *testing.T) { - d, err := ioutil.TempDir("", "terraform-cliconfig-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(d) + d := t.TempDir() mockCredsFilename := filepath.Join(d, "credentials.tfrc.json") diff --git a/internal/command/command_test.go b/internal/command/command_test.go index 205e989dbf..50ab641cb3 100644 --- a/internal/command/command_test.go +++ b/internal/command/command_test.go @@ -53,9 +53,6 @@ var ( testDataDir = "./testdata" ) -// a top level temp directory which will be cleaned after all tests -var testingDir string - func init() { test = true @@ -74,45 +71,18 @@ func init() { if err != nil { panic(err) } - - testingDir, err = ioutil.TempDir(testingDir, "tf") - if err != nil { - panic(err) - } } func TestMain(m *testing.M) { - defer os.RemoveAll(testingDir) - // Make sure backend init is initialized, since our tests tend to assume it. backendInit.Init(nil) os.Exit(m.Run()) } -func tempDir(t *testing.T) string { - t.Helper() - - dir, err := ioutil.TempDir(testingDir, "tf") - if err != nil { - t.Fatalf("err: %s", err) - } - - dir, err = filepath.EvalSymlinks(dir) - if err != nil { - t.Fatal(err) - } - - if err := os.RemoveAll(dir); err != nil { - t.Fatalf("err: %s", err) - } - - return dir -} - // tempWorkingDir constructs a workdir.Dir object referring to a newly-created -// temporary directory, and returns that object along with a cleanup function -// to call once the calling test is complete. +// temporary directory. The temporary directory is automatically removed when +//the test and all its subtests complete. // // Although workdir.Dir is built to support arbitrary base directories, the // not-yet-migrated behaviors in command.Meta tend to expect the root module @@ -120,25 +90,18 @@ func tempDir(t *testing.T) string { // to use the result inside a command.Meta object you must use a pattern // similar to the following when initializing your test: // -// wd, cleanup := tempWorkingDir(t) -// defer cleanup() +// wd := tempWorkingDir(t) // defer testChdir(t, wd.RootModuleDir())() // // Note that testChdir modifies global state for the test process, and so a // test using this pattern must never call t.Parallel(). -func tempWorkingDir(t *testing.T) (*workdir.Dir, func() error) { +func tempWorkingDir(t *testing.T) *workdir.Dir { t.Helper() - dirPath, err := os.MkdirTemp("", "tf-command-test-") - if err != nil { - t.Fatal(err) - } - done := func() error { - return os.RemoveAll(dirPath) - } + dirPath := t.TempDir() t.Logf("temporary directory %s", dirPath) - return workdir.NewDir(dirPath), done + return workdir.NewDir(dirPath) } // tempWorkingDirFixture is like tempWorkingDir but it also copies the content @@ -558,8 +521,7 @@ func testTempFile(t *testing.T) string { func testTempDir(t *testing.T) string { t.Helper() - d := t.TempDir() - d, err := filepath.EvalSymlinks(d) + d, err := filepath.EvalSymlinks(t.TempDir()) if err != nil { t.Fatal(err) } @@ -587,15 +549,13 @@ func testChdir(t *testing.T, new string) func() { } } -// testCwd is used to change the current working directory -// into a test directory that should be removed after -func testCwd(t *testing.T) (string, string) { +// testCwd is used to change the current working directory into a temporary +// directory. The cleanup is performed automatically after the test and all its +// subtests complete. +func testCwd(t *testing.T) string { t.Helper() - tmp, err := ioutil.TempDir(testingDir, "tf") - if err != nil { - t.Fatalf("err: %v", err) - } + tmp := t.TempDir() cwd, err := os.Getwd() if err != nil { @@ -606,20 +566,13 @@ func testCwd(t *testing.T) (string, string) { t.Fatalf("err: %v", err) } - return tmp, cwd -} + t.Cleanup(func() { + if err := os.Chdir(cwd); err != nil { + t.Fatalf("err: %v", err) + } + }) -// testFixCwd is used to as a defer to testDir -func testFixCwd(t *testing.T, tmp, cwd string) { - t.Helper() - - if err := os.Chdir(cwd); err != nil { - t.Fatalf("err: %v", err) - } - - if err := os.RemoveAll(tmp); err != nil { - t.Fatalf("err: %v", err) - } + return tmp } // testStdinPipe changes os.Stdin to be a pipe that sends the data from @@ -866,15 +819,9 @@ func testRemoteState(t *testing.T, s *states.State, c int) (*legacy.State, *http // deferFunc should be called in the caller to properly unlock the file. // Since many tests change the working directory, the sourcedir argument must be // supplied to locate the statelocker.go source. -func testLockState(sourceDir, path string) (func(), error) { +func testLockState(t *testing.T, sourceDir, path string) (func(), error) { // build and run the binary ourselves so we can quickly terminate it for cleanup - buildDir, err := ioutil.TempDir(testingDir, "locker") - if err != nil { - return nil, err - } - cleanFunc := func() { - os.RemoveAll(buildDir) - } + buildDir := t.TempDir() source := filepath.Join(sourceDir, "statelocker.go") lockBin := filepath.Join(buildDir, "statelocker") @@ -884,14 +831,12 @@ func testLockState(sourceDir, path string) (func(), error) { out, err := cmd.CombinedOutput() if err != nil { - cleanFunc() return nil, fmt.Errorf("%s %s", err, out) } locker := exec.Command(lockBin, path) pr, pw, err := os.Pipe() if err != nil { - cleanFunc() return nil, err } defer pr.Close() @@ -903,7 +848,6 @@ func testLockState(sourceDir, path string) (func(), error) { return nil, err } deferFunc := func() { - cleanFunc() locker.Process.Signal(syscall.SIGTERM) locker.Wait() } diff --git a/internal/command/console_test.go b/internal/command/console_test.go index 8cd13ef570..13b743547e 100644 --- a/internal/command/console_test.go +++ b/internal/command/console_test.go @@ -3,7 +3,6 @@ package command import ( "bytes" "io/ioutil" - "os" "path/filepath" "strings" "testing" @@ -22,8 +21,7 @@ import ( // This file still contains some tests using the stdin-based input. func TestConsole_basic(t *testing.T) { - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) p := testProvider() ui := cli.NewMockUi() @@ -54,9 +52,8 @@ func TestConsole_basic(t *testing.T) { } func TestConsole_tfvars(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-vars"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Write a terraform.tvars @@ -113,9 +110,8 @@ func TestConsole_unsetRequiredVars(t *testing.T) { // // This test fixture includes variable "foo" {}, which we are // intentionally not setting here. - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-vars"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -158,9 +154,8 @@ func TestConsole_unsetRequiredVars(t *testing.T) { } func TestConsole_variables(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("variables"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -201,9 +196,8 @@ func TestConsole_variables(t *testing.T) { } func TestConsole_modules(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("modules"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := applyFixtureProvider() diff --git a/internal/command/e2etest/automation_test.go b/internal/command/e2etest/automation_test.go index 1294332993..02652927d7 100644 --- a/internal/command/e2etest/automation_test.go +++ b/internal/command/e2etest/automation_test.go @@ -26,8 +26,7 @@ func TestPlanApplyInAutomation(t *testing.T) { skipIfCannotAccessNetwork(t) fixturePath := filepath.Join("testdata", "full-workflow-null") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) // We advertise that _any_ non-empty value works, so we'll test something // unconventional here. @@ -134,8 +133,7 @@ func TestAutoApplyInAutomation(t *testing.T) { skipIfCannotAccessNetwork(t) fixturePath := filepath.Join("testdata", "full-workflow-null") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) // We advertise that _any_ non-empty value works, so we'll test something // unconventional here. @@ -201,8 +199,7 @@ func TestPlanOnlyInAutomation(t *testing.T) { skipIfCannotAccessNetwork(t) fixturePath := filepath.Join("testdata", "full-workflow-null") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) // We advertise that _any_ non-empty value works, so we'll test something // unconventional here. diff --git a/internal/command/e2etest/init_test.go b/internal/command/e2etest/init_test.go index 0e793c1515..371ee0e1e9 100644 --- a/internal/command/e2etest/init_test.go +++ b/internal/command/e2etest/init_test.go @@ -25,8 +25,7 @@ func TestInitProviders(t *testing.T) { skipIfCannotAccessNetwork(t) fixturePath := filepath.Join("testdata", "template-provider") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) stdout, stderr, err := tf.Run("init") if err != nil { @@ -59,8 +58,7 @@ func TestInitProvidersInternal(t *testing.T) { // provider is internal to the core terraform binary. fixturePath := filepath.Join("testdata", "terraform-provider") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) stdout, stderr, err := tf.Run("init") if err != nil { @@ -99,8 +97,7 @@ func TestInitProvidersVendored(t *testing.T) { skipIfCannotAccessNetwork(t) fixturePath := filepath.Join("testdata", "vendored-provider") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) // Our fixture dir has a generic os_arch dir, which we need to customize // to the actual OS/arch where this test is running in order to get the @@ -143,14 +140,13 @@ func TestInitProvidersLocalOnly(t *testing.T) { // the test fixture.) fixturePath := filepath.Join("testdata", "local-only-provider") - tf := e2e.NewBinary(terraformBin, fixturePath) + tf := e2e.NewBinary(t, terraformBin, fixturePath) // If you run this test on a workstation with a plugin-cache directory // configured, it will leave a bad directory behind and terraform init will // not work until you remove it. // // To avoid this, we will "zero out" any existing cli config file. tf.AddEnv("TF_CLI_CONFIG_FILE=\"\"") - defer tf.Close() // Our fixture dir has a generic os_arch dir, which we need to customize // to the actual OS/arch where this test is running in order to get the @@ -194,8 +190,7 @@ func TestInitProvidersCustomMethod(t *testing.T) { for _, configFile := range []string{"cliconfig.tfrc", "cliconfig.tfrc.json"} { t.Run(configFile, func(t *testing.T) { fixturePath := filepath.Join("testdata", "custom-provider-install-method") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) // Our fixture dir has a generic os_arch dir, which we need to customize // to the actual OS/arch where this test is running in order to get the @@ -240,8 +235,7 @@ func TestInitProviders_pluginCache(t *testing.T) { skipIfCannotAccessNetwork(t) fixturePath := filepath.Join("testdata", "plugin-cache") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) // Our fixture dir has a generic os_arch dir, which we need to customize // to the actual OS/arch where this test is running in order to get the @@ -297,8 +291,7 @@ func TestInit_fromModule(t *testing.T) { skipIfCannotAccessNetwork(t) fixturePath := filepath.Join("testdata", "empty") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) cmd := tf.Cmd("init", "-from-module=hashicorp/vault/aws") cmd.Stdin = nil @@ -331,8 +324,7 @@ func TestInitProviderNotFound(t *testing.T) { skipIfCannotAccessNetwork(t) fixturePath := filepath.Join("testdata", "provider-not-found") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) t.Run("registry provider not found", func(t *testing.T) { _, stderr, err := tf.Run("init", "-no-color") @@ -402,8 +394,7 @@ func TestInitProviderWarnings(t *testing.T) { skipIfCannotAccessNetwork(t) fixturePath := filepath.Join("testdata", "provider-warnings") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) stdout, _, err := tf.Run("init") if err == nil { diff --git a/internal/command/e2etest/primary_test.go b/internal/command/e2etest/primary_test.go index de4ad95b2c..bd570dd4ff 100644 --- a/internal/command/e2etest/primary_test.go +++ b/internal/command/e2etest/primary_test.go @@ -29,8 +29,7 @@ func TestPrimarySeparatePlan(t *testing.T) { skipIfCannotAccessNetwork(t) fixturePath := filepath.Join("testdata", "full-workflow-null") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) //// INIT stdout, stderr, err := tf.Run("init") @@ -150,8 +149,7 @@ func TestPrimaryChdirOption(t *testing.T) { // safe to run it even when network access is disallowed. fixturePath := filepath.Join("testdata", "chdir-option") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) //// INIT _, stderr, err := tf.Run("-chdir=subdir", "init") diff --git a/internal/command/e2etest/provider_dev_test.go b/internal/command/e2etest/provider_dev_test.go index 1aac10bcd5..1f6c9fb0d9 100644 --- a/internal/command/e2etest/provider_dev_test.go +++ b/internal/command/e2etest/provider_dev_test.go @@ -28,8 +28,7 @@ func TestProviderDevOverrides(t *testing.T) { } t.Parallel() - tf := e2e.NewBinary(terraformBin, "testdata/provider-dev-override") - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, "testdata/provider-dev-override") // In order to do a decent end-to-end test for this case we will need a // real enough provider plugin to try to run and make sure we are able diff --git a/internal/command/e2etest/provider_plugin_test.go b/internal/command/e2etest/provider_plugin_test.go index c8ac7fe3f6..8b3aa3af7d 100644 --- a/internal/command/e2etest/provider_plugin_test.go +++ b/internal/command/e2etest/provider_plugin_test.go @@ -23,8 +23,7 @@ func TestProviderProtocols(t *testing.T) { } t.Parallel() - tf := e2e.NewBinary(terraformBin, "testdata/provider-plugin") - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, "testdata/provider-plugin") // In order to do a decent end-to-end test for this case we will need a real // enough provider plugin to try to run and make sure we are able to diff --git a/internal/command/e2etest/providers_mirror_test.go b/internal/command/e2etest/providers_mirror_test.go index cc0b22f860..f237fa6513 100644 --- a/internal/command/e2etest/providers_mirror_test.go +++ b/internal/command/e2etest/providers_mirror_test.go @@ -1,7 +1,6 @@ package e2etest import ( - "io/ioutil" "os" "path/filepath" "sort" @@ -23,16 +22,11 @@ func TestTerraformProvidersMirror(t *testing.T) { // allowed. skipIfCannotAccessNetwork(t) - outputDir, err := ioutil.TempDir("", "terraform-e2etest-providers-mirror") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(outputDir) + outputDir := t.TempDir() t.Logf("creating mirror directory in %s", outputDir) fixturePath := filepath.Join("testdata", "terraform-providers-mirror") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) stdout, stderr, err := tf.Run("providers", "mirror", "-platform=linux_amd64", "-platform=windows_386", outputDir) if err != nil { diff --git a/internal/command/e2etest/providers_tamper_test.go b/internal/command/e2etest/providers_tamper_test.go index 0c285c1f20..0f4e831220 100644 --- a/internal/command/e2etest/providers_tamper_test.go +++ b/internal/command/e2etest/providers_tamper_test.go @@ -27,8 +27,7 @@ func TestProviderTampering(t *testing.T) { skipIfCannotAccessNetwork(t) fixturePath := filepath.Join("testdata", "provider-tampering-base") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) stdout, stderr, err := tf.Run("init") if err != nil { @@ -52,8 +51,7 @@ func TestProviderTampering(t *testing.T) { providerCacheDir := filepath.Join(".terraform", "providers") t.Run("cache dir totally gone", func(t *testing.T) { - tf := e2e.NewBinary(terraformBin, seedDir) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, seedDir) workDir := tf.WorkDir() err := os.RemoveAll(filepath.Join(workDir, ".terraform")) @@ -83,8 +81,7 @@ func TestProviderTampering(t *testing.T) { } }) t.Run("cache dir totally gone, explicit backend", func(t *testing.T) { - tf := e2e.NewBinary(terraformBin, seedDir) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, seedDir) workDir := tf.WorkDir() err := ioutil.WriteFile(filepath.Join(workDir, "backend.tf"), []byte(localBackendConfig), 0600) @@ -119,8 +116,7 @@ func TestProviderTampering(t *testing.T) { } }) t.Run("null plugin package modified before plan", func(t *testing.T) { - tf := e2e.NewBinary(terraformBin, seedDir) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, seedDir) workDir := tf.WorkDir() err := ioutil.WriteFile(filepath.Join(workDir, pluginExe), []byte("tamper"), 0600) @@ -140,8 +136,7 @@ func TestProviderTampering(t *testing.T) { } }) t.Run("version constraint changed in config before plan", func(t *testing.T) { - tf := e2e.NewBinary(terraformBin, seedDir) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, seedDir) workDir := tf.WorkDir() err := ioutil.WriteFile(filepath.Join(workDir, "provider-tampering-base.tf"), []byte(` @@ -170,8 +165,7 @@ func TestProviderTampering(t *testing.T) { } }) t.Run("lock file modified before plan", func(t *testing.T) { - tf := e2e.NewBinary(terraformBin, seedDir) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, seedDir) workDir := tf.WorkDir() // NOTE: We're just emptying out the lock file here because that's @@ -197,8 +191,7 @@ func TestProviderTampering(t *testing.T) { } }) t.Run("lock file modified after plan", func(t *testing.T) { - tf := e2e.NewBinary(terraformBin, seedDir) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, seedDir) workDir := tf.WorkDir() _, stderr, err := tf.Run("plan", "-out", "tfplan") @@ -223,8 +216,7 @@ func TestProviderTampering(t *testing.T) { } }) t.Run("plugin cache dir entirely removed after plan", func(t *testing.T) { - tf := e2e.NewBinary(terraformBin, seedDir) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, seedDir) workDir := tf.WorkDir() _, stderr, err := tf.Run("plan", "-out", "tfplan") @@ -246,8 +238,7 @@ func TestProviderTampering(t *testing.T) { } }) t.Run("null plugin package modified after plan", func(t *testing.T) { - tf := e2e.NewBinary(terraformBin, seedDir) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, seedDir) workDir := tf.WorkDir() _, stderr, err := tf.Run("plan", "-out", "tfplan") diff --git a/internal/command/e2etest/provisioner_plugin_test.go b/internal/command/e2etest/provisioner_plugin_test.go index 4ee75f9ceb..3f5d312b21 100644 --- a/internal/command/e2etest/provisioner_plugin_test.go +++ b/internal/command/e2etest/provisioner_plugin_test.go @@ -27,8 +27,7 @@ func TestProvisionerPlugin(t *testing.T) { // allowed. skipIfCannotAccessNetwork(t) - tf := e2e.NewBinary(terraformBin, "testdata/provisioner-plugin") - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, "testdata/provisioner-plugin") // In order to do a decent end-to-end test for this case we will need a // real enough provisioner plugin to try to run and make sure we are able diff --git a/internal/command/e2etest/provisioner_test.go b/internal/command/e2etest/provisioner_test.go index 928db17887..63d53576eb 100644 --- a/internal/command/e2etest/provisioner_test.go +++ b/internal/command/e2etest/provisioner_test.go @@ -17,8 +17,7 @@ func TestProvisioner(t *testing.T) { // allowed. skipIfCannotAccessNetwork(t) - tf := e2e.NewBinary(terraformBin, "testdata/provisioner") - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, "testdata/provisioner") //// INIT _, stderr, err := tf.Run("init") diff --git a/internal/command/e2etest/remote_state_test.go b/internal/command/e2etest/remote_state_test.go index 2230b0ab17..16b9d5a3f7 100644 --- a/internal/command/e2etest/remote_state_test.go +++ b/internal/command/e2etest/remote_state_test.go @@ -12,8 +12,7 @@ func TestTerraformProviderRead(t *testing.T) { t.Parallel() fixturePath := filepath.Join("testdata", "terraform-provider") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) //// INIT _, stderr, err := tf.Run("init") diff --git a/internal/command/e2etest/unmanaged_test.go b/internal/command/e2etest/unmanaged_test.go index 220fce42d1..e67e758a33 100644 --- a/internal/command/e2etest/unmanaged_test.go +++ b/internal/command/e2etest/unmanaged_test.go @@ -146,8 +146,7 @@ func TestUnmanagedSeparatePlan(t *testing.T) { t.Parallel() fixturePath := filepath.Join("testdata", "test-provider") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) reattachCh := make(chan *plugin.ReattachConfig) closeCh := make(chan struct{}) @@ -252,8 +251,7 @@ func TestUnmanagedSeparatePlan_proto5(t *testing.T) { t.Parallel() fixturePath := filepath.Join("testdata", "test-provider") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) reattachCh := make(chan *plugin.ReattachConfig) closeCh := make(chan struct{}) diff --git a/internal/command/e2etest/version_test.go b/internal/command/e2etest/version_test.go index 048c83020e..90c716aff4 100644 --- a/internal/command/e2etest/version_test.go +++ b/internal/command/e2etest/version_test.go @@ -19,8 +19,7 @@ func TestVersion(t *testing.T) { t.Parallel() fixturePath := filepath.Join("testdata", "empty") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) stdout, stderr, err := tf.Run("version") if err != nil { @@ -48,8 +47,7 @@ func TestVersionWithProvider(t *testing.T) { skipIfCannotAccessNetwork(t) fixturePath := filepath.Join("testdata", "template-provider") - tf := e2e.NewBinary(terraformBin, fixturePath) - defer tf.Close() + tf := e2e.NewBinary(t, terraformBin, fixturePath) // Initial run (before "init") should work without error but will not // include the provider version, since we've not "locked" one yet. diff --git a/internal/command/fmt_test.go b/internal/command/fmt_test.go index b2a4d3f39b..b163121c66 100644 --- a/internal/command/fmt_test.go +++ b/internal/command/fmt_test.go @@ -22,15 +22,10 @@ func TestFmt(t *testing.T) { t.Fatal(err) } - td, err := ioutil.TempDir("", "terraform-fmt-test") + tmpDir, err := filepath.EvalSymlinks(t.TempDir()) if err != nil { t.Fatal(err) } - tmpDir, err := filepath.EvalSymlinks(td) - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(td) for _, info := range entries { if info.IsDir() { diff --git a/internal/command/get_test.go b/internal/command/get_test.go index 77daeb0b4d..3f9cc300b5 100644 --- a/internal/command/get_test.go +++ b/internal/command/get_test.go @@ -32,8 +32,7 @@ func TestGet(t *testing.T) { } func TestGet_multipleArgs(t *testing.T) { - wd, cleanup := tempWorkingDir(t) - defer cleanup() + wd := tempWorkingDir(t) defer testChdir(t, wd.RootModuleDir())() ui := cli.NewMockUi() diff --git a/internal/command/graph_test.go b/internal/command/graph_test.go index 3fc2584ccd..f58f7103e9 100644 --- a/internal/command/graph_test.go +++ b/internal/command/graph_test.go @@ -14,9 +14,8 @@ import ( ) func TestGraph(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("graph"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -57,9 +56,8 @@ func TestGraph_multipleArgs(t *testing.T) { } func TestGraph_noArgs(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("graph"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -82,9 +80,8 @@ func TestGraph_noArgs(t *testing.T) { } func TestGraph_noConfig(t *testing.T) { - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -104,8 +101,7 @@ func TestGraph_noConfig(t *testing.T) { } func TestGraph_plan(t *testing.T) { - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) plan := &plans.Plan{ Changes: plans.NewChanges(), diff --git a/internal/command/import_test.go b/internal/command/import_test.go index 091646ecc2..f81658223b 100644 --- a/internal/command/import_test.go +++ b/internal/command/import_test.go @@ -160,9 +160,8 @@ func TestImport_providerConfig(t *testing.T) { // "remote" state provided by the "local" backend func TestImport_remoteState(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("import-provider-remote-state"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := "imported.tfstate" @@ -273,9 +272,8 @@ func TestImport_remoteState(t *testing.T) { // early failure on import should not leave stale lock func TestImport_initializationErrorShouldUnlock(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("import-provider-remote-state"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := "imported.tfstate" @@ -800,9 +798,8 @@ func TestImport_missingModuleConfig(t *testing.T) { } func TestImportModuleVarFile(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("import-module-var-file"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) @@ -875,9 +872,8 @@ func TestImportModuleVarFile(t *testing.T) { // uses the traversal foo.bar.baz in a local. A default value in the child // module of {} causes this local evaluation to error, breaking import. func TestImportModuleInputVariableEvaluation(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("import-module-input-variable"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testTempFile(t) diff --git a/internal/command/init_test.go b/internal/command/init_test.go index d23625cecb..c97be55faa 100644 --- a/internal/command/init_test.go +++ b/internal/command/init_test.go @@ -31,9 +31,8 @@ import ( func TestInit_empty(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -54,9 +53,8 @@ func TestInit_empty(t *testing.T) { func TestInit_multipleArgs(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -80,9 +78,8 @@ func TestInit_multipleArgs(t *testing.T) { func TestInit_fromModule_cwdDest(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, os.ModePerm) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -109,11 +106,10 @@ func TestInit_fromModule_cwdDest(t *testing.T) { // https://github.com/hashicorp/terraform/issues/518 func TestInit_fromModule_dstInSrc(t *testing.T) { - dir := tempDir(t) + dir := t.TempDir() if err := os.MkdirAll(dir, 0755); err != nil { t.Fatalf("err: %s", err) } - defer os.RemoveAll(dir) // Change to the temporary directory cwd, err := os.Getwd() @@ -161,9 +157,8 @@ func TestInit_fromModule_dstInSrc(t *testing.T) { func TestInit_get(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-get"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -190,9 +185,8 @@ func TestInit_get(t *testing.T) { func TestInit_getUpgradeModules(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-get"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -222,9 +216,8 @@ func TestInit_getUpgradeModules(t *testing.T) { func TestInit_backend(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -249,9 +242,8 @@ func TestInit_backend(t *testing.T) { func TestInit_backendUnset(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() { @@ -316,9 +308,8 @@ func TestInit_backendUnset(t *testing.T) { func TestInit_backendConfigFile(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-config-file"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() t.Run("good-config-file", func(t *testing.T) { @@ -453,9 +444,8 @@ func TestInit_backendConfigFile(t *testing.T) { func TestInit_backendConfigFilePowershellConfusion(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-config-file"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -489,9 +479,8 @@ func TestInit_backendConfigFilePowershellConfusion(t *testing.T) { func TestInit_backendReconfigure(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() providerSource, close := newMockProviderSource(t, map[string][]string{ @@ -537,9 +526,8 @@ func TestInit_backendReconfigure(t *testing.T) { func TestInit_backendConfigFileChange(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-config-file-change"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -566,9 +554,8 @@ func TestInit_backendConfigFileChange(t *testing.T) { func TestInit_backendMigrateWhileLocked(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-migrate-while-locked"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() providerSource, close := newMockProviderSource(t, map[string][]string{ @@ -599,7 +586,7 @@ func TestInit_backendMigrateWhileLocked(t *testing.T) { } // Lock the source state - unlock, err := testLockState(testDataDir, "local-state.tfstate") + unlock, err := testLockState(t, testDataDir, "local-state.tfstate") if err != nil { t.Fatal(err) } @@ -620,9 +607,8 @@ func TestInit_backendMigrateWhileLocked(t *testing.T) { func TestInit_backendConfigFileChangeWithExistingState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-config-file-change-migrate-existing"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -655,9 +641,8 @@ func TestInit_backendConfigFileChangeWithExistingState(t *testing.T) { func TestInit_backendConfigKV(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-config-kv"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -684,9 +669,8 @@ func TestInit_backendConfigKV(t *testing.T) { func TestInit_backendConfigKVReInit(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-config-kv"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -748,9 +732,8 @@ func TestInit_backendConfigKVReInit(t *testing.T) { func TestInit_backendConfigKVReInitWithConfigDiff(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -797,9 +780,8 @@ func TestInit_backendConfigKVReInitWithConfigDiff(t *testing.T) { func TestInit_backendCli_no_config_block(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -824,9 +806,8 @@ func TestInit_backendCli_no_config_block(t *testing.T) { } func TestInit_backendReinitWithExtra(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-empty"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() m := testMetaBackend(t, nil) @@ -882,9 +863,8 @@ func TestInit_backendReinitWithExtra(t *testing.T) { // move option from config to -backend-config args func TestInit_backendReinitConfigToExtra(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -953,13 +933,10 @@ func TestInit_backendCloudInvalidOptions(t *testing.T) { // of them will customize it a bit as part of their work. setupTempDir := func(t *testing.T) func() { t.Helper() - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-cloud-simple"), td) unChdir := testChdir(t, td) - return func() { - unChdir() - os.RemoveAll(td) - } + return unChdir } // Some of the tests need a non-empty placeholder state file to work @@ -1253,9 +1230,8 @@ prompts. // make sure inputFalse stops execution on migrate func TestInit_inputFalse(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -1332,9 +1308,8 @@ func TestInit_inputFalse(t *testing.T) { func TestInit_getProvider(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-get-providers"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() overrides := metaOverridesForProvider(testProvider()) @@ -1438,9 +1413,8 @@ func TestInit_getProvider(t *testing.T) { func TestInit_getProviderSource(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-get-provider-source"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() overrides := metaOverridesForProvider(testProvider()) @@ -1489,9 +1463,8 @@ func TestInit_getProviderSource(t *testing.T) { func TestInit_getProviderLegacyFromState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-get-provider-legacy-from-state"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() overrides := metaOverridesForProvider(testProvider()) @@ -1531,9 +1504,8 @@ func TestInit_getProviderLegacyFromState(t *testing.T) { func TestInit_getProviderInvalidPackage(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-get-provider-invalid-package"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() overrides := metaOverridesForProvider(testProvider()) @@ -1594,9 +1566,8 @@ func TestInit_getProviderInvalidPackage(t *testing.T) { func TestInit_getProviderDetectedLegacy(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-get-provider-detected-legacy"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // We need to construct a multisource with a mock source and a registry @@ -1662,9 +1633,8 @@ func TestInit_getProviderDetectedLegacy(t *testing.T) { func TestInit_providerSource(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-required-providers"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() providerSource, close := newMockProviderSource(t, map[string][]string{ @@ -1770,9 +1740,8 @@ func TestInit_cancelModules(t *testing.T) { // This test runs `terraform init` as if SIGINT (or similar on other // platforms) were sent to it, testing that it is interruptible. - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-registry-module"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Our shutdown channel is pre-closed so init will exit as soon as it @@ -1808,9 +1777,8 @@ func TestInit_cancelProviders(t *testing.T) { // This test runs `terraform init` as if SIGINT (or similar on other // platforms) were sent to it, testing that it is interruptible. - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-required-providers"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Use a provider source implementation which is designed to hang indefinitely, @@ -1853,9 +1821,8 @@ func TestInit_cancelProviders(t *testing.T) { func TestInit_getUpgradePlugins(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-get-providers"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() providerSource, close := newMockProviderSource(t, map[string][]string{ @@ -1979,9 +1946,8 @@ func TestInit_getUpgradePlugins(t *testing.T) { func TestInit_getProviderMissing(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-get-providers"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() providerSource, close := newMockProviderSource(t, map[string][]string{ @@ -2019,9 +1985,8 @@ func TestInit_getProviderMissing(t *testing.T) { func TestInit_checkRequiredVersion(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-check-required-version"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := cli.NewMockUi() @@ -2102,9 +2067,10 @@ func TestInit_checkRequiredVersionFirst(t *testing.T) { func TestInit_providerLockFile(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-provider-lock-file"), td) - defer os.RemoveAll(td) + // The temporary directory does not have write permission (dr-xr-xr-x) after the copy + defer os.Chmod(td, os.ModePerm) defer testChdir(t, td)() providerSource, close := newMockProviderSource(t, map[string][]string{ @@ -2290,9 +2256,8 @@ provider "registry.terraform.io/hashicorp/test" { for _, tc := range cases { t.Run(tc.desc, func(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath(tc.fixture), td) - defer os.RemoveAll(td) defer testChdir(t, td)() providerSource, close := newMockProviderSource(t, tc.providers) @@ -2406,9 +2371,8 @@ func TestInit_pluginDirReset(t *testing.T) { // Test user-supplied -plugin-dir func TestInit_pluginDirProviders(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-get-providers"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // An empty provider source @@ -2504,9 +2468,8 @@ func TestInit_pluginDirProviders(t *testing.T) { // Test user-supplied -plugin-dir doesn't allow auto-install func TestInit_pluginDirProvidersDoesNotGet(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-get-providers"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Our provider source has a suitable package for "between" available, @@ -2582,9 +2545,8 @@ func TestInit_pluginDirProvidersDoesNotGet(t *testing.T) { // Verify that plugin-dir doesn't prevent discovery of internal providers func TestInit_pluginDirWithBuiltIn(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-internal"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // An empty provider source @@ -2621,9 +2583,8 @@ func TestInit_invalidBuiltInProviders(t *testing.T) { // explicit version number, which is not allowed because it's builtin. // - an explicit dependency on terraform.io/builtin/nonexist, which does // not exist at all. - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-internal-invalid"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // An empty provider source diff --git a/internal/command/login_test.go b/internal/command/login_test.go index 35c51f44e0..b612b7bbed 100644 --- a/internal/command/login_test.go +++ b/internal/command/login_test.go @@ -2,9 +2,7 @@ package command import ( "context" - "io/ioutil" "net/http/httptest" - "os" "path/filepath" "strings" "testing" @@ -36,11 +34,7 @@ func TestLogin(t *testing.T) { loginTestCase := func(test func(t *testing.T, c *LoginCommand, ui *cli.MockUi)) func(t *testing.T) { return func(t *testing.T) { t.Helper() - workDir, err := ioutil.TempDir("", "terraform-test-command-login") - if err != nil { - t.Fatalf("cannot create temporary directory: %s", err) - } - defer os.RemoveAll(workDir) + workDir := t.TempDir() // We'll use this context to avoid asynchronous tasks outliving // a single test run. diff --git a/internal/command/logout_test.go b/internal/command/logout_test.go index 19472e3149..6f2511ee74 100644 --- a/internal/command/logout_test.go +++ b/internal/command/logout_test.go @@ -1,8 +1,6 @@ package command import ( - "io/ioutil" - "os" "path/filepath" "testing" @@ -15,11 +13,7 @@ import ( ) func TestLogout(t *testing.T) { - workDir, err := ioutil.TempDir("", "terraform-test-command-logout") - if err != nil { - t.Fatalf("cannot create temporary directory: %s", err) - } - defer os.RemoveAll(workDir) + workDir := t.TempDir() ui := cli.NewMockUi() credsSrc := cliconfig.EmptyCredentialsSourceForTests(filepath.Join(workDir, "credentials.tfrc.json")) @@ -54,7 +48,7 @@ func TestLogout(t *testing.T) { for _, tc := range testCases { host := svchost.Hostname(tc.hostname) token := svcauth.HostCredentialsToken("some-token") - err = credsSrc.StoreForHost(host, token) + err := credsSrc.StoreForHost(host, token) if err != nil { t.Fatalf("unexpected error storing credentials: %s", err) } diff --git a/internal/command/meta_backend_test.go b/internal/command/meta_backend_test.go index b9d8b91166..111e136cee 100644 --- a/internal/command/meta_backend_test.go +++ b/internal/command/meta_backend_test.go @@ -28,9 +28,8 @@ import ( // Test empty directory with no config/state creates a local state. func TestMetaBackend_emptyDir(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() // Get the backend @@ -84,9 +83,8 @@ func isEmptyState(path string) bool { // use the legacy state. func TestMetaBackend_emptyWithDefaultState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() // Write the legacy state @@ -149,15 +147,13 @@ func TestMetaBackend_emptyWithDefaultState(t *testing.T) { // Test an empty directory with an explicit state path (outside the dir) func TestMetaBackend_emptyWithExplicitState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() // Create another directory to store our state - stateDir := tempDir(t) + stateDir := t.TempDir() os.MkdirAll(stateDir, 0755) - defer os.RemoveAll(stateDir) // Write the legacy state statePath := filepath.Join(stateDir, "foo") @@ -222,9 +218,8 @@ func TestMetaBackend_emptyWithExplicitState(t *testing.T) { // Verify that interpolations result in an error func TestMetaBackend_configureInterpolation(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-new-interp"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Setup the meta @@ -239,9 +234,8 @@ func TestMetaBackend_configureInterpolation(t *testing.T) { // Newly configured backend func TestMetaBackend_configureNew(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-new"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Setup the meta @@ -304,9 +298,8 @@ func TestMetaBackend_configureNew(t *testing.T) { // Newly configured backend with prior local state and no remote state func TestMetaBackend_configureNewWithState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-new-migrate"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Ask input @@ -382,9 +375,8 @@ func TestMetaBackend_configureNewWithState(t *testing.T) { // for copy. func TestMetaBackend_configureNewWithoutCopy(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-new-migrate"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() if err := copy.CopyFile(DefaultStateFilename, "local-state.tfstate"); err != nil { @@ -433,9 +425,8 @@ func TestMetaBackend_configureNewWithoutCopy(t *testing.T) { // but opting to not migrate. func TestMetaBackend_configureNewWithStateNoMigrate(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-new-migrate"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Ask input @@ -478,9 +469,8 @@ func TestMetaBackend_configureNewWithStateNoMigrate(t *testing.T) { // Newly configured backend with prior local state and remote state func TestMetaBackend_configureNewWithStateExisting(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-new-migrate-existing"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Setup the meta @@ -550,9 +540,8 @@ func TestMetaBackend_configureNewWithStateExisting(t *testing.T) { // Newly configured backend with prior local state and remote state func TestMetaBackend_configureNewWithStateExistingNoMigrate(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-new-migrate-existing"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Ask input @@ -662,9 +651,8 @@ func TestMetaBackend_configuredUnchanged(t *testing.T) { // Changing a configured backend func TestMetaBackend_configuredChange(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-change"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Ask input @@ -742,9 +730,8 @@ func TestMetaBackend_configuredChange(t *testing.T) { // backend is if this is the first time. func TestMetaBackend_reconfigureChange(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-change-single-to-single"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Register the single-state backend @@ -796,9 +783,8 @@ func TestMetaBackend_reconfigureChange(t *testing.T) { // is available. func TestMetaBackend_initSelectedWorkspaceDoesNotExist(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-selected-workspace-doesnt-exist-multi"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Setup the meta @@ -830,9 +816,8 @@ func TestMetaBackend_initSelectedWorkspaceDoesNotExist(t *testing.T) { // automatically select that single workspace. func TestMetaBackend_initSelectedWorkspaceDoesNotExistAutoSelect(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-selected-workspace-doesnt-exist-single"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Setup the meta @@ -872,9 +857,8 @@ func TestMetaBackend_initSelectedWorkspaceDoesNotExistAutoSelect(t *testing.T) { // the currently selected workspace with input=false should fail. func TestMetaBackend_initSelectedWorkspaceDoesNotExistInputFalse(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-selected-workspace-doesnt-exist-multi"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Setup the meta @@ -893,9 +877,8 @@ func TestMetaBackend_initSelectedWorkspaceDoesNotExistInputFalse(t *testing.T) { // Changing a configured backend, copying state func TestMetaBackend_configuredChangeCopy(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-change"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Ask input @@ -941,9 +924,8 @@ func TestMetaBackend_configuredChangeCopy(t *testing.T) { // backend that only supports single states. func TestMetaBackend_configuredChangeCopy_singleState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-change-single-to-single"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Register the single-state backend @@ -996,9 +978,8 @@ func TestMetaBackend_configuredChangeCopy_singleState(t *testing.T) { // a default state. func TestMetaBackend_configuredChangeCopy_multiToSingleDefault(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-change-multi-default-to-single"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Register the single-state backend @@ -1050,9 +1031,8 @@ func TestMetaBackend_configuredChangeCopy_multiToSingleDefault(t *testing.T) { // backend that only supports single states. func TestMetaBackend_configuredChangeCopy_multiToSingle(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-change-multi-to-single"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Register the single-state backend @@ -1120,9 +1100,8 @@ func TestMetaBackend_configuredChangeCopy_multiToSingle(t *testing.T) { // backend that only supports single states. func TestMetaBackend_configuredChangeCopy_multiToSingleCurrentEnv(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-change-multi-to-single"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Register the single-state backend @@ -1186,9 +1165,8 @@ func TestMetaBackend_configuredChangeCopy_multiToSingleCurrentEnv(t *testing.T) // backend that also supports multi-state. func TestMetaBackend_configuredChangeCopy_multiToMulti(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-change-multi-to-multi"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Ask input @@ -1280,9 +1258,8 @@ func TestMetaBackend_configuredChangeCopy_multiToMulti(t *testing.T) { // default state while the default state is non-empty. func TestMetaBackend_configuredChangeCopy_multiToNoDefaultWithDefault(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-change-multi-to-no-default-with-default"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Register the single-state backend @@ -1356,9 +1333,8 @@ func TestMetaBackend_configuredChangeCopy_multiToNoDefaultWithDefault(t *testing // default state while the default state is empty. func TestMetaBackend_configuredChangeCopy_multiToNoDefaultWithoutDefault(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-change-multi-to-no-default-without-default"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Register the single-state backend @@ -1429,9 +1405,8 @@ func TestMetaBackend_configuredChangeCopy_multiToNoDefaultWithoutDefault(t *test // Unsetting a saved backend func TestMetaBackend_configuredUnset(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-unset"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Ask input @@ -1492,9 +1467,8 @@ func TestMetaBackend_configuredUnset(t *testing.T) { // Unsetting a saved backend and copying the remote state func TestMetaBackend_configuredUnsetCopy(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-unset"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Ask input @@ -1550,9 +1524,8 @@ func TestMetaBackend_configuredUnsetCopy(t *testing.T) { // A plan that has uses the local backend func TestMetaBackend_planLocal(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-plan-local"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() backendConfigBlock := cty.ObjectVal(map[string]cty.Value{ @@ -1639,9 +1612,8 @@ func TestMetaBackend_planLocal(t *testing.T) { // A plan with a custom state save path func TestMetaBackend_planLocalStatePath(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-plan-local"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() original := testState() @@ -1742,9 +1714,8 @@ func TestMetaBackend_planLocalStatePath(t *testing.T) { // A plan that has no backend config, matching local state func TestMetaBackend_planLocalMatch(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-plan-local-match"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() backendConfigBlock := cty.ObjectVal(map[string]cty.Value{ @@ -1830,9 +1801,8 @@ func TestMetaBackend_planLocalMatch(t *testing.T) { // init a backend using -backend-config options multiple times func TestMetaBackend_configureWithExtra(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-empty"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() extras := map[string]cty.Value{"path": cty.StringVal("hello")} @@ -1882,9 +1852,8 @@ func TestMetaBackend_configureWithExtra(t *testing.T) { // when configuring a default local state, don't delete local state func TestMetaBackend_localDoesNotDeleteLocal(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-empty"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // // create our local state @@ -1910,9 +1879,8 @@ func TestMetaBackend_localDoesNotDeleteLocal(t *testing.T) { // move options from config to -backend-config func TestMetaBackend_configToExtra(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // init the backend diff --git a/internal/command/meta_test.go b/internal/command/meta_test.go index 5971840f01..b8b6c83372 100644 --- a/internal/command/meta_test.go +++ b/internal/command/meta_test.go @@ -181,9 +181,8 @@ func TestMeta_initStatePaths(t *testing.T) { } func TestMeta_Env(t *testing.T) { - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() m := new(Meta) @@ -257,9 +256,8 @@ func TestMeta_Workspace_override(t *testing.T) { } func TestMeta_Workspace_invalidSelected(t *testing.T) { - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() // this is an invalid workspace name @@ -294,9 +292,8 @@ func TestMeta_process(t *testing.T) { defer func() { test = true }() // Create a temporary directory for our cwd - d := tempDir(t) + d := t.TempDir() os.MkdirAll(d, 0755) - defer os.RemoveAll(d) defer testChdir(t, d)() // At one point it was the responsibility of this process function to @@ -391,9 +388,8 @@ func TestMeta_process(t *testing.T) { func TestCommand_checkRequiredVersion(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("command-check-required-version"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := cli.NewMockUi() diff --git a/internal/command/plan_test.go b/internal/command/plan_test.go index 84950d7e0d..b0709b92b2 100644 --- a/internal/command/plan_test.go +++ b/internal/command/plan_test.go @@ -27,9 +27,8 @@ import ( ) func TestPlan(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := planFixtureProvider() @@ -50,12 +49,11 @@ func TestPlan(t *testing.T) { } func TestPlan_lockedState(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() - unlock, err := testLockState(testDataDir, filepath.Join(td, DefaultStateFilename)) + unlock, err := testLockState(t, testDataDir, filepath.Join(td, DefaultStateFilename)) if err != nil { t.Fatal(err) } @@ -83,8 +81,7 @@ func TestPlan_lockedState(t *testing.T) { } func TestPlan_plan(t *testing.T) { - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) planPath := testPlanFileNoop(t) @@ -106,9 +103,8 @@ func TestPlan_plan(t *testing.T) { } func TestPlan_destroy(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := states.BuildState(func(s *states.SyncState) { @@ -160,9 +156,8 @@ func TestPlan_destroy(t *testing.T) { } func TestPlan_noState(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := planFixtureProvider() @@ -195,9 +190,8 @@ func TestPlan_noState(t *testing.T) { } func TestPlan_outPath(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() outPath := filepath.Join(td, "test.plan") @@ -228,9 +222,8 @@ func TestPlan_outPath(t *testing.T) { } func TestPlan_outPathNoChange(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := states.BuildState(func(s *states.SyncState) { @@ -285,9 +278,8 @@ func TestPlan_outPathNoChange(t *testing.T) { // When using "-out" with a backend, the plan should encode the backend config func TestPlan_outBackend(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan-out-backend"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := states.BuildState(func(s *states.SyncState) { @@ -386,9 +378,8 @@ func TestPlan_outBackend(t *testing.T) { func TestPlan_refreshFalse(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := planFixtureProvider() @@ -416,9 +407,8 @@ func TestPlan_refreshFalse(t *testing.T) { func TestPlan_state(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := testState() @@ -459,9 +449,8 @@ func TestPlan_state(t *testing.T) { func TestPlan_stateDefault(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Generate state and move it to the default path @@ -505,9 +494,8 @@ func TestPlan_validate(t *testing.T) { test = false defer func() { test = true }() - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan-invalid"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -553,9 +541,8 @@ func TestPlan_validate(t *testing.T) { func TestPlan_vars(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan-vars"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := planVarsFixtureProvider() @@ -590,9 +577,8 @@ func TestPlan_vars(t *testing.T) { func TestPlan_varsUnset(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan-vars"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // The plan command will prompt for interactive input of var.foo. @@ -627,9 +613,8 @@ func TestPlan_varsUnset(t *testing.T) { // https://github.com/hashicorp/terraform/issues/26035 func TestPlan_providerArgumentUnset(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Disable test mode so input would be asked @@ -691,9 +676,8 @@ func TestPlan_providerArgumentUnset(t *testing.T) { // between config files and interactive input variables. // https://github.com/hashicorp/terraform/issues/28956 func TestPlan_providerConfigMerge(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan-provider-input"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Disable test mode so input would be asked @@ -781,9 +765,8 @@ func TestPlan_providerConfigMerge(t *testing.T) { func TestPlan_varFile(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan-vars"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() varFilePath := testTempFile(t) @@ -823,9 +806,8 @@ func TestPlan_varFile(t *testing.T) { func TestPlan_varFileDefault(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan-vars"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() varFilePath := filepath.Join(td, "terraform.tfvars") @@ -863,9 +845,8 @@ func TestPlan_varFileDefault(t *testing.T) { func TestPlan_varFileWithDecls(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan-vars"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() varFilePath := testTempFile(t) @@ -898,9 +879,8 @@ func TestPlan_varFileWithDecls(t *testing.T) { } func TestPlan_detailedExitcode(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() t.Run("return 1", func(t *testing.T) { @@ -937,9 +917,8 @@ func TestPlan_detailedExitcode(t *testing.T) { } func TestPlan_detailedExitcode_emptyDiff(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan-emptydiff"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -961,9 +940,8 @@ func TestPlan_detailedExitcode_emptyDiff(t *testing.T) { func TestPlan_shutdown(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-shutdown"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() cancelled := make(chan struct{}) @@ -1031,9 +1009,8 @@ func TestPlan_shutdown(t *testing.T) { } func TestPlan_init_required(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() view, done := testView(t) @@ -1058,9 +1035,8 @@ func TestPlan_init_required(t *testing.T) { // Config with multiple resources, targeting plan of a subset func TestPlan_targeted(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply-targeted"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -1145,9 +1121,8 @@ func TestPlan_targetFlagsDiags(t *testing.T) { } func TestPlan_replace(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan-replace"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := states.BuildState(func(s *states.SyncState) { @@ -1219,9 +1194,8 @@ func TestPlan_replace(t *testing.T) { // concurrent calls to PlanResourceChange. func TestPlan_parallelism(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("parallelism"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() par := 4 @@ -1302,9 +1276,8 @@ func TestPlan_parallelism(t *testing.T) { } func TestPlan_warnings(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("plan"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() t.Run("full warnings", func(t *testing.T) { diff --git a/internal/command/plugins_lock_test.go b/internal/command/plugins_lock_test.go index 812a8218bf..730346e462 100644 --- a/internal/command/plugins_lock_test.go +++ b/internal/command/plugins_lock_test.go @@ -8,7 +8,7 @@ import ( ) func TestPluginSHA256LockFile_Read(t *testing.T) { - f, err := ioutil.TempFile(testingDir, "tf-pluginsha1lockfile-test-") + f, err := ioutil.TempFile(t.TempDir(), "tf-pluginsha1lockfile-test-") if err != nil { t.Fatalf("failed to create temporary file: %s", err) } diff --git a/internal/command/providers_lock_test.go b/internal/command/providers_lock_test.go index da6cca6ec5..ef22f51d18 100644 --- a/internal/command/providers_lock_test.go +++ b/internal/command/providers_lock_test.go @@ -15,9 +15,8 @@ func TestProvidersLock(t *testing.T) { t.Run("noop", func(t *testing.T) { // in the most basic case, running providers lock in a directory with no configuration at all should succeed. // create an empty working directory - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() ui := new(cli.MockUi) @@ -34,9 +33,8 @@ func TestProvidersLock(t *testing.T) { // This test depends on the -fs-mirror argument, so we always know what results to expect t.Run("basic", func(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("providers-lock/basic"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Our fixture dir has a generic os_arch dir, which we need to customize diff --git a/internal/command/providers_schema_test.go b/internal/command/providers_schema_test.go index aaae7463b3..9aa8f810c7 100644 --- a/internal/command/providers_schema_test.go +++ b/internal/command/providers_schema_test.go @@ -43,10 +43,9 @@ func TestProvidersSchema_output(t *testing.T) { continue } t.Run(entry.Name(), func(t *testing.T) { - td := tempDir(t) + td := t.TempDir() inputDir := filepath.Join(fixtureDir, entry.Name()) testCopyDir(t, inputDir, td) - defer os.RemoveAll(td) defer testChdir(t, td)() providerSource, close := newMockProviderSource(t, map[string][]string{ diff --git a/internal/command/providers_test.go b/internal/command/providers_test.go index d11bda79e6..9d9bc9b6b9 100644 --- a/internal/command/providers_test.go +++ b/internal/command/providers_test.go @@ -75,9 +75,8 @@ func TestProviders_noConfigs(t *testing.T) { } func TestProviders_modules(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("providers/modules"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // first run init with mock provider sources to install the module diff --git a/internal/command/refresh_test.go b/internal/command/refresh_test.go index 72a71ef645..1598bbd299 100644 --- a/internal/command/refresh_test.go +++ b/internal/command/refresh_test.go @@ -29,9 +29,8 @@ var equateEmpty = cmpopts.EquateEmpty() func TestRefresh(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("refresh"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := testState() @@ -87,9 +86,8 @@ func TestRefresh(t *testing.T) { func TestRefresh_empty(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("refresh-empty"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -122,15 +120,14 @@ func TestRefresh_empty(t *testing.T) { func TestRefresh_lockedState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("refresh"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := testState() statePath := testStateFile(t, state) - unlock, err := testLockState(testDataDir, statePath) + unlock, err := testLockState(t, testDataDir, statePath) if err != nil { t.Fatal(err) } @@ -232,9 +229,8 @@ func TestRefresh_cwd(t *testing.T) { func TestRefresh_defaultState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("refresh"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() originalState := testState() @@ -315,16 +311,15 @@ func TestRefresh_defaultState(t *testing.T) { func TestRefresh_outPath(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("refresh"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := testState() statePath := testStateFile(t, state) // Output path - outf, err := ioutil.TempFile(testingDir, "tf") + outf, err := ioutil.TempFile(td, "tf") if err != nil { t.Fatalf("err: %s", err) } @@ -385,9 +380,8 @@ func TestRefresh_outPath(t *testing.T) { func TestRefresh_var(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("refresh-var"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := testState() @@ -423,9 +417,8 @@ func TestRefresh_var(t *testing.T) { func TestRefresh_varFile(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("refresh-var"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := testState() @@ -466,9 +459,8 @@ func TestRefresh_varFile(t *testing.T) { func TestRefresh_varFileDefault(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("refresh-var"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := testState() @@ -508,9 +500,8 @@ func TestRefresh_varFileDefault(t *testing.T) { func TestRefresh_varsUnset(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("refresh-unset-var"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Disable test mode so input would be asked @@ -557,16 +548,15 @@ func TestRefresh_varsUnset(t *testing.T) { func TestRefresh_backup(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("refresh"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := testState() statePath := testStateFile(t, state) // Output path - outf, err := ioutil.TempFile(testingDir, "tf") + outf, err := ioutil.TempFile(td, "tf") if err != nil { t.Fatalf("err: %s", err) } @@ -581,7 +571,7 @@ func TestRefresh_backup(t *testing.T) { } // Backup path - backupf, err := ioutil.TempFile(testingDir, "tf") + backupf, err := ioutil.TempFile(td, "tf") if err != nil { t.Fatalf("err: %s", err) } @@ -643,16 +633,15 @@ func TestRefresh_backup(t *testing.T) { func TestRefresh_disableBackup(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("refresh"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := testState() statePath := testStateFile(t, state) // Output path - outf, err := ioutil.TempFile(testingDir, "tf") + outf, err := ioutil.TempFile(td, "tf") if err != nil { t.Fatalf("err: %s", err) } @@ -719,9 +708,8 @@ func TestRefresh_disableBackup(t *testing.T) { func TestRefresh_displaysOutputs(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("refresh-output"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := testState() @@ -767,9 +755,8 @@ func TestRefresh_displaysOutputs(t *testing.T) { // Config with multiple resources, targeting refresh of a subset func TestRefresh_targeted(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("refresh-targeted"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := testState() @@ -862,9 +849,8 @@ func TestRefresh_targetFlagsDiags(t *testing.T) { func TestRefresh_warnings(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("apply"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() diff --git a/internal/command/show_test.go b/internal/command/show_test.go index d0601cc0c5..25acbac290 100644 --- a/internal/command/show_test.go +++ b/internal/command/show_test.go @@ -69,8 +69,7 @@ func TestShow_noArgsNoState(t *testing.T) { func TestShow_noArgsWithState(t *testing.T) { // Get a temp cwd - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) // Create the default state testStateFileDefault(t, testState()) @@ -484,10 +483,9 @@ func TestShow_json_output(t *testing.T) { } t.Run(entry.Name(), func(t *testing.T) { - td := tempDir(t) + td := t.TempDir() inputDir := filepath.Join(fixtureDir, entry.Name()) testCopyDir(t, inputDir, td) - defer os.RemoveAll(td) defer testChdir(t, td)() expectError := strings.Contains(entry.Name(), "error") @@ -588,10 +586,9 @@ func TestShow_json_output(t *testing.T) { } func TestShow_json_output_sensitive(t *testing.T) { - td := tempDir(t) + td := t.TempDir() inputDir := "testdata/show-json-sensitive" testCopyDir(t, inputDir, td) - defer os.RemoveAll(td) defer testChdir(t, td)() providerSource, close := newMockProviderSource(t, map[string][]string{"test": {"1.2.3"}}) @@ -682,10 +679,9 @@ func TestShow_json_output_sensitive(t *testing.T) { // Failing conditions are only present in JSON output for refresh-only plans, // so we test that separately here. func TestShow_json_output_conditions_refresh_only(t *testing.T) { - td := tempDir(t) + td := t.TempDir() inputDir := "testdata/show-json/conditions" testCopyDir(t, inputDir, td) - defer os.RemoveAll(td) defer testChdir(t, td)() providerSource, close := newMockProviderSource(t, map[string][]string{"test": {"1.2.3"}}) @@ -790,10 +786,9 @@ func TestShow_json_output_state(t *testing.T) { } t.Run(entry.Name(), func(t *testing.T) { - td := tempDir(t) + td := t.TempDir() inputDir := filepath.Join(fixtureDir, entry.Name()) testCopyDir(t, inputDir, td) - defer os.RemoveAll(td) defer testChdir(t, td)() providerSource, close := newMockProviderSource(t, map[string][]string{ @@ -865,9 +860,8 @@ func TestShow_json_output_state(t *testing.T) { func TestShow_planWithNonDefaultStateLineage(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("show"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Write default state file with a testing lineage ("fake-for-testing") diff --git a/internal/command/state_list_test.go b/internal/command/state_list_test.go index e66a7968c7..0b75051e38 100644 --- a/internal/command/state_list_test.go +++ b/internal/command/state_list_test.go @@ -1,7 +1,6 @@ package command import ( - "os" "strings" "testing" @@ -97,9 +96,8 @@ func TestStateListWithNonExistentID(t *testing.T) { func TestStateList_backendDefaultState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("state-list-backend-default"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -126,9 +124,8 @@ func TestStateList_backendDefaultState(t *testing.T) { func TestStateList_backendCustomState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("state-list-backend-custom"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -155,9 +152,8 @@ func TestStateList_backendCustomState(t *testing.T) { func TestStateList_backendOverrideState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("state-list-backend-custom"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -184,8 +180,7 @@ func TestStateList_backendOverrideState(t *testing.T) { } func TestStateList_noState(t *testing.T) { - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) p := testProvider() ui := cli.NewMockUi() @@ -204,9 +199,8 @@ func TestStateList_noState(t *testing.T) { func TestStateList_modules(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("state-list-nested-modules"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() diff --git a/internal/command/state_mv_test.go b/internal/command/state_mv_test.go index 7a5d889cf0..00f871f880 100644 --- a/internal/command/state_mv_test.go +++ b/internal/command/state_mv_test.go @@ -170,9 +170,8 @@ func TestStateMv_backupAndBackupOutOptionsWithNonLocalBackend(t *testing.T) { }) t.Run("backup option specified", func(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-http"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() backupPath := filepath.Join(td, "backup") @@ -219,9 +218,8 @@ on a local state file only. You must specify a local state file with the }) t.Run("backup-out option specified", func(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-http"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() backupOutPath := filepath.Join(td, "backup-out") @@ -268,9 +266,8 @@ on a local state file only. You must specify a local state file with the }) t.Run("backup and backup-out options specified", func(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-http"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() backupPath := filepath.Join(td, "backup") @@ -319,9 +316,8 @@ on a local state file only. You must specify a local state file with the }) t.Run("backup option specified with state option", func(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-http"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testStateFile(t, state) @@ -360,9 +356,8 @@ on a local state file only. You must specify a local state file with the }) t.Run("backup-out option specified with state option", func(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend-http"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() statePath := testStateFile(t, state) @@ -852,9 +847,8 @@ match. // don't modify backend state is we supply a -state flag func TestStateMv_explicitWithBackend(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("init-backend"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() backupPath := filepath.Join(td, "backup") @@ -1140,8 +1134,7 @@ func TestStateMv_stateOutExisting(t *testing.T) { } func TestStateMv_noState(t *testing.T) { - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) p := testProvider() ui := new(cli.MockUi) @@ -1467,9 +1460,8 @@ func TestStateMv_toNewModule(t *testing.T) { } func TestStateMv_withinBackend(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-unchanged"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := states.BuildState(func(s *states.SyncState) { @@ -1547,9 +1539,8 @@ func TestStateMv_withinBackend(t *testing.T) { } func TestStateMv_fromBackendToLocal(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-unchanged"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := states.NewState() @@ -1715,9 +1706,8 @@ func TestStateMvInvalidSourceAddress(t *testing.T) { func TestStateMv_checkRequiredVersion(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("command-check-required-version"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := states.BuildState(func(s *states.SyncState) { diff --git a/internal/command/state_pull_test.go b/internal/command/state_pull_test.go index fb54629721..233bed25c0 100644 --- a/internal/command/state_pull_test.go +++ b/internal/command/state_pull_test.go @@ -3,7 +3,6 @@ package command import ( "bytes" "io/ioutil" - "os" "strings" "testing" @@ -12,9 +11,8 @@ import ( func TestStatePull(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("state-pull-backend"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() expected, err := ioutil.ReadFile("local-state.tfstate") @@ -43,8 +41,7 @@ func TestStatePull(t *testing.T) { } func TestStatePull_noState(t *testing.T) { - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) p := testProvider() ui := cli.NewMockUi() @@ -68,9 +65,8 @@ func TestStatePull_noState(t *testing.T) { func TestStatePull_checkRequiredVersion(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("command-check-required-version"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() diff --git a/internal/command/state_push_test.go b/internal/command/state_push_test.go index 251d952d0b..e30010bb9e 100644 --- a/internal/command/state_push_test.go +++ b/internal/command/state_push_test.go @@ -2,7 +2,6 @@ package command import ( "bytes" - "os" "strings" "testing" @@ -14,9 +13,8 @@ import ( func TestStatePush_empty(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("state-push-good"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() expected := testStateRead(t, "replace.tfstate") @@ -45,9 +43,8 @@ func TestStatePush_empty(t *testing.T) { func TestStatePush_lockedState(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("state-push-good"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -61,7 +58,7 @@ func TestStatePush_lockedState(t *testing.T) { }, } - unlock, err := testLockState(testDataDir, "local-state.tfstate") + unlock, err := testLockState(t, testDataDir, "local-state.tfstate") if err != nil { t.Fatal(err) } @@ -78,9 +75,8 @@ func TestStatePush_lockedState(t *testing.T) { func TestStatePush_replaceMatch(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("state-push-replace-match"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() expected := testStateRead(t, "replace.tfstate") @@ -109,9 +105,8 @@ func TestStatePush_replaceMatch(t *testing.T) { func TestStatePush_replaceMatchStdin(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("state-push-replace-match"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() expected := testStateRead(t, "replace.tfstate") @@ -147,9 +142,8 @@ func TestStatePush_replaceMatchStdin(t *testing.T) { func TestStatePush_lineageMismatch(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("state-push-bad-lineage"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() expected := testStateRead(t, "local-state.tfstate") @@ -178,9 +172,8 @@ func TestStatePush_lineageMismatch(t *testing.T) { func TestStatePush_serialNewer(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("state-push-serial-newer"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() expected := testStateRead(t, "local-state.tfstate") @@ -209,9 +202,8 @@ func TestStatePush_serialNewer(t *testing.T) { func TestStatePush_serialOlder(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("state-push-serial-older"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() expected := testStateRead(t, "replace.tfstate") @@ -239,9 +231,8 @@ func TestStatePush_serialOlder(t *testing.T) { } func TestStatePush_forceRemoteState(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("inmem-backend"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() defer inmem.Reset() @@ -294,9 +285,8 @@ func TestStatePush_forceRemoteState(t *testing.T) { func TestStatePush_checkRequiredVersion(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("command-check-required-version"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() diff --git a/internal/command/state_replace_provider_test.go b/internal/command/state_replace_provider_test.go index dd6b0a852d..9c86cf7797 100644 --- a/internal/command/state_replace_provider_test.go +++ b/internal/command/state_replace_provider_test.go @@ -2,7 +2,6 @@ package command import ( "bytes" - "os" "path/filepath" "strings" "testing" @@ -297,9 +296,8 @@ func TestStateReplaceProvider_docs(t *testing.T) { func TestStateReplaceProvider_checkRequiredVersion(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("command-check-required-version"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := states.BuildState(func(s *states.SyncState) { diff --git a/internal/command/state_rm_test.go b/internal/command/state_rm_test.go index 3ec0e41cc9..1b58a59677 100644 --- a/internal/command/state_rm_test.go +++ b/internal/command/state_rm_test.go @@ -354,8 +354,7 @@ func TestStateRm_backupExplicit(t *testing.T) { } func TestStateRm_noState(t *testing.T) { - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) p := testProvider() ui := new(cli.MockUi) @@ -377,9 +376,8 @@ func TestStateRm_noState(t *testing.T) { } func TestStateRm_needsInit(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-change"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() p := testProvider() @@ -406,9 +404,8 @@ func TestStateRm_needsInit(t *testing.T) { } func TestStateRm_backendState(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-unchanged"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := states.BuildState(func(s *states.SyncState) { @@ -488,9 +485,8 @@ func TestStateRm_backendState(t *testing.T) { func TestStateRm_checkRequiredVersion(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("command-check-required-version"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() state := states.BuildState(func(s *states.SyncState) { diff --git a/internal/command/state_show_test.go b/internal/command/state_show_test.go index 32e4178b81..3da87c0eca 100644 --- a/internal/command/state_show_test.go +++ b/internal/command/state_show_test.go @@ -147,8 +147,7 @@ func TestStateShow_multi(t *testing.T) { } func TestStateShow_noState(t *testing.T) { - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) p := testProvider() ui := new(cli.MockUi) diff --git a/internal/command/state_test.go b/internal/command/state_test.go index cbacb6c633..cd2e830125 100644 --- a/internal/command/state_test.go +++ b/internal/command/state_test.go @@ -25,8 +25,7 @@ func testStateBackups(t *testing.T, dir string) []string { } func TestStateDefaultBackupExtension(t *testing.T) { - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) s, err := (&StateMeta{}).State() if err != nil { diff --git a/internal/command/taint_test.go b/internal/command/taint_test.go index ee41ad382a..001d477082 100644 --- a/internal/command/taint_test.go +++ b/internal/command/taint_test.go @@ -72,7 +72,7 @@ func TestTaint_lockedState(t *testing.T) { }) statePath := testStateFile(t, state) - unlock, err := testLockState(testDataDir, statePath) + unlock, err := testLockState(t, testDataDir, statePath) if err != nil { t.Fatal(err) } @@ -102,8 +102,7 @@ func TestTaint_lockedState(t *testing.T) { func TestTaint_backup(t *testing.T) { // Get a temp cwd - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) // Write the temp state state := states.BuildState(func(s *states.SyncState) { @@ -147,8 +146,7 @@ func TestTaint_backup(t *testing.T) { func TestTaint_backupDisable(t *testing.T) { // Get a temp cwd - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) // Write the temp state state := states.BuildState(func(s *states.SyncState) { @@ -215,8 +213,7 @@ func TestTaint_badState(t *testing.T) { func TestTaint_defaultState(t *testing.T) { // Get a temp cwd - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) // Write the temp state state := states.BuildState(func(s *states.SyncState) { @@ -259,8 +256,7 @@ func TestTaint_defaultState(t *testing.T) { func TestTaint_defaultWorkspaceState(t *testing.T) { // Get a temp cwd - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) state := states.BuildState(func(s *states.SyncState) { s.SetResourceInstanceCurrent( @@ -392,8 +388,7 @@ because -allow-missing was set. func TestTaint_stateOut(t *testing.T) { // Get a temp cwd - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) // Write the temp state state := states.BuildState(func(s *states.SyncState) { @@ -493,9 +488,8 @@ func TestTaint_module(t *testing.T) { func TestTaint_checkRequiredVersion(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("command-check-required-version"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() // Write the temp state diff --git a/internal/command/test_test.go b/internal/command/test_test.go index 1f776b5ffd..17ae6da67a 100644 --- a/internal/command/test_test.go +++ b/internal/command/test_test.go @@ -3,7 +3,6 @@ package command import ( "bytes" "io/ioutil" - "os" "strings" "testing" @@ -15,9 +14,8 @@ import ( // These are the main tests for the "terraform test" command. func TestTest(t *testing.T) { t.Run("passes", func(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("test-passes"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() streams, close := terminal.StreamsForTesting(t) @@ -85,9 +83,8 @@ Success! All of the test assertions passed. } }) t.Run("fails", func(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("test-fails"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() streams, close := terminal.StreamsForTesting(t) diff --git a/internal/command/unlock_test.go b/internal/command/unlock_test.go index 8219b587ed..9822b38426 100644 --- a/internal/command/unlock_test.go +++ b/internal/command/unlock_test.go @@ -13,9 +13,8 @@ import ( // Since we can't unlock a local state file, just test that calling unlock // doesn't fail. func TestUnlock(t *testing.T) { - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() // Write the legacy state @@ -66,9 +65,8 @@ func TestUnlock(t *testing.T) { // Newly configured backend func TestUnlock_inmemBackend(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("backend-inmem-locked"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() defer inmem.Reset() diff --git a/internal/command/untaint_test.go b/internal/command/untaint_test.go index 4b84e5b0dd..cc193125e4 100644 --- a/internal/command/untaint_test.go +++ b/internal/command/untaint_test.go @@ -75,7 +75,7 @@ func TestUntaint_lockedState(t *testing.T) { ) }) statePath := testStateFile(t, state) - unlock, err := testLockState(testDataDir, statePath) + unlock, err := testLockState(t, testDataDir, statePath) if err != nil { t.Fatal(err) } @@ -106,8 +106,7 @@ func TestUntaint_lockedState(t *testing.T) { func TestUntaint_backup(t *testing.T) { // Get a temp cwd - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) // Write the temp state state := states.BuildState(func(s *states.SyncState) { @@ -162,8 +161,7 @@ test_instance.foo: func TestUntaint_backupDisable(t *testing.T) { // Get a temp cwd - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) // Write the temp state state := states.BuildState(func(s *states.SyncState) { @@ -234,8 +232,7 @@ func TestUntaint_badState(t *testing.T) { func TestUntaint_defaultState(t *testing.T) { // Get a temp cwd - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) // Write the temp state state := states.BuildState(func(s *states.SyncState) { @@ -282,8 +279,7 @@ test_instance.foo: func TestUntaint_defaultWorkspaceState(t *testing.T) { // Get a temp cwd - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) // Write the temp state state := states.BuildState(func(s *states.SyncState) { @@ -420,8 +416,7 @@ because -allow-missing was set. func TestUntaint_stateOut(t *testing.T) { // Get a temp cwd - tmp, cwd := testCwd(t) - defer testFixCwd(t, tmp, cwd) + testCwd(t) // Write the temp state state := states.BuildState(func(s *states.SyncState) { diff --git a/internal/command/validate_test.go b/internal/command/validate_test.go index afff810707..969e79683f 100644 --- a/internal/command/validate_test.go +++ b/internal/command/validate_test.go @@ -65,9 +65,8 @@ func TestValidateCommand(t *testing.T) { func TestValidateCommandWithTfvarsFile(t *testing.T) { // Create a temporary working directory that is empty because this test // requires scanning the current working directory by validate command. - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("validate-valid/with-tfvars-file"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() view, done := testView(t) diff --git a/internal/command/version_test.go b/internal/command/version_test.go index 62be7f9e7a..3ec5a4b863 100644 --- a/internal/command/version_test.go +++ b/internal/command/version_test.go @@ -1,8 +1,6 @@ package command import ( - "io/ioutil" - "os" "strings" "testing" @@ -18,11 +16,7 @@ func TestVersionCommand_implements(t *testing.T) { } func TestVersion(t *testing.T) { - td, err := ioutil.TempDir("", "terraform-test-version") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(td) + td := t.TempDir() defer testChdir(t, td)() // We'll create a fixed dependency lock file in our working directory @@ -116,11 +110,7 @@ func TestVersion_outdated(t *testing.T) { } func TestVersion_json(t *testing.T) { - td, err := ioutil.TempDir("", "terraform-test-version") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(td) + td := t.TempDir() defer testChdir(t, td)() ui := cli.NewMockUi() diff --git a/internal/command/workdir/plugin_dirs_test.go b/internal/command/workdir/plugin_dirs_test.go index 5ed224ab3f..614ff8585d 100644 --- a/internal/command/workdir/plugin_dirs_test.go +++ b/internal/command/workdir/plugin_dirs_test.go @@ -1,7 +1,6 @@ package workdir import ( - "os" "path/filepath" "testing" @@ -9,11 +8,7 @@ import ( ) func TestDirForcedPluginDirs(t *testing.T) { - tmpDir, err := os.MkdirTemp("", "terraform-workdir-") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() dir := NewDir(tmpDir) // We'll use the default convention of a data dir nested inside the diff --git a/internal/command/workspace_command_test.go b/internal/command/workspace_command_test.go index 30096cb868..35dd090d0c 100644 --- a/internal/command/workspace_command_test.go +++ b/internal/command/workspace_command_test.go @@ -20,9 +20,8 @@ import ( func TestWorkspace_createAndChange(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() newCmd := &WorkspaceNewCommand{} @@ -64,9 +63,8 @@ func TestWorkspace_createAndChange(t *testing.T) { // This also ensures we switch to the correct env after each call func TestWorkspace_createAndList(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() // make sure a vars file doesn't interfere @@ -113,9 +111,8 @@ func TestWorkspace_createAndList(t *testing.T) { // Create some workspaces and test the show output. func TestWorkspace_createAndShow(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() // make sure a vars file doesn't interfere @@ -182,9 +179,8 @@ func TestWorkspace_createAndShow(t *testing.T) { // Don't allow names that aren't URL safe func TestWorkspace_createInvalid(t *testing.T) { // Create a temporary working directory that is empty - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() envs := []string{"test_a*", "test_b/foo", "../../../test_c", "好_d"} @@ -220,9 +216,8 @@ func TestWorkspace_createInvalid(t *testing.T) { } func TestWorkspace_createWithState(t *testing.T) { - td := tempDir(t) + td := t.TempDir() testCopyDir(t, testFixturePath("inmem-backend"), td) - defer os.RemoveAll(td) defer testChdir(t, td)() defer inmem.Reset() @@ -291,9 +286,8 @@ func TestWorkspace_createWithState(t *testing.T) { } func TestWorkspace_delete(t *testing.T) { - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() // create the workspace directories @@ -345,9 +339,8 @@ func TestWorkspace_delete(t *testing.T) { } func TestWorkspace_deleteInvalid(t *testing.T) { - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() // choose an invalid workspace name @@ -378,9 +371,8 @@ func TestWorkspace_deleteInvalid(t *testing.T) { } func TestWorkspace_deleteWithState(t *testing.T) { - td := tempDir(t) + td := t.TempDir() os.MkdirAll(td, 0755) - defer os.RemoveAll(td) defer testChdir(t, td)() // create the workspace directories diff --git a/internal/communicator/ssh/communicator_test.go b/internal/communicator/ssh/communicator_test.go index 0ee9015776..8d7db99967 100644 --- a/internal/communicator/ssh/communicator_test.go +++ b/internal/communicator/ssh/communicator_test.go @@ -576,11 +576,7 @@ func TestAccUploadFile(t *testing.T) { t.Fatalf("error creating communicator: %s", err) } - tmpDir, err := ioutil.TempDir("", "communicator") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpDir) + tmpDir := t.TempDir() content := []byte("this is the file content") source := bytes.NewReader(content) diff --git a/internal/communicator/ssh/ssh_test.go b/internal/communicator/ssh/ssh_test.go index c1086569fd..85164be3e2 100644 --- a/internal/communicator/ssh/ssh_test.go +++ b/internal/communicator/ssh/ssh_test.go @@ -17,11 +17,7 @@ import ( // verify that we can locate public key data func TestFindKeyData(t *testing.T) { // set up a test directory - td, err := ioutil.TempDir("", "ssh") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(td) + td := t.TempDir() cwd, err := os.Getwd() if err != nil { t.Fatal(err) diff --git a/internal/configs/configload/copy_dir_test.go b/internal/configs/configload/copy_dir_test.go index 2f9f86b8fc..b7cc80495a 100644 --- a/internal/configs/configload/copy_dir_test.go +++ b/internal/configs/configload/copy_dir_test.go @@ -21,14 +21,10 @@ import ( // └── main.tf func TestCopyDir_symlinks(t *testing.T) { - tmpdir, err := ioutil.TempDir("", "copy-dir-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpdir) + tmpdir := t.TempDir() moduleDir := filepath.Join(tmpdir, "modules") - err = os.Mkdir(moduleDir, os.ModePerm) + err := os.Mkdir(moduleDir, os.ModePerm) if err != nil { t.Fatal(err) } @@ -67,14 +63,10 @@ func TestCopyDir_symlinks(t *testing.T) { } func TestCopyDir_symlink_file(t *testing.T) { - tmpdir, err := ioutil.TempDir("", "copy-file-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpdir) + tmpdir := t.TempDir() moduleDir := filepath.Join(tmpdir, "modules") - err = os.Mkdir(moduleDir, os.ModePerm) + err := os.Mkdir(moduleDir, os.ModePerm) if err != nil { t.Fatal(err) } diff --git a/internal/copy/copy_dir_test.go b/internal/copy/copy_dir_test.go index 225c43abc2..244bcbb4e0 100644 --- a/internal/copy/copy_dir_test.go +++ b/internal/copy/copy_dir_test.go @@ -21,14 +21,10 @@ import ( // └── main.tf func TestCopyDir_symlinks(t *testing.T) { - tmpdir, err := ioutil.TempDir("", "copy-dir-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpdir) + tmpdir := t.TempDir() moduleDir := filepath.Join(tmpdir, "modules") - err = os.Mkdir(moduleDir, os.ModePerm) + err := os.Mkdir(moduleDir, os.ModePerm) if err != nil { t.Fatal(err) } @@ -67,14 +63,10 @@ func TestCopyDir_symlinks(t *testing.T) { } func TestCopyDir_symlink_file(t *testing.T) { - tmpdir, err := ioutil.TempDir("", "copy-file-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpdir) + tmpdir := t.TempDir() moduleDir := filepath.Join(tmpdir, "modules") - err = os.Mkdir(moduleDir, os.ModePerm) + err := os.Mkdir(moduleDir, os.ModePerm) if err != nil { t.Fatal(err) } diff --git a/internal/depsfile/locks_file_test.go b/internal/depsfile/locks_file_test.go index a2633a4eb0..632aa71c7a 100644 --- a/internal/depsfile/locks_file_test.go +++ b/internal/depsfile/locks_file_test.go @@ -220,11 +220,7 @@ func TestSaveLocksToFile(t *testing.T) { locks.SetProvider(bazProvider, oneDotTwo, nil, nil) locks.SetProvider(booProvider, oneDotTwo, abbreviatedOneDotTwo, nil) - dir, err := ioutil.TempDir("", "terraform-internal-depsfile-savelockstofile") - if err != nil { - t.Fatal(err.Error()) - } - defer os.RemoveAll(dir) + dir := t.TempDir() filename := filepath.Join(dir, LockFilePath) diags := SaveLocksToFile(locks, filename) diff --git a/internal/e2e/e2e.go b/internal/e2e/e2e.go index e07f2e87d5..e1ede0e460 100644 --- a/internal/e2e/e2e.go +++ b/internal/e2e/e2e.go @@ -8,6 +8,7 @@ import ( "os" "os/exec" "path/filepath" + "testing" "github.com/hashicorp/terraform/internal/plans" "github.com/hashicorp/terraform/internal/plans/planfile" @@ -31,13 +32,8 @@ type binary struct { // cannot be found, or if an error occurs while _copying_ the fixture files, // this function will panic. Tests should be written to assume that this // function always succeeds. -func NewBinary(binaryPath, workingDir string) *binary { - tmpDir, err := ioutil.TempDir("", "binary-e2etest") - if err != nil { - panic(err) - } - - tmpDir, err = filepath.EvalSymlinks(tmpDir) +func NewBinary(t *testing.T, binaryPath, workingDir string) *binary { + tmpDir, err := filepath.EvalSymlinks(t.TempDir()) if err != nil { panic(err) } @@ -211,6 +207,7 @@ func (b *binary) Plan(path string) (*plans.Plan, error) { if err != nil { return nil, err } + defer pr.Close() plan, err := pr.ReadPlan() if err != nil { return nil, err @@ -238,21 +235,6 @@ func (b *binary) SetLocalState(state *states.State) error { return statefile.Write(sf, f) } -// Close cleans up the temporary resources associated with the object, -// including its working directory. It is not valid to call Cmd or Run -// after Close returns. -// -// This method does _not_ stop any running child processes. It's the -// caller's responsibility to also terminate those _before_ closing the -// underlying binary object. -// -// This function is designed to run under "defer", so it doesn't actually -// do any error handling and will leave dangling temporary files on disk -// if any errors occur while cleaning up. -func (b *binary) Close() { - os.RemoveAll(b.workDir) -} - func GoBuild(pkgPath, tmpPrefix string) string { dir, prefix := filepath.Split(tmpPrefix) tmpFile, err := ioutil.TempFile(dir, prefix) diff --git a/internal/initwd/from_module_test.go b/internal/initwd/from_module_test.go index a28ad2a7dc..9714ed3465 100644 --- a/internal/initwd/from_module_test.go +++ b/internal/initwd/from_module_test.go @@ -2,7 +2,6 @@ package initwd import ( "context" - "io/ioutil" "os" "path/filepath" "strings" @@ -214,10 +213,7 @@ func TestDirFromModule_rel_submodules(t *testing.T) { // - tmpdir/local-modules (with contents of testdata/local-modules) // - tmpdir/empty: the workDir we CD into for the test // - tmpdir/empty/target (target, the destination for init -from-module) - tmpDir, err := ioutil.TempDir("", "terraform-configload") - if err != nil { - t.Fatal(err) - } + tmpDir := t.TempDir() fromModuleDir := filepath.Join(tmpDir, "local-modules") workDir := filepath.Join(tmpDir, "empty") if err := os.Mkdir(fromModuleDir, os.ModePerm); err != nil { @@ -242,8 +238,9 @@ func TestDirFromModule_rel_submodules(t *testing.T) { if err != nil { t.Fatalf("failed to switch to temp dir %s: %s", tmpDir, err) } - defer os.Chdir(oldDir) - defer os.RemoveAll(tmpDir) + t.Cleanup(func() { + os.Chdir(oldDir) + }) hooks := &testInstallHooks{} diff --git a/internal/plans/planfile/planfile_test.go b/internal/plans/planfile/planfile_test.go index 1197d30eef..96c91343c8 100644 --- a/internal/plans/planfile/planfile_test.go +++ b/internal/plans/planfile/planfile_test.go @@ -1,7 +1,6 @@ package planfile import ( - "io/ioutil" "path/filepath" "testing" @@ -85,11 +84,7 @@ func TestRoundtrip(t *testing.T) { }, ) - workDir, err := ioutil.TempDir("", "tf-planfile") - if err != nil { - t.Fatal(err) - } - planFn := filepath.Join(workDir, "tfplan") + planFn := filepath.Join(t.TempDir(), "tfplan") err = Create(planFn, CreateArgs{ ConfigSnapshot: snapIn, diff --git a/internal/providercache/dir_modify_test.go b/internal/providercache/dir_modify_test.go index d9c103cd94..6e7821b575 100644 --- a/internal/providercache/dir_modify_test.go +++ b/internal/providercache/dir_modify_test.go @@ -2,8 +2,6 @@ package providercache import ( "context" - "io/ioutil" - "os" "path/filepath" "testing" @@ -15,12 +13,7 @@ import ( ) func TestInstallPackage(t *testing.T) { - tmpDirPath, err := ioutil.TempDir("", "terraform-test-providercache") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpDirPath) - tmpDirPath, err = filepath.EvalSymlinks(tmpDirPath) + tmpDirPath, err := filepath.EvalSymlinks(t.TempDir()) if err != nil { t.Fatal(err) } @@ -74,12 +67,7 @@ func TestInstallPackage(t *testing.T) { func TestLinkFromOtherCache(t *testing.T) { srcDirPath := "testdata/cachedir" - tmpDirPath, err := ioutil.TempDir("", "terraform-test-providercache") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpDirPath) - tmpDirPath, err = filepath.EvalSymlinks(tmpDirPath) + tmpDirPath, err := filepath.EvalSymlinks(t.TempDir()) if err != nil { t.Fatal(err) } diff --git a/internal/providercache/installer_test.go b/internal/providercache/installer_test.go index f0e04f5d89..0ca7038883 100644 --- a/internal/providercache/installer_test.go +++ b/internal/providercache/installer_test.go @@ -3,11 +3,9 @@ package providercache import ( "context" "encoding/json" - "io/ioutil" "log" "net/http" "net/http/httptest" - "os" "path/filepath" "strings" "testing" @@ -1443,11 +1441,7 @@ func TestEnsureProviderVersions_local_source(t *testing.T) { source := getproviders.NewFilesystemMirrorSource("testdata/cachedir") // create a temporary workdir - tmpDirPath, err := ioutil.TempDir("", "terraform-test-providercache") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpDirPath) + tmpDirPath := t.TempDir() // set up the installer using the temporary directory and filesystem source platform := getproviders.Platform{OS: "linux", Arch: "amd64"} @@ -1545,11 +1539,7 @@ func TestEnsureProviderVersions_protocol_errors(t *testing.T) { defer close() // create a temporary workdir - tmpDirPath, err := ioutil.TempDir("", "terraform-test-providercache") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpDirPath) + tmpDirPath := t.TempDir() version0 := getproviders.MustParseVersionConstraints("0.1.0") // supports protocol version 1.0 version1 := getproviders.MustParseVersion("1.2.0") // this is the expected result in tests with a match @@ -1860,8 +1850,7 @@ func fakeRegistryHandler(resp http.ResponseWriter, req *http.Request) { // In order to be able to compare the recorded temp dir paths, we need to // normalize the path to match what the installer would report. func tmpDir(t *testing.T) string { - d := t.TempDir() - unlinked, err := filepath.EvalSymlinks(d) + unlinked, err := filepath.EvalSymlinks(t.TempDir()) if err != nil { t.Fatal(err) } diff --git a/internal/states/statemgr/filesystem_test.go b/internal/states/statemgr/filesystem_test.go index 5a73819d60..1d319920f5 100644 --- a/internal/states/statemgr/filesystem_test.go +++ b/internal/states/statemgr/filesystem_test.go @@ -185,11 +185,7 @@ func TestFilesystem_backup(t *testing.T) { func TestFilesystem_backupAndReadPath(t *testing.T) { defer testOverrideVersion(t, "1.2.3")() - workDir, err := ioutil.TempDir("", "tf") - if err != nil { - t.Fatalf("failed to create temporary directory: %s", err) - } - defer os.RemoveAll(workDir) + workDir := t.TempDir() markerOutput := addrs.OutputValue{Name: "foo"}.Absolute(addrs.RootModuleInstance) diff --git a/internal/terraform/context_apply_test.go b/internal/terraform/context_apply_test.go index 64f357700b..841ec7719d 100644 --- a/internal/terraform/context_apply_test.go +++ b/internal/terraform/context_apply_test.go @@ -2340,7 +2340,7 @@ func TestContext2Apply_provisionerInterpCount(t *testing.T) { // We'll marshal and unmarshal the plan here, to ensure that we have // a clean new context as would be created if we separately ran // terraform plan -out=tfplan && terraform apply tfplan - ctxOpts, m, plan, err := contextOptsForPlanViaFile(snap, plan) + ctxOpts, m, plan, err := contextOptsForPlanViaFile(t, snap, plan) if err != nil { t.Fatal(err) } @@ -5723,7 +5723,7 @@ func TestContext2Apply_destroyModuleWithAttrsReferencingResource(t *testing.T) { t.Logf("Step 2 plan: %s", legacyDiffComparisonString(plan.Changes)) - ctxOpts, m, plan, err := contextOptsForPlanViaFile(snap, plan) + ctxOpts, m, plan, err := contextOptsForPlanViaFile(t, snap, plan) if err != nil { t.Fatalf("failed to round-trip through planfile: %s", err) } @@ -5793,7 +5793,7 @@ func TestContext2Apply_destroyWithModuleVariableAndCount(t *testing.T) { t.Fatalf("destroy plan err: %s", diags.Err()) } - ctxOpts, m, plan, err := contextOptsForPlanViaFile(snap, plan) + ctxOpts, m, plan, err := contextOptsForPlanViaFile(t, snap, plan) if err != nil { t.Fatalf("failed to round-trip through planfile: %s", err) } @@ -5937,7 +5937,7 @@ func TestContext2Apply_destroyWithModuleVariableAndCountNested(t *testing.T) { t.Fatalf("destroy plan err: %s", diags.Err()) } - ctxOpts, m, plan, err := contextOptsForPlanViaFile(snap, plan) + ctxOpts, m, plan, err := contextOptsForPlanViaFile(t, snap, plan) if err != nil { t.Fatalf("failed to round-trip through planfile: %s", err) } @@ -7889,7 +7889,7 @@ func TestContext2Apply_issue7824(t *testing.T) { } // Write / Read plan to simulate running it through a Plan file - ctxOpts, m, plan, err := contextOptsForPlanViaFile(snap, plan) + ctxOpts, m, plan, err := contextOptsForPlanViaFile(t, snap, plan) if err != nil { t.Fatalf("failed to round-trip through planfile: %s", err) } @@ -7964,7 +7964,7 @@ func TestContext2Apply_issue5254(t *testing.T) { } // Write / Read plan to simulate running it through a Plan file - ctxOpts, m, plan, err := contextOptsForPlanViaFile(snap, plan) + ctxOpts, m, plan, err := contextOptsForPlanViaFile(t, snap, plan) if err != nil { t.Fatalf("failed to round-trip through planfile: %s", err) } @@ -8041,7 +8041,7 @@ func TestContext2Apply_targetedWithTaintedInState(t *testing.T) { } // Write / Read plan to simulate running it through a Plan file - ctxOpts, m, plan, err := contextOptsForPlanViaFile(snap, plan) + ctxOpts, m, plan, err := contextOptsForPlanViaFile(t, snap, plan) if err != nil { t.Fatalf("failed to round-trip through planfile: %s", err) } @@ -8304,7 +8304,7 @@ func TestContext2Apply_destroyNestedModuleWithAttrsReferencingResource(t *testin t.Fatalf("destroy plan err: %s", diags.Err()) } - ctxOpts, m, plan, err := contextOptsForPlanViaFile(snap, plan) + ctxOpts, m, plan, err := contextOptsForPlanViaFile(t, snap, plan) if err != nil { t.Fatalf("failed to round-trip through planfile: %s", err) } @@ -8860,7 +8860,7 @@ func TestContext2Apply_plannedInterpolatedCount(t *testing.T) { // We'll marshal and unmarshal the plan here, to ensure that we have // a clean new context as would be created if we separately ran // terraform plan -out=tfplan && terraform apply tfplan - ctxOpts, m, plan, err := contextOptsForPlanViaFile(snap, plan) + ctxOpts, m, plan, err := contextOptsForPlanViaFile(t, snap, plan) if err != nil { t.Fatalf("failed to round-trip through planfile: %s", err) } @@ -8919,7 +8919,7 @@ func TestContext2Apply_plannedDestroyInterpolatedCount(t *testing.T) { // We'll marshal and unmarshal the plan here, to ensure that we have // a clean new context as would be created if we separately ran // terraform plan -out=tfplan && terraform apply tfplan - ctxOpts, m, plan, err := contextOptsForPlanViaFile(snap, plan) + ctxOpts, m, plan, err := contextOptsForPlanViaFile(t, snap, plan) if err != nil { t.Fatalf("failed to round-trip through planfile: %s", err) } @@ -9440,7 +9440,7 @@ func TestContext2Apply_destroyDataCycle(t *testing.T) { // We'll marshal and unmarshal the plan here, to ensure that we have // a clean new context as would be created if we separately ran // terraform plan -out=tfplan && terraform apply tfplan - ctxOpts, m, plan, err := contextOptsForPlanViaFile(snap, plan) + ctxOpts, m, plan, err := contextOptsForPlanViaFile(t, snap, plan) if err != nil { t.Fatal(err) } @@ -9791,7 +9791,7 @@ func TestContext2Apply_cbdCycle(t *testing.T) { // We'll marshal and unmarshal the plan here, to ensure that we have // a clean new context as would be created if we separately ran // terraform plan -out=tfplan && terraform apply tfplan - ctxOpts, m, plan, err := contextOptsForPlanViaFile(snap, plan) + ctxOpts, m, plan, err := contextOptsForPlanViaFile(t, snap, plan) if err != nil { t.Fatal(err) } diff --git a/internal/terraform/context_test.go b/internal/terraform/context_test.go index e40a95058a..d1926a8803 100644 --- a/internal/terraform/context_test.go +++ b/internal/terraform/context_test.go @@ -4,8 +4,6 @@ import ( "bufio" "bytes" "fmt" - "io/ioutil" - "os" "path/filepath" "sort" "strings" @@ -613,8 +611,8 @@ func testProviderSchema(name string) *providers.GetProviderSchemaResponse { }) } -// contextForPlanViaFile is a helper that creates a temporary plan file, then -// reads it back in again and produces a ContextOpts object containing the +// contextOptsForPlanViaFile is a helper that creates a temporary plan file, +// then reads it back in again and produces a ContextOpts object containing the // planned changes, prior state and config from the plan file. // // This is intended for testing the separated plan/apply workflow in a more @@ -623,12 +621,8 @@ func testProviderSchema(name string) *providers.GetProviderSchemaResponse { // our context tests try to exercise lots of stuff at once and so having them // round-trip things through on-disk files is often an important part of // fully representing an old bug in a regression test. -func contextOptsForPlanViaFile(configSnap *configload.Snapshot, plan *plans.Plan) (*ContextOpts, *configs.Config, *plans.Plan, error) { - dir, err := ioutil.TempDir("", "terraform-contextForPlanViaFile") - if err != nil { - return nil, nil, nil, err - } - defer os.RemoveAll(dir) +func contextOptsForPlanViaFile(t *testing.T, configSnap *configload.Snapshot, plan *plans.Plan) (*ContextOpts, *configs.Config, *plans.Plan, error) { + dir := t.TempDir() // We'll just create a dummy statefile.File here because we're not going // to run through any of the codepaths that care about Lineage/Serial/etc @@ -655,7 +649,7 @@ func contextOptsForPlanViaFile(configSnap *configload.Snapshot, plan *plans.Plan } filename := filepath.Join(dir, "tfplan") - err = planfile.Create(filename, planfile.CreateArgs{ + err := planfile.Create(filename, planfile.CreateArgs{ ConfigSnapshot: configSnap, PreviousRunStateFile: prevStateFile, StateFile: stateFile, diff --git a/internal/terraform/terraform_test.go b/internal/terraform/terraform_test.go index 51c1579ecc..a3d81b7b6b 100644 --- a/internal/terraform/terraform_test.go +++ b/internal/terraform/terraform_test.go @@ -4,7 +4,6 @@ import ( "context" "flag" "io" - "io/ioutil" "os" "path/filepath" "strings" @@ -86,11 +85,7 @@ func testModuleWithSnapshot(t *testing.T, name string) (*configs.Config, *config func testModuleInline(t *testing.T, sources map[string]string) *configs.Config { t.Helper() - cfgPath, err := ioutil.TempDir("", "tf-test") - if err != nil { - t.Errorf("Error creating temporary directory for config: %s", err) - } - defer os.RemoveAll(cfgPath) + cfgPath := t.TempDir() for path, configStr := range sources { dir := filepath.Dir(path)