github.com/cloud-foundations/dominator@v0.0.0-20221004181915-6e4fee580046/lib/fsutil/watchFile_test.go (about) 1 package fsutil 2 3 import ( 4 "errors" 5 "io" 6 "io/ioutil" 7 "os" 8 "path" 9 "testing" 10 "time" 11 12 "github.com/Cloud-Foundations/Dominator/lib/log/testlogger" 13 ) 14 15 var errorTimeout = errors.New("timeout") 16 17 func TestWatchFileDir(t *testing.T) { 18 dirname, err := ioutil.TempDir("", "WatchFileTests") 19 if err != nil { 20 t.Fatal(err) 21 } 22 defer os.RemoveAll(dirname) 23 testWatchFile(t, dirname) 24 } 25 26 func TestWatchFileCwd(t *testing.T) { 27 cwd, err := os.Getwd() 28 if err != nil { 29 t.Fatal(err) 30 } 31 defer os.Chdir(cwd) 32 dirname, err := ioutil.TempDir("", "WatchFileTests") 33 if err != nil { 34 t.Fatal(err) 35 } 36 defer os.RemoveAll(dirname) 37 if err := os.Chdir(dirname); err != nil { 38 t.Fatal(err) 39 } 40 testWatchFile(t, "") 41 } 42 43 func testWatchFile(t *testing.T, dirname string) { 44 logger := testlogger.New(t) 45 pathNotExist := path.Join(dirname, "never-exists") 46 ch := WatchFile(pathNotExist, logger) 47 rc, err := watchTimeout(ch, time.Millisecond*50) 48 if err != errorTimeout { 49 rc.Close() 50 t.Fatal("Expected timeout error for non-existent file") 51 } 52 pathExists := path.Join(dirname, "exists") 53 file, err := os.Create(pathExists) 54 if err != nil { 55 t.Fatal(err) 56 } 57 file.Close() 58 ch = WatchFile(pathExists, logger) 59 rc, err = watchTimeout(ch, time.Millisecond*50) 60 if err != nil { 61 t.Fatal(err) 62 } else { 63 rc.Close() 64 } 65 pathExistsLater := path.Join(dirname, "exists-later") 66 go func() { 67 time.Sleep(time.Millisecond * 50) 68 file, err := os.Create(pathExistsLater) 69 if err != nil { 70 panic(err) 71 } 72 file.Close() 73 }() 74 ch = WatchFile(pathExistsLater, logger) 75 _, err = watchTimeout(ch, time.Millisecond*10) 76 if err != errorTimeout { 77 t.Fatal("Expected timeout error for non-existent file") 78 } 79 rc, err = watchTimeout(ch, time.Millisecond*90) 80 if err != nil { 81 t.Fatal(err) 82 } else { 83 rc.Close() 84 } 85 pathWillBeRenamed := path.Join(dirname, "will-be-renamed") 86 file, err = os.Create(pathWillBeRenamed) 87 if err != nil { 88 t.Fatal(err) 89 } 90 file.Close() 91 rc, err = watchTimeout(ch, time.Millisecond*10) 92 if err != errorTimeout { 93 rc.Close() 94 t.Fatal("Expected timeout error for unchanged file") 95 } 96 if err := os.Rename(pathWillBeRenamed, pathExistsLater); err != nil { 97 t.Fatal(err) 98 } 99 rc, err = watchTimeout(ch, time.Millisecond*50) 100 if err != nil { 101 t.Fatal(err) 102 } else { 103 rc.Close() 104 } 105 } 106 107 func watchTimeout(channel <-chan io.ReadCloser, timeout time.Duration) ( 108 io.ReadCloser, error) { 109 select { 110 case readCloser := <-channel: 111 return readCloser, nil 112 case <-time.After(timeout): 113 return nil, errorTimeout 114 } 115 }