]> Cypherpunks repositories - gostls13.git/commitdiff
testing: return unique directory inside same base root for TempDir
authorRoger Peppe <rogpeppe@gmail.com>
Mon, 4 May 2020 16:37:10 +0000 (17:37 +0100)
committerroger peppe <rogpeppe@gmail.com>
Tue, 19 May 2020 17:38:32 +0000 (17:38 +0000)
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>
src/testing/testing.go
src/testing/testing_test.go

index 216e46ee81609c3d1c1171214ce8f2f84e15808f..aa1584f2d9f0d1aabe3731d9d6487faa119c5b5e 100644 (file)
@@ -372,6 +372,7 @@ type common struct {
        tempDirOnce sync.Once
        tempDir     string
        tempDirErr  error
+       tempDirSeq  int32
 }
 
 // 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
 // all its subtests complete.
 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.Helper()
 
@@ -849,7 +852,12 @@ func (c *common) TempDir() string {
        if c.tempDirErr != nil {
                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.
index 1340dae5c4d2a72c1c5c6599a111d84a71ac44bf..dbef7066e0e8c121b0bc7c3e6c628ce3482651d4 100644 (file)
@@ -7,6 +7,7 @@ package testing_test
 import (
        "io/ioutil"
        "os"
+       "path/filepath"
        "testing"
 )
 
@@ -55,8 +56,11 @@ func testTempDir(t *testing.T) {
                t.Fatal("expected dir")
        }
        dir2 := t.TempDir()
-       if dir != dir2 {
-               t.Fatal("directory changed between calls")
+       if dir == dir2 {
+               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
        fi, err := os.Stat(dir)