Added IsDir and more tests

This commit is contained in:
Stephen McQuay 2015-08-09 20:18:41 -07:00
parent d65b52fedb
commit ec32af71be
2 changed files with 61 additions and 4 deletions

15
fs.go
View File

@ -4,10 +4,19 @@ import "os"
// Exists returns if a file exists // Exists returns if a file exists
func Exists(path string) bool { func Exists(path string) bool {
if _, err := os.Stat(path); err != nil { if _, err := os.Stat(path); os.IsNotExist(err) {
return false
} else if os.IsNotExist(err) {
return false return false
} }
return true return true
} }
func IsDir(path string) bool {
info, err := os.Stat(path)
if err != nil {
return false
}
if info.IsDir() {
return true
}
return false
}

View File

@ -9,8 +9,11 @@ import (
func TestExists(t *testing.T) { func TestExists(t *testing.T) {
tmp, err := ioutil.TempDir("", "fs-test-") tmp, err := ioutil.TempDir("", "fs-test-")
defer func() {
os.RemoveAll(tmp)
}()
if err != nil { if err != nil {
panic(err) t.Fatalf("couldn't create temp dir: %v", err)
} }
filename := filepath.Join(tmp, "foo") filename := filepath.Join(tmp, "foo")
@ -28,4 +31,49 @@ func TestExists(t *testing.T) {
if !Exists(filename) { if !Exists(filename) {
t.Errorf("failure to find existant file: %s", filename) t.Errorf("failure to find existant file: %s", filename)
} }
dirname := filepath.Join(tmp, "somedir")
if err := os.Mkdir(dirname, 0777); err != nil {
t.Errorf("problem creating directory: %v", err)
}
if !Exists(dirname) {
t.Errorf("failure to find existant directory: %s", dirname)
}
}
func TestIsDir(t *testing.T) {
tmp, err := ioutil.TempDir("", "fs-test-")
defer func() {
os.RemoveAll(tmp)
}()
if err != nil {
t.Fatalf("couldn't create temp dir: %v", err)
}
dirname := filepath.Join(tmp, "somedir")
if err := os.Mkdir(dirname, 0777); err != nil {
t.Errorf("problem creating directory: %v", err)
}
if isdir := IsDir(filepath.Join(tmp, "notexist")); isdir {
t.Errorf("failed to correctly interpret non-existant file: got %t, want %t", isdir, false)
}
if !Exists(dirname) {
t.Errorf("failure to find existant directory: %s", dirname)
}
if !IsDir(dirname) {
t.Errorf("failure to detect directory: %s", dirname)
}
filename := filepath.Join(tmp, "foo")
f, err := os.Create(filename)
if err != nil {
t.Errorf("problem opening fresh file (%q): %v", filename, err)
}
f.Close()
if isdir := IsDir(filename); isdir {
t.Errorf("failure to correctly interpret file as directory; got %t, want %t", isdir, false)
}
} }