mirror of
https://github.com/golang/go
synced 2024-11-18 08:44:43 -07:00
testing: return unique directory inside same base root for TempDir
We use a single parent directory for all temporary directories created by a test so they're all kept together. Fixes #38850 Change-Id: If8edae10c5136efcbcf6fd632487d198b9e3a868 Reviewed-on: https://go-review.googlesource.com/c/go/+/231958 Reviewed-by: Russ Cox <rsc@golang.org>
This commit is contained in:
parent
8fa468d511
commit
6d6e4827c0
@ -372,6 +372,7 @@ type common struct {
|
|||||||
tempDirOnce sync.Once
|
tempDirOnce sync.Once
|
||||||
tempDir string
|
tempDir string
|
||||||
tempDirErr error
|
tempDirErr error
|
||||||
|
tempDirSeq int32
|
||||||
}
|
}
|
||||||
|
|
||||||
// Short reports whether the -test.short flag is set.
|
// Short reports whether the -test.short flag is set.
|
||||||
@ -827,6 +828,8 @@ var tempDirReplacer struct {
|
|||||||
// The directory is automatically removed by Cleanup when the test and
|
// The directory is automatically removed by Cleanup when the test and
|
||||||
// all its subtests complete.
|
// all its subtests complete.
|
||||||
func (c *common) TempDir() string {
|
func (c *common) TempDir() string {
|
||||||
|
// Use a single parent directory for all the temporary directories
|
||||||
|
// created by a test, each numbered sequentially.
|
||||||
c.tempDirOnce.Do(func() {
|
c.tempDirOnce.Do(func() {
|
||||||
c.Helper()
|
c.Helper()
|
||||||
|
|
||||||
@ -849,7 +852,12 @@ func (c *common) TempDir() string {
|
|||||||
if c.tempDirErr != nil {
|
if c.tempDirErr != nil {
|
||||||
c.Fatalf("TempDir: %v", c.tempDirErr)
|
c.Fatalf("TempDir: %v", c.tempDirErr)
|
||||||
}
|
}
|
||||||
return c.tempDir
|
seq := atomic.AddInt32(&c.tempDirSeq, 1)
|
||||||
|
dir := fmt.Sprintf("%s%c%03d", c.tempDir, os.PathSeparator, seq)
|
||||||
|
if err := os.Mkdir(dir, 0777); err != nil {
|
||||||
|
c.Fatalf("TempDir: %v", err)
|
||||||
|
}
|
||||||
|
return dir
|
||||||
}
|
}
|
||||||
|
|
||||||
// panicHanding is an argument to runCleanup.
|
// panicHanding is an argument to runCleanup.
|
||||||
|
@ -7,6 +7,7 @@ package testing_test
|
|||||||
import (
|
import (
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -55,8 +56,11 @@ func testTempDir(t *testing.T) {
|
|||||||
t.Fatal("expected dir")
|
t.Fatal("expected dir")
|
||||||
}
|
}
|
||||||
dir2 := t.TempDir()
|
dir2 := t.TempDir()
|
||||||
if dir != dir2 {
|
if dir == dir2 {
|
||||||
t.Fatal("directory changed between calls")
|
t.Fatal("subsequent calls to TempDir returned the same directory")
|
||||||
|
}
|
||||||
|
if filepath.Dir(dir) != filepath.Dir(dir2) {
|
||||||
|
t.Fatalf("calls to TempDir do not share a parent; got %q, %q", dir, dir2)
|
||||||
}
|
}
|
||||||
dirCh <- dir
|
dirCh <- dir
|
||||||
fi, err := os.Stat(dir)
|
fi, err := os.Stat(dir)
|
||||||
|
Loading…
Reference in New Issue
Block a user