Browse Source

Added IsDir and more tests

Stephen McQuay 4 years ago
parent
commit
ec32af71be
2 changed files with 61 additions and 4 deletions
  1. 12
    3
      fs.go
  2. 49
    1
      fs_test.go

+ 12
- 3
fs.go View File

@@ -4,10 +4,19 @@ import "os"
4 4
 
5 5
 // Exists returns if a file exists
6 6
 func Exists(path string) bool {
7
-	if _, err := os.Stat(path); err != nil {
8
-		return false
9
-	} else if os.IsNotExist(err) {
7
+	if _, err := os.Stat(path); os.IsNotExist(err) {
10 8
 		return false
11 9
 	}
12 10
 	return true
13 11
 }
12
+
13
+func IsDir(path string) bool {
14
+	info, err := os.Stat(path)
15
+	if err != nil {
16
+		return false
17
+	}
18
+	if info.IsDir() {
19
+		return true
20
+	}
21
+	return false
22
+}

+ 49
- 1
fs_test.go View File

@@ -9,8 +9,11 @@ import (
9 9
 
10 10
 func TestExists(t *testing.T) {
11 11
 	tmp, err := ioutil.TempDir("", "fs-test-")
12
+	defer func() {
13
+		os.RemoveAll(tmp)
14
+	}()
12 15
 	if err != nil {
13
-		panic(err)
16
+		t.Fatalf("couldn't create temp dir: %v", err)
14 17
 	}
15 18
 
16 19
 	filename := filepath.Join(tmp, "foo")
@@ -28,4 +31,49 @@ func TestExists(t *testing.T) {
28 31
 	if !Exists(filename) {
29 32
 		t.Errorf("failure to find existant file: %s", filename)
30 33
 	}
34
+
35
+	dirname := filepath.Join(tmp, "somedir")
36
+	if err := os.Mkdir(dirname, 0777); err != nil {
37
+		t.Errorf("problem creating directory: %v", err)
38
+	}
39
+
40
+	if !Exists(dirname) {
41
+		t.Errorf("failure to find existant directory: %s", dirname)
42
+	}
43
+}
44
+
45
+func TestIsDir(t *testing.T) {
46
+	tmp, err := ioutil.TempDir("", "fs-test-")
47
+	defer func() {
48
+		os.RemoveAll(tmp)
49
+	}()
50
+	if err != nil {
51
+		t.Fatalf("couldn't create temp dir: %v", err)
52
+	}
53
+	dirname := filepath.Join(tmp, "somedir")
54
+	if err := os.Mkdir(dirname, 0777); err != nil {
55
+		t.Errorf("problem creating directory: %v", err)
56
+	}
57
+
58
+	if isdir := IsDir(filepath.Join(tmp, "notexist")); isdir {
59
+		t.Errorf("failed to correctly interpret non-existant file: got %t, want %t", isdir, false)
60
+	}
61
+
62
+	if !Exists(dirname) {
63
+		t.Errorf("failure to find existant directory: %s", dirname)
64
+	}
65
+
66
+	if !IsDir(dirname) {
67
+		t.Errorf("failure to detect directory: %s", dirname)
68
+	}
69
+
70
+	filename := filepath.Join(tmp, "foo")
71
+	f, err := os.Create(filename)
72
+	if err != nil {
73
+		t.Errorf("problem opening fresh file (%q): %v", filename, err)
74
+	}
75
+	f.Close()
76
+	if isdir := IsDir(filename); isdir {
77
+		t.Errorf("failure to correctly interpret file as directory; got %t, want %t", isdir, false)
78
+	}
31 79
 }

Loading…
Cancel
Save