test: use T.TempDir to create temporary test directory (#30803)

This commit replaces `ioutil.TempDir` with `t.TempDir` in tests. The
directory created by `t.TempDir` is automatically removed when the test
and all its subtests complete.

Prior to this commit, temporary directory created using `ioutil.TempDir`
needs to be removed manually by calling `os.RemoveAll`, which is omitted
in some tests. The error handling boilerplate e.g.
	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			t.Fatal(err)
		}
	}
is also tedious, but `t.TempDir` handles this for us nicely.

Reference: https://pkg.go.dev/testing#T.TempDir
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
This commit is contained in:
Eng Zer Jun
2022-04-09 00:34:16 +08:00
committed by GitHub
parent 5b615882e2
commit fedd315275
66 changed files with 373 additions and 852 deletions

View File

@@ -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{}