1 // Copyright 2010 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 ioutil 6 7 import ( 8 "os" 9 "path/filepath" 10 "regexp" 11 "testing" 12 ) 13 14 func TestTempFile(t *testing.T) { 15 dir, err := TempDir("", "TestTempFile_BadDir") 16 if err != nil { 17 t.Fatal(err) 18 } 19 defer os.RemoveAll(dir) 20 21 nonexistentDir := filepath.Join(dir, "_not_exists_") 22 f, err := TempFile(nonexistentDir, "foo") 23 if f != nil || err == nil { 24 t.Errorf("TempFile(%q, `foo`) = %v, %v", nonexistentDir, f, err) 25 } 26 27 dir = os.TempDir() 28 f, err = TempFile(dir, "ioutil_test") 29 if f == nil || err != nil { 30 t.Errorf("TempFile(dir, `ioutil_test`) = %v, %v", f, err) 31 } 32 if f != nil { 33 f.Close() 34 os.Remove(f.Name()) 35 re := regexp.MustCompile("^" + regexp.QuoteMeta(filepath.Join(dir, "ioutil_test")) + "[0-9]+$") 36 if !re.MatchString(f.Name()) { 37 t.Errorf("TempFile(`"+dir+"`, `ioutil_test`) created bad name %s", f.Name()) 38 } 39 } 40 } 41 42 func TestTempDir(t *testing.T) { 43 name, err := TempDir("/_not_exists_", "foo") 44 if name != "" || err == nil { 45 t.Errorf("TempDir(`/_not_exists_`, `foo`) = %v, %v", name, err) 46 } 47 48 dir := os.TempDir() 49 name, err = TempDir(dir, "ioutil_test") 50 if name == "" || err != nil { 51 t.Errorf("TempDir(dir, `ioutil_test`) = %v, %v", name, err) 52 } 53 if name != "" { 54 os.Remove(name) 55 re := regexp.MustCompile("^" + regexp.QuoteMeta(filepath.Join(dir, "ioutil_test")) + "[0-9]+$") 56 if !re.MatchString(name) { 57 t.Errorf("TempDir(`"+dir+"`, `ioutil_test`) created bad name %s", name) 58 } 59 } 60 } 61 62 // test that we return a nice error message if the dir argument to TempDir doesn't 63 // exist (or that it's empty and os.TempDir doesn't exist) 64 func TestTempDir_BadDir(t *testing.T) { 65 dir, err := TempDir("", "TestTempDir_BadDir") 66 if err != nil { 67 t.Fatal(err) 68 } 69 defer os.RemoveAll(dir) 70 71 badDir := filepath.Join(dir, "not-exist") 72 _, err = TempDir(badDir, "foo") 73 if pe, ok := err.(*os.PathError); !ok || !os.IsNotExist(err) || pe.Path != badDir { 74 t.Errorf("TempDir error = %#v; want PathError for path %q satisifying os.IsNotExist", err, badDir) 75 } 76 } 77