testing: add TB.TempDir

Fixes #35998

Change-Id: I87c6bf4e34e832be68862ca16ecfa6ea12048d31
Reviewed-on: https://go-review.googlesource.com/c/go/+/226877
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
This commit is contained in:
Brad Fitzpatrick 2020-04-01 10:43:57 -07:00
parent 2bed279721
commit 888a0c8ef6
6 changed files with 94 additions and 7 deletions

View file

@ -239,6 +239,7 @@ import (
"fmt"
"internal/race"
"io"
"io/ioutil"
"os"
"runtime"
"runtime/debug"
@ -362,6 +363,10 @@ type common struct {
barrier chan bool // To signal parallel subtests they may start.
signal chan bool // To signal a test is done.
sub []*T // Queue of subtests to be run in parallel.
tempDirOnce sync.Once
tempDir string
tempDirErr error
}
// Short reports whether the -test.short flag is set.
@ -561,6 +566,7 @@ type TB interface {
SkipNow()
Skipf(format string, args ...interface{})
Skipped() bool
TempDir() string
// A private method to prevent users implementing the
// interface and so future additions to it will not
@ -791,6 +797,30 @@ func (c *common) Cleanup(f func()) {
}
}
// TempDir returns a temporary directory for the test to use.
// It is lazily created on first access, and calls t.Fatal if the directory
// creation fails.
// Subsequent calls to t.TempDir return the same directory.
// The directory is automatically removed by Cleanup when the test and
// all its subtests complete.
func (c *common) TempDir() string {
c.tempDirOnce.Do(func() {
c.Helper()
c.tempDir, c.tempDirErr = ioutil.TempDir("", c.Name())
if c.tempDirErr == nil {
c.Cleanup(func() {
if err := os.RemoveAll(c.tempDir); err != nil {
c.Errorf("TempDir RemoveAll cleanup: %v", err)
}
})
}
})
if c.tempDirErr != nil {
c.Fatalf("TempDir: %v", c.tempDirErr)
}
return c.tempDir
}
// panicHanding is an argument to runCleanup.
type panicHandling int