From 61387e5038c10d3b015f31947e1b327bad1a0a6c Mon Sep 17 00:00:00 2001 From: Will Miller Date: Thu, 12 Sep 2024 11:20:10 +0100 Subject: [PATCH] file/dirwatcher_test: wait for Done() in all relevant tests --- dirwatcher_test.go | 21 ++++++++++++++++----- filewatcher_test.go | 16 +++++++++------- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/dirwatcher_test.go b/dirwatcher_test.go index 517515b..af6b075 100644 --- a/dirwatcher_test.go +++ b/dirwatcher_test.go @@ -22,14 +22,20 @@ func TestDirWatcher(t *testing.T) { t.Run("ExistingFile", func(t *testing.T) { ctx, cancel := context.WithCancel(ctx) - defer cancel() + dw, err := NewDirWatcher(ctx, IN_CREATE, dir) + if err != nil { + t.Error(err) + } + defer func() { + cancel() + <-dw.Done() + }() f, err := os.OpenFile(filepath.Join(dir, "f1"), os.O_CREATE, os.ModePerm) f.Close() defer os.Remove(filepath.Join(dir, "f1")) - dw, err := NewDirWatcher(ctx, IN_CREATE, dir) if err != nil { t.Error(err) } @@ -45,12 +51,14 @@ func TestDirWatcher(t *testing.T) { t.Run("FileInSubdir", func(t *testing.T) { ctx, cancel := context.WithCancel(ctx) - defer cancel() - dw, err := NewDirWatcher(ctx, IN_CREATE, dir) if err != nil { t.Error(err) } + defer func() { + cancel() + <-dw.Done() + }() err = os.Mkdir(filepath.Join(dir, "subfolder"), os.ModePerm) if err != nil { @@ -82,12 +90,15 @@ func TestDirWatcher(t *testing.T) { t.Run("ClosedDirwatcherBecomesDone", func(t *testing.T) { ctx, cancel := context.WithCancel(ctx) - defer cancel() dw, err := NewDirWatcher(ctx, IN_CREATE, dir) if err != nil { t.Error(err) } + defer func() { + cancel() + <-dw.Done() + }() go func() { for e := range dw.C { diff --git a/filewatcher_test.go b/filewatcher_test.go index 9849440..4532e64 100644 --- a/filewatcher_test.go +++ b/filewatcher_test.go @@ -21,20 +21,20 @@ func TestFileWatcher(t *testing.T) { defer os.Remove(dir) t.Run("Simple", func(t *testing.T) { - - ctx, cancel := context.WithCancel(ctx) - defer cancel() - f1 := filepath.Join(dir, "/dir1/foo") f2 := filepath.Join(dir, "/dir2/bar") - os.MkdirAll(filepath.Dir(f1), os.ModePerm) os.MkdirAll(filepath.Dir(f2), os.ModePerm) + ctx, cancel := context.WithCancel(ctx) fw, err := NewFileWatcher(ctx, IN_ALL_EVENTS, f1, f2) if err != nil { t.Error(err) } + defer func() { + cancel() + <-fw.Done() + }() { f, err := os.OpenFile(f1, os.O_RDWR|os.O_CREATE, 0) @@ -64,12 +64,14 @@ func TestFileWatcher(t *testing.T) { t.Run("ClosedFileWatcherHasClosedChannel", func(t *testing.T) { ctx, cancel := context.WithCancel(ctx) - defer cancel() - fw, err := NewFileWatcher(ctx, IN_ALL_EVENTS, filepath.Join(dir, "foo")) if err != nil { t.Error(err) } + defer func() { + cancel() + <-fw.Done() + }() go func() { for e := range fw.C {