From 19f1484ac9a25a4b0b08c50f5b091d3611431212 Mon Sep 17 00:00:00 2001 From: mattn Date: Wed, 12 Jul 2023 21:47:58 +0900 Subject: [PATCH] Add test for remWatch (#418) Add test for remWatch, which #288 fixed. Co-authored-by: jie Co-authored-by: Nahum Shalman Co-authored-by: Martin Tournoij --- backend_windows_test.go | 17 +++++++++++++++ fsnotify_test.go | 48 ++++++++++++++++++++++++++++++++++++++++- helpers_test.go | 12 +++++++++++ 3 files changed, 76 insertions(+), 1 deletion(-) diff --git a/backend_windows_test.go b/backend_windows_test.go index 7dc46bb..ee59b27 100644 --- a/backend_windows_test.go +++ b/backend_windows_test.go @@ -49,3 +49,20 @@ func TestRemoveState(t *testing.T) { } check(0) } + +func TestWindowsRemWatch(t *testing.T) { + tmp := t.TempDir() + + touch(t, tmp, "file") + + w := newWatcher(t) + defer w.Close() + + addWatch(t, w, tmp) + if err := w.Remove(tmp); err != nil { + t.Fatalf("Could not remove the watch: %v\n", err) + } + if err := w.remWatch(tmp); err == nil { + t.Fatal("Should be fail with closed handle\n") + } +} diff --git a/fsnotify_test.go b/fsnotify_test.go index b86d54d..61ded52 100644 --- a/fsnotify_test.go +++ b/fsnotify_test.go @@ -1302,6 +1302,53 @@ func TestRemove(t *testing.T) { } }) + // Make sure file handles are correctly released. + // + // regression test for #42 see https://gist.github.com/timshannon/603f92824c5294269797 + t.Run("", func(t *testing.T) { + w := newWatcher(t) + defer w.Close() + + // consume the events + var werr error + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case werr = <-w.Errors: + return + case <-w.Events: + } + } + }() + + tmp := t.TempDir() + dir := join(tmp, "child") + addWatch(t, w, tmp) + mkdir(t, dir) + addWatch(t, w, dir) // start watching child + rmWatch(t, w, dir) // stop watching child + rmAll(t, dir) // delete child dir + + // Child dir should no longer exist + _, err := os.Stat(dir) + if err == nil { + t.Fatalf("dir %q should no longer exist!", dir) + } + if _, ok := err.(*os.PathError); err != nil && !ok { + t.Errorf("Expected a PathError, got %v", err) + } + + w.Close() + wg.Wait() + + if werr != nil { + t.Fatal(werr) + } + }) + t.Run("remove with ... when non-recursive", func(t *testing.T) { recurseOnly(t) t.Parallel() @@ -1317,7 +1364,6 @@ func TestRemove(t *testing.T) { t.Fatal(err) } }) - } func TestEventString(t *testing.T) { diff --git a/helpers_test.go b/helpers_test.go index 6ebf2ea..2051a94 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -70,6 +70,18 @@ func addWatch(t *testing.T, w *Watcher, path ...string) { } } +// rmWatch removes a watch. +func rmWatch(t *testing.T, watcher *Watcher, path ...string) { + t.Helper() + if len(path) < 1 { + t.Fatalf("rmWatch: path must have at least one element: %s", path) + } + err := watcher.Remove(join(path...)) + if err != nil { + t.Fatalf("rmWatch(%q): %s", join(path...), err) + } +} + const noWait = "" func shouldWait(path ...string) bool { -- 2.50.1