Permalink
Browse files

Add basic tests for Dir

  • Loading branch information...
1 parent 442000d commit e97f618ad47038dd231ff61681c5dc115c2702a0 @mrnugget committed Mar 18, 2013
View
@@ -20,7 +20,7 @@ type Dir struct {
Events chan *fsnotify.FileEvent
}
-func (d *Dir) StartWatching() (err error) {
+func (d *Dir) Listen() (err error) {
err = d.scan()
if err != nil {
return
View
@@ -0,0 +1,77 @@
+package watchgopher
+
+import (
+ // "github.com/howeyc/fsnotify"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "runtime"
+ "testing"
+ "time"
+)
+
+var (
+ _, filename, _, _ = runtime.Caller(0)
+ fixtures = filepath.Dir(filename) + "/fixtures"
+)
+
+func TestFiles(t *testing.T) {
+ dir := NewDir(fixtures)
+
+ err := dir.Listen()
+ checkErr(t, err)
+
+ _, ok := dir.Files[fixtures+"/foobar.txt"]
+ if !ok {
+ t.Errorf("dir.Files does not include right files")
+ }
+
+ _, ok = dir.Files[fixtures+"/hello_world.txt"]
+ if !ok {
+ t.Errorf("dir.Files does not include right files")
+ }
+}
+
+func TestEvents(t *testing.T) {
+ testfilepath := fixtures + "/testfile.txt"
+ dir := NewDir(fixtures)
+
+ err := dir.Listen()
+ checkErr(t, err)
+
+ err = ioutil.WriteFile(testfilepath, []byte("Hello World!"), 0644)
+ checkErr(t, err)
+
+ createev := <-dir.Events
+ if createev.Name != testfilepath && !createev.IsCreate() {
+ t.Fatal("Did not receive the right event")
+ }
+
+ time.Sleep(50 * time.Millisecond)
+
+ _, ok := dir.Files[testfilepath]
+ if !ok {
+ t.Errorf("Did not add the created file to dir.Files")
+ }
+
+ err = os.Remove(testfilepath)
+ checkErr(t, err)
+
+ time.Sleep(50 * time.Millisecond)
+
+ deleteev := <-dir.Events
+ if deleteev.Name != testfilepath && !deleteev.IsDelete() {
+ t.Fatal("Did not receive the right event")
+ }
+
+ file, ok := dir.Files[testfilepath]
+ if file != nil && ok {
+ t.Errorf("Did not remove the deleted file from dir.Files")
+ }
+}
+
+func checkErr(t *testing.T, err error) {
+ if err != nil {
+ t.Fatal(err)
+ }
+}
@@ -0,0 +1 @@
+Foobar
@@ -0,0 +1 @@
+Hello World
View
@@ -29,7 +29,7 @@ type Monitor struct {
func (m *Monitor) start() {
go m.workOff(m.queue)
- err := m.dir.StartWatching()
+ err := m.dir.Listen()
if err != nil {
panic(err)
}

0 comments on commit e97f618

Please sign in to comment.