1+ // +build !windows
2+
3+ // TODO: implement readdir for windows, then enable this file
4+
15// Copyright 2014 The Go Authors. All rights reserved.
26// Use of this source code is governed by a BSD-style
37// license that can be found in the LICENSE file.
@@ -6,6 +10,7 @@ package testing_test
610
711import (
812 "os"
13+ "path/filepath"
914 "testing"
1015)
1116
@@ -16,3 +21,101 @@ import (
1621func TestMain (m * testing.M ) {
1722 os .Exit (m .Run ())
1823}
24+
25+ func TestTempDirInCleanup (t * testing.T ) {
26+ var dir string
27+
28+ t .Run ("test" , func (t * testing.T ) {
29+ t .Cleanup (func () {
30+ dir = t .TempDir ()
31+ })
32+ _ = t .TempDir ()
33+ })
34+
35+ fi , err := os .Stat (dir )
36+ if fi != nil {
37+ t .Fatalf ("Directory %q from user Cleanup still exists" , dir )
38+ }
39+ if ! os .IsNotExist (err ) {
40+ t .Fatalf ("Unexpected error: %v" , err )
41+ }
42+ }
43+
44+ func TestTempDirInBenchmark (t * testing.T ) {
45+ testing .Benchmark (func (b * testing.B ) {
46+ if ! b .Run ("test" , func (b * testing.B ) {
47+ // Add a loop so that the test won't fail. See issue 38677.
48+ for i := 0 ; i < b .N ; i ++ {
49+ _ = b .TempDir ()
50+ }
51+ }) {
52+ t .Fatal ("Sub test failure in a benchmark" )
53+ }
54+ })
55+ }
56+
57+ func TestTempDir (t * testing.T ) {
58+ testTempDir (t )
59+ t .Run ("InSubtest" , testTempDir )
60+ t .Run ("test/subtest" , testTempDir )
61+ t .Run ("test\\ subtest" , testTempDir )
62+ t .Run ("test:subtest" , testTempDir )
63+ t .Run ("test/.." , testTempDir )
64+ t .Run ("../test" , testTempDir )
65+ t .Run ("test[]" , testTempDir )
66+ t .Run ("test*" , testTempDir )
67+ t .Run ("äöüéè" , testTempDir )
68+ }
69+
70+ func testTempDir (t * testing.T ) {
71+ dirCh := make (chan string , 1 )
72+ t .Cleanup (func () {
73+ // Verify directory has been removed.
74+ select {
75+ case dir := <- dirCh :
76+ fi , err := os .Stat (dir )
77+ if os .IsNotExist (err ) {
78+ // All good
79+ return
80+ }
81+ if err != nil {
82+ t .Fatal (err )
83+ }
84+ t .Errorf ("directory %q still exists: %v, isDir=%v" , dir , fi , fi .IsDir ())
85+ default :
86+ if ! t .Failed () {
87+ t .Fatal ("never received dir channel" )
88+ }
89+ }
90+ })
91+
92+ dir := t .TempDir ()
93+ if dir == "" {
94+ t .Fatal ("expected dir" )
95+ }
96+ dir2 := t .TempDir ()
97+ if dir == dir2 {
98+ t .Fatal ("subsequent calls to TempDir returned the same directory" )
99+ }
100+ if filepath .Dir (dir ) != filepath .Dir (dir2 ) {
101+ t .Fatalf ("calls to TempDir do not share a parent; got %q, %q" , dir , dir2 )
102+ }
103+ dirCh <- dir
104+ fi , err := os .Stat (dir )
105+ if err != nil {
106+ t .Fatal (err )
107+ }
108+ if ! fi .IsDir () {
109+ t .Errorf ("dir %q is not a dir" , dir )
110+ }
111+
112+ glob := filepath .Join (dir , "*.txt" )
113+ if _ , err := filepath .Glob (glob ); err != nil {
114+ t .Error (err )
115+ }
116+
117+ err = os .Remove (dir )
118+ if err != nil {
119+ t .Errorf ("unexpected files in TempDir" )
120+ }
121+ }
0 commit comments