github.com/megatontech/mynoteforgo@v0.0.0-20200507084910-5d0c6ea6e890/源码/io/ioutil/tempfile_test.go (about) 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 "strings" 12 "testing" 13 ) 14 15 func TestTempFile(t *testing.T) { 16 dir, err := TempDir("", "TestTempFile_BadDir") 17 if err != nil { 18 t.Fatal(err) 19 } 20 defer os.RemoveAll(dir) 21 22 nonexistentDir := filepath.Join(dir, "_not_exists_") 23 f, err := TempFile(nonexistentDir, "foo") 24 if f != nil || err == nil { 25 t.Errorf("TempFile(%q, `foo`) = %v, %v", nonexistentDir, f, err) 26 } 27 } 28 29 func TestTempFile_pattern(t *testing.T) { 30 tests := []struct{ pattern, prefix, suffix string }{ 31 {"ioutil_test", "ioutil_test", ""}, 32 {"ioutil_test*", "ioutil_test", ""}, 33 {"ioutil_test*xyz", "ioutil_test", "xyz"}, 34 } 35 for _, test := range tests { 36 f, err := TempFile("", test.pattern) 37 if err != nil { 38 t.Errorf("TempFile(..., %q) error: %v", test.pattern, err) 39 continue 40 } 41 defer os.Remove(f.Name()) 42 base := filepath.Base(f.Name()) 43 f.Close() 44 if !(strings.HasPrefix(base, test.prefix) && strings.HasSuffix(base, test.suffix)) { 45 t.Errorf("TempFile pattern %q created bad name %q; want prefix %q & suffix %q", 46 test.pattern, base, test.prefix, test.suffix) 47 } 48 } 49 } 50 51 func TestTempDir(t *testing.T) { 52 name, err := TempDir("/_not_exists_", "foo") 53 if name != "" || err == nil { 54 t.Errorf("TempDir(`/_not_exists_`, `foo`) = %v, %v", name, err) 55 } 56 57 dir := os.TempDir() 58 name, err = TempDir(dir, "ioutil_test") 59 if name == "" || err != nil { 60 t.Errorf("TempDir(dir, `ioutil_test`) = %v, %v", name, err) 61 } 62 if name != "" { 63 os.Remove(name) 64 re := regexp.MustCompile("^" + regexp.QuoteMeta(filepath.Join(dir, "ioutil_test")) + "[0-9]+$") 65 if !re.MatchString(name) { 66 t.Errorf("TempDir(`"+dir+"`, `ioutil_test`) created bad name %s", name) 67 } 68 } 69 } 70 71 // test that we return a nice error message if the dir argument to TempDir doesn't 72 // exist (or that it's empty and os.TempDir doesn't exist) 73 func TestTempDir_BadDir(t *testing.T) { 74 dir, err := TempDir("", "TestTempDir_BadDir") 75 if err != nil { 76 t.Fatal(err) 77 } 78 defer os.RemoveAll(dir) 79 80 badDir := filepath.Join(dir, "not-exist") 81 _, err = TempDir(badDir, "foo") 82 if pe, ok := err.(*os.PathError); !ok || !os.IsNotExist(err) || pe.Path != badDir { 83 t.Errorf("TempDir error = %#v; want PathError for path %q satisifying os.IsNotExist", err, badDir) 84 } 85 }