all: use t.TempDir in tests

This removes all usage of ioutil.TempDir in tests (and a few cases of
os.TempDir as well, while we're at it), which simplifies test cleanup a
lot.

Compile tested (go test -c) for most platforms (except zos).

Change-Id: I9178f5ec615c0a6cfef36e8de78c6b72e055b7cb
Reviewed-on: https://go-review.googlesource.com/c/sys/+/526297
Reviewed-by: Tobias Klauser <tobias.klauser@gmail.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: qiulaidongfeng <2645477756@qq.com>
Auto-Submit: Ian Lance Taylor <iant@golang.org>
This commit is contained in:
Kir Kolyshkin
2023-09-08 15:25:11 +00:00
committed by Gopher Robot
parent 0514fecd90
commit 0e97d69659
12 changed files with 35 additions and 178 deletions
+4 -12
View File
@@ -58,16 +58,12 @@ func TestCommand(t *testing.T) {
func(s string) *Cmd { return Command(s) }, func(s string) *Cmd { return Command(s) },
func(s string) *Cmd { return CommandContext(context.Background(), s) }, func(s string) *Cmd { return CommandContext(context.Background(), s) },
} { } {
tmpDir, err := ioutil.TempDir("", "execabs-test") tmpDir := t.TempDir()
if err != nil {
t.Fatalf("ioutil.TempDir failed: %s", err)
}
defer os.RemoveAll(tmpDir)
executable := "execabs-test" executable := "execabs-test"
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
executable += ".exe" executable += ".exe"
} }
if err = ioutil.WriteFile(filepath.Join(tmpDir, executable), []byte{1, 2, 3}, 0111); err != nil { if err := ioutil.WriteFile(filepath.Join(tmpDir, executable), []byte{1, 2, 3}, 0111); err != nil {
t.Fatalf("ioutil.WriteFile failed: %s", err) t.Fatalf("ioutil.WriteFile failed: %s", err)
} }
cwd, err := os.Getwd() cwd, err := os.Getwd()
@@ -97,16 +93,12 @@ func TestCommand(t *testing.T) {
func TestLookPath(t *testing.T) { func TestLookPath(t *testing.T) {
mustHaveExec(t) mustHaveExec(t)
tmpDir, err := ioutil.TempDir("", "execabs-test") tmpDir := t.TempDir()
if err != nil {
t.Fatalf("ioutil.TempDir failed: %s", err)
}
defer os.RemoveAll(tmpDir)
executable := "execabs-test" executable := "execabs-test"
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
executable += ".exe" executable += ".exe"
} }
if err = ioutil.WriteFile(filepath.Join(tmpDir, executable), []byte{1, 2, 3}, 0111); err != nil { if err := ioutil.WriteFile(filepath.Join(tmpDir, executable), []byte{1, 2, 3}, 0111); err != nil {
t.Fatalf("ioutil.WriteFile failed: %s", err) t.Fatalf("ioutil.WriteFile failed: %s", err)
} }
cwd, err := os.Getwd() cwd, err := os.Getwd()
+4 -13
View File
@@ -11,7 +11,6 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os"
"path/filepath" "path/filepath"
"runtime" "runtime"
"sort" "sort"
@@ -29,16 +28,12 @@ func TestDirent(t *testing.T) {
filenameMinSize = 11 filenameMinSize = 11
) )
d, err := ioutil.TempDir("", "dirent-test") d := t.TempDir()
if err != nil {
t.Fatalf("tempdir: %v", err)
}
defer os.RemoveAll(d)
t.Logf("tmpdir: %s", d) t.Logf("tmpdir: %s", d)
for i, c := range []byte("0123456789") { for i, c := range []byte("0123456789") {
name := string(bytes.Repeat([]byte{c}, filenameMinSize+i)) name := string(bytes.Repeat([]byte{c}, filenameMinSize+i))
err = ioutil.WriteFile(filepath.Join(d, name), nil, 0644) err := ioutil.WriteFile(filepath.Join(d, name), nil, 0644)
if err != nil { if err != nil {
t.Fatalf("writefile: %v", err) t.Fatalf("writefile: %v", err)
} }
@@ -98,18 +93,14 @@ func TestDirentRepeat(t *testing.T) {
} }
// Make a directory containing N files // Make a directory containing N files
d, err := ioutil.TempDir("", "direntRepeat-test") d := t.TempDir()
if err != nil {
t.Fatalf("tempdir: %v", err)
}
defer os.RemoveAll(d)
var files []string var files []string
for i := 0; i < N; i++ { for i := 0; i < N; i++ {
files = append(files, fmt.Sprintf("file%d", i)) files = append(files, fmt.Sprintf("file%d", i))
} }
for _, file := range files { for _, file := range files {
err = ioutil.WriteFile(filepath.Join(d, file), []byte("contents"), 0644) err := ioutil.WriteFile(filepath.Join(d, file), []byte("contents"), 0644)
if err != nil { if err != nil {
t.Fatalf("writefile: %v", err) t.Fatalf("writefile: %v", err)
} }
+2 -5
View File
@@ -30,11 +30,8 @@ func testGetdirentries(t *testing.T, count int) {
if count > 100 && testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" { if count > 100 && testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" {
t.Skip("skipping in -short mode") t.Skip("skipping in -short mode")
} }
d, err := ioutil.TempDir("", "getdirentries-test") d := t.TempDir()
if err != nil {
t.Fatalf("Tempdir: %v", err)
}
defer os.RemoveAll(d)
var names []string var names []string
for i := 0; i < count; i++ { for i := 0; i < count; i++ {
names = append(names, fmt.Sprintf("file%03d", i)) names = append(names, fmt.Sprintf("file%03d", i))
+5 -15
View File
@@ -21,14 +21,16 @@ import (
) )
func TestMmap(t *testing.T) { func TestMmap(t *testing.T) {
tmpdir := mktmpdir(t) tmpdir := filepath.Join(t.TempDir(), "testdata")
filename := filepath.Join(filepath.Join(tmpdir, "testdata"), "memmapped_file") if err := os.Mkdir(tmpdir, 0700); err != nil {
t.Fatal(err)
}
filename := filepath.Join(tmpdir, "memmapped_file")
destination, err := os.Create(filename) destination, err := os.Create(filename)
if err != nil { if err != nil {
t.Fatal("os.Create:", err) t.Fatal("os.Create:", err)
return return
} }
defer os.RemoveAll(tmpdir)
fmt.Fprintf(destination, "%s\n", "0 <- Flipped between 0 and 1 when test runs successfully") fmt.Fprintf(destination, "%s\n", "0 <- Flipped between 0 and 1 when test runs successfully")
fmt.Fprintf(destination, "%s\n", "//Do not change contents - mmap test relies on this") fmt.Fprintf(destination, "%s\n", "//Do not change contents - mmap test relies on this")
@@ -73,15 +75,3 @@ func TestMmap(t *testing.T) {
t.Fatalf("Munmap: %v", err) t.Fatalf("Munmap: %v", err)
} }
} }
func mktmpdir(t *testing.T) string {
tmpdir, err := ioutil.TempDir("", "memmapped_file")
if err != nil {
t.Fatal("mktmpdir:", err)
}
if err := os.Mkdir(filepath.Join(tmpdir, "testdata"), 0700); err != nil {
os.RemoveAll(tmpdir)
t.Fatal("mktmpdir:", err)
}
return tmpdir
}
+2 -7
View File
@@ -19,14 +19,9 @@ import (
func TestSendfile(t *testing.T) { func TestSendfile(t *testing.T) {
// Set up source data file. // Set up source data file.
tempDir, err := ioutil.TempDir("", "TestSendfile") name := filepath.Join(t.TempDir(), "source")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempDir)
name := filepath.Join(tempDir, "source")
const contents = "contents" const contents = "contents"
err = ioutil.WriteFile(name, []byte(contents), 0666) err := ioutil.WriteFile(name, []byte(contents), 0666)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
+2 -11
View File
@@ -99,17 +99,8 @@ func TestClonefileatWithCwd(t *testing.T) {
} }
func TestClonefileatWithRelativePaths(t *testing.T) { func TestClonefileatWithRelativePaths(t *testing.T) {
srcDir, err := ioutil.TempDir("", "src") srcDir := t.TempDir()
if err != nil { dstDir := t.TempDir()
t.Fatal(err)
}
defer os.RemoveAll(srcDir)
dstDir, err := ioutil.TempDir("", "dest")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dstDir)
srcFd, err := unix.Open(srcDir, unix.O_RDONLY|unix.O_DIRECTORY, 0) srcFd, err := unix.Open(srcDir, unix.O_RDONLY|unix.O_DIRECTORY, 0)
if err != nil { if err != nil {
+3 -35
View File
@@ -10,7 +10,6 @@ package unix_test
import ( import (
"flag" "flag"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"os" "os"
"os/exec" "os/exec"
@@ -34,10 +33,8 @@ func TestSysctlUint64(t *testing.T) {
// corresponding to the given key. // corresponding to the given key.
type testProc struct { type testProc struct {
fn func() // should always exit instead of returning fn func() // should always exit instead of returning
arg func(t *testing.T) string // generate argument for test success bool // whether zero-exit means success or failure
cleanup func(arg string) error // for instance, delete coredumps from testing pledge
success bool // whether zero-exit means success or failure
} }
var ( var (
@@ -71,16 +68,7 @@ func testCmd(procName string, procArg string) (*exec.Cmd, error) {
// a testProc with a key. // a testProc with a key.
func ExitsCorrectly(t *testing.T, procName string) { func ExitsCorrectly(t *testing.T, procName string) {
s := testProcs[procName] s := testProcs[procName]
arg := "-" c, err := testCmd(procName, t.TempDir())
if s.arg != nil {
arg = s.arg(t)
}
c, err := testCmd(procName, arg)
defer func(arg string) {
if err := s.cleanup(arg); err != nil {
t.Fatalf("Failed to run cleanup for %s %s %#v", procName, err, err)
}
}(arg)
if err != nil { if err != nil {
t.Fatalf("Failed to construct command for %s", procName) t.Fatalf("Failed to construct command for %s", procName)
} }
@@ -134,27 +122,9 @@ func CapEnterTest() {
os.Exit(0) os.Exit(0)
} }
func makeTempDir(t *testing.T) string {
d, err := ioutil.TempDir("", "go_openat_test")
if err != nil {
t.Fatalf("TempDir failed: %s", err)
}
return d
}
func removeTempDir(arg string) error {
err := os.RemoveAll(arg)
if err != nil && err.(*os.PathError).Err == unix.ENOENT {
return nil
}
return err
}
func init() { func init() {
testProcs["cap_enter"] = testProc{ testProcs["cap_enter"] = testProc{
CapEnterTest, CapEnterTest,
makeTempDir,
removeTempDir,
true, true,
} }
} }
@@ -252,8 +222,6 @@ func OpenatTest() {
func init() { func init() {
testProcs["openat"] = testProc{ testProcs["openat"] = testProc{
OpenatTest, OpenatTest,
makeTempDir,
removeTempDir,
true, true,
} }
} }
+1 -7
View File
@@ -986,13 +986,7 @@ func TestOpenat2(t *testing.T) {
} }
// prepare // prepare
tempDir, err := ioutil.TempDir("", t.Name()) subdir := filepath.Join(t.TempDir(), "dir")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempDir)
subdir := filepath.Join(tempDir, "dir")
if err := os.Mkdir(subdir, 0755); err != nil { if err := os.Mkdir(subdir, 0755); err != nil {
t.Fatal(err) t.Fatal(err)
} }
+4 -24
View File
@@ -145,12 +145,11 @@ func TestFcntlInt(t *testing.T) {
// TestFcntlFlock tests whether the file locking structure matches // TestFcntlFlock tests whether the file locking structure matches
// the calling convention of each kernel. // the calling convention of each kernel.
func TestFcntlFlock(t *testing.T) { func TestFcntlFlock(t *testing.T) {
name := filepath.Join(os.TempDir(), "TestFcntlFlock") name := filepath.Join(t.TempDir(), "TestFcntlFlock")
fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0) fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0)
if err != nil { if err != nil {
t.Fatalf("Open failed: %v", err) t.Fatalf("Open failed: %v", err)
} }
defer unix.Unlink(name)
defer unix.Close(fd) defer unix.Close(fd)
flock := unix.Flock_t{ flock := unix.Flock_t{
Type: unix.F_RDLCK, Type: unix.F_RDLCK,
@@ -199,12 +198,6 @@ func TestPassFD(t *testing.T) {
} }
} }
tempDir, err := ioutil.TempDir("", "TestPassFD")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempDir)
fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0) fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
if err != nil { if err != nil {
t.Fatalf("Socketpair: %v", err) t.Fatalf("Socketpair: %v", err)
@@ -214,7 +207,7 @@ func TestPassFD(t *testing.T) {
defer writeFile.Close() defer writeFile.Close()
defer readFile.Close() defer readFile.Close()
cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir) cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", t.TempDir())
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" { if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp) cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
@@ -659,15 +652,7 @@ func TestGetwd(t *testing.T) {
case "android": case "android":
dirs = []string{"/", "/system/bin"} dirs = []string{"/", "/system/bin"}
case "ios": case "ios":
d1, err := ioutil.TempDir("", "d1") dirs = []string{t.TempDir(), t.TempDir()}
if err != nil {
t.Fatalf("TempDir: %v", err)
}
d2, err := ioutil.TempDir("", "d2")
if err != nil {
t.Fatalf("TempDir: %v", err)
}
dirs = []string{d1, d2}
} }
oldwd := os.Getenv("PWD") oldwd := os.Getenv("PWD")
for _, d := range dirs { for _, d := range dirs {
@@ -1166,17 +1151,12 @@ func chtmpdir(t *testing.T) func() {
if err != nil { if err != nil {
t.Fatalf("chtmpdir: %v", err) t.Fatalf("chtmpdir: %v", err)
} }
d, err := ioutil.TempDir("", "test") if err := os.Chdir(t.TempDir()); err != nil {
if err != nil {
t.Fatalf("chtmpdir: %v", err)
}
if err := os.Chdir(d); err != nil {
t.Fatalf("chtmpdir: %v", err) t.Fatalf("chtmpdir: %v", err)
} }
return func() { return func() {
if err := os.Chdir(oldwd); err != nil { if err := os.Chdir(oldwd); err != nil {
t.Fatalf("chtmpdir: %v", err) t.Fatalf("chtmpdir: %v", err)
} }
os.RemoveAll(d)
} }
} }
+5 -29
View File
@@ -143,12 +143,11 @@ func TestFcntlInt(t *testing.T) {
// TestFcntlFlock tests whether the file locking structure matches // TestFcntlFlock tests whether the file locking structure matches
// the calling convention of each kernel. // the calling convention of each kernel.
func TestFcntlFlock(t *testing.T) { func TestFcntlFlock(t *testing.T) {
name := filepath.Join(os.TempDir(), "TestFcntlFlock") name := filepath.Join(t.TempDir(), "TestFcntlFlock")
fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0) fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0)
if err != nil { if err != nil {
t.Fatalf("Open failed: %v", err) t.Fatalf("Open failed: %v", err)
} }
defer unix.Unlink(name)
defer unix.Close(fd) defer unix.Close(fd)
flock := unix.Flock_t{ flock := unix.Flock_t{
Type: unix.F_RDLCK, Type: unix.F_RDLCK,
@@ -197,12 +196,6 @@ func TestPassFD(t *testing.T) {
} }
} }
tempDir, err := ioutil.TempDir("", "TestPassFD")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempDir)
fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0) fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
if err != nil { if err != nil {
t.Fatalf("Socketpair: %v", err) t.Fatalf("Socketpair: %v", err)
@@ -212,7 +205,7 @@ func TestPassFD(t *testing.T) {
defer writeFile.Close() defer writeFile.Close()
defer readFile.Close() defer readFile.Close()
cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir) cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", t.TempDir())
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" { if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp) cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
@@ -493,15 +486,7 @@ func TestGetwd(t *testing.T) {
case "darwin": case "darwin":
switch runtime.GOARCH { switch runtime.GOARCH {
case "arm64": case "arm64":
d1, err := ioutil.TempDir("", "d1") dirs = []string{t.TempDir(), t.TempDir()}
if err != nil {
t.Fatalf("TempDir: %v", err)
}
d2, err := ioutil.TempDir("", "d2")
if err != nil {
t.Fatalf("TempDir: %v", err)
}
dirs = []string{d1, d2}
} }
} }
oldwd := os.Getenv("PWD") oldwd := os.Getenv("PWD")
@@ -629,11 +614,7 @@ func TestMountUnmount(t *testing.T) {
func TestChroot(t *testing.T) { func TestChroot(t *testing.T) {
// create temp dir and tempfile 1 // create temp dir and tempfile 1
tempDir, err := ioutil.TempDir("", "TestChroot") tempDir := t.TempDir()
if err != nil {
t.Fatalf("TempDir: %s", err.Error())
}
defer os.RemoveAll(tempDir)
f, err := ioutil.TempFile(tempDir, "chroot_test_file") f, err := ioutil.TempFile(tempDir, "chroot_test_file")
if err != nil { if err != nil {
t.Fatalf("TempFile: %s", err.Error()) t.Fatalf("TempFile: %s", err.Error())
@@ -686,12 +667,7 @@ func TestFlock(t *testing.T) {
} }
} else { } else {
// create temp dir and tempfile 1 // create temp dir and tempfile 1
tempDir, err := ioutil.TempDir("", "TestFlock") f, err := ioutil.TempFile(t.TempDir(), "flock_test_file")
if err != nil {
t.Fatalf("TempDir: %s", err.Error())
}
defer os.RemoveAll(tempDir)
f, err := ioutil.TempFile(tempDir, "flock_test_file")
if err != nil { if err != nil {
t.Fatalf("TempFile: %s", err.Error()) t.Fatalf("TempFile: %s", err.Error())
} }
+1 -7
View File
@@ -93,13 +93,7 @@ func TestExample(t *testing.T) {
} }
defer m.Disconnect() defer m.Disconnect()
dir, err := ioutil.TempDir("", "svc") exepath := filepath.Join(t.TempDir(), "a.exe")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
defer os.RemoveAll(dir)
exepath := filepath.Join(dir, "a.exe")
o, err := exec.Command("go", "build", "-o", exepath, "golang.org/x/sys/windows/svc/example").CombinedOutput() o, err := exec.Command("go", "build", "-o", exepath, "golang.org/x/sys/windows/svc/example").CombinedOutput()
if err != nil { if err != nil {
t.Fatalf("failed to build service program: %v\n%v", err, string(o)) t.Fatalf("failed to build service program: %v\n%v", err, string(o))
+2 -13
View File
@@ -27,13 +27,7 @@ import (
) )
func TestWin32finddata(t *testing.T) { func TestWin32finddata(t *testing.T) {
dir, err := ioutil.TempDir("", "go-build") path := filepath.Join(t.TempDir(), "long_name.and_extension")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "long_name.and_extension")
f, err := os.Create(path) f, err := os.Create(path)
if err != nil { if err != nil {
t.Fatalf("failed to create %v: %v", path, err) t.Fatalf("failed to create %v: %v", path, err)
@@ -673,12 +667,7 @@ func TestWinVerifyTrust(t *testing.T) {
// Now that we've verified the legitimate file verifies, let's corrupt it and see if it correctly fails. // Now that we've verified the legitimate file verifies, let's corrupt it and see if it correctly fails.
dir, err := ioutil.TempDir("", "go-build") corruptedEvsignedfile := filepath.Join(t.TempDir(), "corrupted-file")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
defer os.RemoveAll(dir)
corruptedEvsignedfile := filepath.Join(dir, "corrupted-file")
evsignedfileBytes, err := ioutil.ReadFile(evsignedfile) evsignedfileBytes, err := ioutil.ReadFile(evsignedfile)
if err != nil { if err != nil {
t.Fatalf("unable to read %s bytes: %v", evsignedfile, err) t.Fatalf("unable to read %s bytes: %v", evsignedfile, err)