From 721819e7bad078ac350bdebebb28793e13081e82 Mon Sep 17 00:00:00 2001 From: Changkun Ou Date: Fri, 28 Aug 2020 12:13:37 +0200 Subject: testing: make TempDir idempotent for both Cleanup and Benchmark Ensures that calling TempDir() in either of Cleanup or Benchmark doesn't cause test failures which were previously caused by the created directory having been deleted after the first run, yet we prevented the recreation of the directory due to our selection of concurrency primitive sync.Once. This change recreates the temporary directory if it doesn't exist, regardless of how many times Cleanup and Benchmark are invoked. Fixes #41062 Change-Id: I925d9f7207d7c369a193d1e17da7a59a586244a7 Reviewed-on: https://go-review.googlesource.com/c/go/+/251297 Reviewed-by: Emmanuel Odeke Run-TryBot: Emmanuel Odeke TryBot-Result: Gobot Gobot --- src/testing/testing_test.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'src/testing/testing_test.go') diff --git a/src/testing/testing_test.go b/src/testing/testing_test.go index dbef7066e0..d665a334e4 100644 --- a/src/testing/testing_test.go +++ b/src/testing/testing_test.go @@ -19,6 +19,38 @@ func TestMain(m *testing.M) { os.Exit(m.Run()) } +func TestTempDirInCleanup(t *testing.T) { + var dir string + + t.Run("test", func(t *testing.T) { + t.Cleanup(func() { + dir = t.TempDir() + }) + _ = t.TempDir() + }) + + fi, err := os.Stat(dir) + if fi != nil { + t.Fatalf("Directory %q from user Cleanup still exists", dir) + } + if !os.IsNotExist(err) { + t.Fatalf("Unexpected error: %v", err) + } +} + +func TestTempDirInBenchmark(t *testing.T) { + testing.Benchmark(func(b *testing.B) { + if !b.Run("test", func(b *testing.B) { + // Add a loop so that the test won't fail. See issue 38677. + for i := 0; i < b.N; i++ { + _ = b.TempDir() + } + }) { + t.Fatal("Sub test failure in a benchmark") + } + }) +} + func TestTempDir(t *testing.T) { testTempDir(t) t.Run("InSubtest", testTempDir) -- cgit v1.3-5-g9baa