-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher_test.go
341 lines (319 loc) · 8.83 KB
/
watcher_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package main
import (
"context"
"errors"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/fsnotify/fsnotify"
)
func TestWatcherAddDirs(t *testing.T) {
testDir := filepath.Join(os.TempDir(), "test_watcher_add_dirs")
// teardown
defer func() {
if !t.Failed() {
// clean tmp dir on test success
_ = os.RemoveAll(testDir)
}
}()
logger := log.New(os.Stdout, "gtr-test:", log.Ltime)
var watcher *Watcher
var err error
cases := []struct {
desc string
setup, tearDown func() error
dirsWatching int
err error
}{
{
desc: "Create directories and add to watcher",
setup: func() error {
_ = os.Mkdir(filepath.Join(testDir, ".hidden"), 0700)
_ = os.MkdirAll(filepath.Join(testDir, "ad", "add", "addd"), 0700)
err = os.MkdirAll(filepath.Join(testDir, "bd", "bdd"), 0700)
if err != nil {
return err
}
watcher, err = NewWatcher(testDir, nil, 0, nil, nil, logger)
return err
},
tearDown: func() error {
return watcher.Stop()
},
dirsWatching: 6, err: nil,
},
{
desc: "Exclude add directory from watching",
setup: func() error {
watcher, err = NewWatcher(testDir, nil, 0, nil, []string{"add"}, logger)
return err
},
tearDown: func() error {
return watcher.Stop()
},
dirsWatching: 4, err: nil,
},
}
for i, tc := range cases {
// setup()
execTestHelper(t, i, tc.desc, tc.setup)
err = watcher.addDirs()
// teardown()
execTestHelper(t, i, tc.desc, tc.tearDown)
if isUnexpectedErr(t, i, tc.desc, tc.err, err) {
continue
}
if len(watcher.dirs) != tc.dirsWatching {
t.Errorf("case [%d] %s\nexpected %+v\ngot %+v",
i, tc.desc, tc.dirsWatching, len(watcher.dirs))
}
}
}
func TestWatcherSkipChange(t *testing.T) {
cases := []struct {
desc string
excludeFilePrefixes []string
event fsnotify.Event
lastModTime time.Time
lastModFile string
expect bool
}{
{
desc: "new file Create event",
event: fsnotify.Event{"file.go", fsnotify.Create},
expect: false,
},
{
desc: "file.go Rename event",
event: fsnotify.Event{"file.go", fsnotify.Rename},
expect: true,
},
{
desc: "file.go Remove event",
event: fsnotify.Event{"file.go", fsnotify.Remove},
expect: true,
},
{
desc: "file.go Write event",
event: fsnotify.Event{"file.go", fsnotify.Write},
expect: false,
},
{
desc: "file Write event, updated < delay",
event: fsnotify.Event{"file.go", fsnotify.Write},
lastModTime: time.Now().Add(-100 * time.Millisecond),
lastModFile: "file.go",
expect: true,
},
{
desc: "file.js file Write event",
event: fsnotify.Event{"file.js", fsnotify.Write},
expect: true,
},
{
desc: "prefixfile.go skipped by prefix Write event",
excludeFilePrefixes: []string{"prefix", "otherprefix"},
event: fsnotify.Event{"prefixfile.go", fsnotify.Write},
lastModTime: time.Time{},
lastModFile: "file.go",
expect: true,
},
}
for i, tc := range cases {
watcher := &Watcher{
delay: 1000 * time.Millisecond,
excludeFilePrefixes: tc.excludeFilePrefixes,
}
if watcher.skipChange(tc.event, tc.lastModFile, tc.lastModTime) != tc.expect {
t.Errorf("case [%d] %s\nexpected %+v\ngot %+v",
i, tc.desc, tc.expect, !tc.expect)
}
}
}
func TestWatcherRunTasks(t *testing.T) {
testDir := filepath.Join(os.TempDir(), "test_watcher_run_tasks")
os.RemoveAll(testDir)
// teardown
defer func() {
if !t.Failed() {
// clean tmp dir on test success
_ = os.RemoveAll(testDir)
}
}()
var watcher *Watcher
var err error
var taskOutput string
var taskErr error
logger := log.New(os.Stdout, "gtr-test:", log.Ltime)
taskCanceledErr := errors.New("task canceled")
cases := []struct {
desc string
setup, tearDown func() error
expectedTaskOutput string
expectedTaskErr error
}{
{
desc: "Run tasks/stop tasks",
setup: func() error {
// prepare dir tree
_ = os.Mkdir(filepath.Join(testDir, ".hidden"), 0700)
_ = os.MkdirAll(filepath.Join(testDir, "ad", "add", "addd"), 0700)
err = os.MkdirAll(filepath.Join(testDir, "bd", "bdd"), 0700)
if err != nil {
return err
}
task1 := NewTask("task1", func(log *log.Logger, ctx context.Context) (string, error) {
<-ctx.Done()
taskErr = taskCanceledErr
return taskErr.Error(), taskErr
}, logger)
watcher, _ = NewWatcher(testDir, []Task{task1}, 0, nil, nil, logger)
_ = watcher.addDirs()
// run tasks
go watcher.runTasks()
return ioutil.WriteFile(filepath.Join(testDir, "file.go"), nil, 0600)
},
tearDown: func() error {
taskErr = nil
taskOutput = ""
return nil
},
expectedTaskOutput: "", expectedTaskErr: taskCanceledErr,
},
{
desc: "Run multiple tasks in order file > task1 > task2",
setup: func() error {
task1 := NewTask("task1", func(log *log.Logger, ctx context.Context) (string, error) {
fname, ok := ctx.Value(changedFileNameKey).(string)
if !ok {
return "", taskCanceledErr
}
taskOutput = fname + ">task1"
return taskOutput, nil
}, logger)
task2 := NewTask("task2", func(log *log.Logger, ctx context.Context) (string, error) {
prevOut, ok := ctx.Value(prevTaskOutputKey).(string)
if !ok {
return "", taskCanceledErr
}
taskOutput = prevOut + ">task2"
return taskOutput, nil
}, logger)
watcher, _ = NewWatcher(testDir, []Task{task1, task2}, 0, nil, nil, logger)
_ = watcher.addDirs()
// run tasks
go watcher.runTasks()
return ioutil.WriteFile(filepath.Join(testDir, "file.go"), nil, 0600)
},
tearDown: func() error {
taskErr = nil
taskOutput = ""
return nil
},
expectedTaskOutput: filepath.Join(testDir, "file.go>task1>task2"),
expectedTaskErr: nil,
},
{
desc: "Do not trigger task on none go files",
setup: func() error {
gotask := NewTask("gotask", func(log *log.Logger, ctx context.Context) (string, error) {
return "should not run", errors.New("should not run")
}, logger)
watcher, _ = NewWatcher(testDir, []Task{gotask}, 0, nil, nil, logger)
_ = watcher.addDirs()
// run tasks
go watcher.runTasks()
return ioutil.WriteFile(filepath.Join(testDir, "file.js"), nil, 0600)
},
tearDown: func() error {
taskErr = nil
taskOutput = ""
return nil
},
expectedTaskOutput: "", expectedTaskErr: nil,
},
{
desc: "Add new directory to a watch list",
setup: func() error {
task := NewTask("task", func(log *log.Logger, ctx context.Context) (string, error) {
fname := ctx.Value(changedFileNameKey).(string)
_, file := filepath.Split(fname)
if file != "file_in_new_dir.go" {
return "unexpected file", taskCanceledErr
}
taskOutput = "OK"
return taskOutput, nil
}, logger)
watcher, _ = NewWatcher(testDir, []Task{task}, 0, nil, nil, logger)
_ = watcher.addDirs()
// run tasks
go watcher.runTasks()
// create new directory
newDir := filepath.Join(testDir, "newdir")
os.Mkdir(newDir, 0700)
// delay for a watcher to add newdir
time.Sleep(time.Millisecond)
return ioutil.WriteFile(
filepath.Join(newDir, "file_in_new_dir.go"), nil, 0600)
},
tearDown: func() error {
taskErr = nil
taskOutput = ""
return nil
},
expectedTaskOutput: "OK", expectedTaskErr: nil,
},
{
desc: "Remove deleted directory from a watch list",
setup: func() error {
task := NewTask("task_return_dirs", func(log *log.Logger, ctx context.Context) (string, error) {
taskOutput = strconv.Itoa(len(watcher.dirs))
return taskOutput, nil
}, logger)
watcher, _ = NewWatcher(testDir, []Task{task}, 0, nil, nil, logger)
_ = watcher.addDirs()
// run tasks
go watcher.runTasks()
// remove new directory
time.Sleep(time.Millisecond)
os.RemoveAll(filepath.Join(testDir, "newdir"))
return ioutil.WriteFile(
filepath.Join(testDir, "file_update.go"), nil, 0600)
},
tearDown: func() error {
taskErr = nil
taskOutput = ""
return nil
},
expectedTaskOutput: "6", expectedTaskErr: nil,
},
}
for i, tc := range cases {
if i > 0 {
// teardown
prev := i - 1
execTestHelper(t, prev, cases[prev].desc, cases[prev].tearDown)
}
// setup()
execTestHelper(t, i, tc.desc, tc.setup)
// wait watcher to process changes
time.Sleep(time.Millisecond)
err = watcher.Stop()
if isUnexpectedErr(t, i, tc.desc, nil, err) {
continue
}
// wait task watcher runTasks returns
time.Sleep(time.Millisecond)
if isUnexpectedErr(t, i, tc.desc, tc.expectedTaskErr, taskErr) {
continue
}
if tc.expectedTaskOutput != taskOutput {
t.Errorf("case [%d] %s\nexpected %+v\ngot %+v",
i, tc.desc, tc.expectedTaskOutput, taskOutput)
}
}
}