github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/testing/testing_test.go (about) 1 // Copyright 2014 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package testing_test 6 7 import ( 8 "os" 9 "path/filepath" 10 "testing" 11 ) 12 13 // This is exactly what a test would do without a TestMain. 14 // It's here only so that there is at least one package in the 15 // standard library with a TestMain, so that code is executed. 16 17 func TestMain(m *testing.M) { 18 os.Exit(m.Run()) 19 } 20 21 func TestTempDirInCleanup(t *testing.T) { 22 var dir string 23 24 t.Run("test", func(t *testing.T) { 25 t.Cleanup(func() { 26 dir = t.TempDir() 27 }) 28 _ = t.TempDir() 29 }) 30 31 fi, err := os.Stat(dir) 32 if fi != nil { 33 t.Fatalf("Directory %q from user Cleanup still exists", dir) 34 } 35 if !os.IsNotExist(err) { 36 t.Fatalf("Unexpected error: %v", err) 37 } 38 } 39 40 func TestTempDirInBenchmark(t *testing.T) { 41 testing.Benchmark(func(b *testing.B) { 42 if !b.Run("test", func(b *testing.B) { 43 // Add a loop so that the test won't fail. See issue 38677. 44 for i := 0; i < b.N; i++ { 45 _ = b.TempDir() 46 } 47 }) { 48 t.Fatal("Sub test failure in a benchmark") 49 } 50 }) 51 } 52 53 func TestTempDir(t *testing.T) { 54 testTempDir(t) 55 t.Run("InSubtest", testTempDir) 56 t.Run("test/subtest", testTempDir) 57 t.Run("test\\subtest", testTempDir) 58 t.Run("test:subtest", testTempDir) 59 t.Run("test/..", testTempDir) 60 t.Run("../test", testTempDir) 61 } 62 63 func testTempDir(t *testing.T) { 64 dirCh := make(chan string, 1) 65 t.Cleanup(func() { 66 // Verify directory has been removed. 67 select { 68 case dir := <-dirCh: 69 fi, err := os.Stat(dir) 70 if os.IsNotExist(err) { 71 // All good 72 return 73 } 74 if err != nil { 75 t.Fatal(err) 76 } 77 t.Errorf("directory %q stil exists: %v, isDir=%v", dir, fi, fi.IsDir()) 78 default: 79 if !t.Failed() { 80 t.Fatal("never received dir channel") 81 } 82 } 83 }) 84 85 dir := t.TempDir() 86 if dir == "" { 87 t.Fatal("expected dir") 88 } 89 dir2 := t.TempDir() 90 if dir == dir2 { 91 t.Fatal("subsequent calls to TempDir returned the same directory") 92 } 93 if filepath.Dir(dir) != filepath.Dir(dir2) { 94 t.Fatalf("calls to TempDir do not share a parent; got %q, %q", dir, dir2) 95 } 96 dirCh <- dir 97 fi, err := os.Stat(dir) 98 if err != nil { 99 t.Fatal(err) 100 } 101 if !fi.IsDir() { 102 t.Errorf("dir %q is not a dir", dir) 103 } 104 files, err := os.ReadDir(dir) 105 if err != nil { 106 t.Fatal(err) 107 } 108 if len(files) > 0 { 109 t.Errorf("unexpected %d files in TempDir: %v", len(files), files) 110 } 111 }