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

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