github.com/gofunct/common@v0.0.0-20190131174352-fd058c7fbf22/pkg/temp/dir_test.go (about) 1 package temp 2 3 import ( 4 "io/ioutil" 5 "os" 6 "path/filepath" 7 "strings" 8 "testing" 9 ) 10 11 func TestTempDir(t *testing.T) { 12 dir, err := CreateTempDir("prefix") 13 if err != nil { 14 t.Fatal(err) 15 } 16 17 // Delete the directory no matter what. 18 defer dir.Delete() 19 20 // Make sure we have created the dir, with the proper name 21 _, err = os.Stat(dir.Name) 22 if err != nil { 23 t.Fatal(err) 24 } 25 if !strings.HasPrefix(filepath.Base(dir.Name), "prefix") { 26 t.Fatalf(`Directory doesn't start with "prefix": %q`, 27 dir.Name) 28 } 29 30 // Verify that the directory is empty 31 entries, err := ioutil.ReadDir(dir.Name) 32 if err != nil { 33 t.Fatal(err) 34 } 35 if len(entries) != 0 { 36 t.Fatalf("Directory should be empty, has %d elements", 37 len(entries)) 38 } 39 40 // Create a couple of files 41 _, err = dir.NewFile("ONE") 42 if err != nil { 43 t.Fatal(err) 44 } 45 _, err = dir.NewFile("TWO") 46 if err != nil { 47 t.Fatal(err) 48 } 49 // We can't create the same file twice 50 _, err = dir.NewFile("TWO") 51 if err == nil { 52 t.Fatal("NewFile should fail to create the same file twice") 53 } 54 55 // We have created only two files 56 entries, err = ioutil.ReadDir(dir.Name) 57 if err != nil { 58 t.Fatal(err) 59 } 60 if len(entries) != 2 { 61 t.Fatalf("ReadDir should have two elements, has %d elements", 62 len(entries)) 63 } 64 65 // Verify that deletion works 66 err = dir.Delete() 67 if err != nil { 68 t.Fatal(err) 69 } 70 _, err = os.Stat(dir.Name) 71 if err == nil { 72 t.Fatal("Directory should be gone, still present.") 73 } 74 }