-
-
Notifications
You must be signed in to change notification settings - Fork 4k
/
basicfs_watch_test.go
539 lines (442 loc) · 12.6 KB
/
basicfs_watch_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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// Copyright (C) 2016 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
// +build !solaris,!darwin solaris,cgo darwin,cgo
package fs
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"testing"
"time"
"github.com/syncthing/notify"
)
func TestMain(m *testing.M) {
if err := os.RemoveAll(testDir); err != nil {
panic(err)
}
dir, err := filepath.Abs(".")
if err != nil {
panic("Cannot get absolute path to working dir")
}
dir, err = evalSymlinks(dir)
if err != nil {
panic("Cannot get real path to working dir")
}
testDirAbs = filepath.Join(dir, testDir)
if runtime.GOOS == "windows" {
testDirAbs = longFilenameSupport(testDirAbs)
}
testFs = NewFilesystem(FilesystemTypeBasic, testDirAbs)
backendBuffer = 10
exitCode := m.Run()
backendBuffer = 500
os.RemoveAll(testDir)
os.Exit(exitCode)
}
const (
testDir = "testdata"
failsOnOpenBSD = "Fails on OpenBSD. See https://github.com/rjeczalik/notify/issues/172"
)
var (
testDirAbs string
testFs Filesystem
)
func TestWatchIgnore(t *testing.T) {
if runtime.GOOS == "openbsd" {
t.Skip(failsOnOpenBSD)
}
name := "ignore"
file := "file"
ignored := "ignored"
testCase := func() {
createTestFile(name, file)
createTestFile(name, ignored)
}
expectedEvents := []Event{
{file, NonRemove},
}
allowedEvents := []Event{
{name, NonRemove},
}
testScenario(t, name, testCase, expectedEvents, allowedEvents, fakeMatcher{ignore: filepath.Join(name, ignored), skipIgnoredDirs: true})
}
func TestWatchInclude(t *testing.T) {
if runtime.GOOS == "openbsd" {
t.Skip(failsOnOpenBSD)
}
name := "include"
file := "file"
ignored := "ignored"
testFs.MkdirAll(filepath.Join(name, ignored), 0777)
included := filepath.Join(ignored, "included")
testCase := func() {
createTestFile(name, file)
createTestFile(name, included)
}
expectedEvents := []Event{
{file, NonRemove},
{included, NonRemove},
}
allowedEvents := []Event{
{name, NonRemove},
}
testScenario(t, name, testCase, expectedEvents, allowedEvents, fakeMatcher{ignore: filepath.Join(name, ignored), include: filepath.Join(name, included)})
}
func TestWatchRename(t *testing.T) {
if runtime.GOOS == "openbsd" {
t.Skip(failsOnOpenBSD)
}
name := "rename"
old := createTestFile(name, "oldfile")
new := "newfile"
testCase := func() {
renameTestFile(name, old, new)
}
destEvent := Event{new, Remove}
// Only on these platforms the removed file can be differentiated from
// the created file during renaming
if runtime.GOOS == "windows" || runtime.GOOS == "linux" || runtime.GOOS == "solaris" || runtime.GOOS == "freebsd" {
destEvent = Event{new, NonRemove}
}
expectedEvents := []Event{
{old, Remove},
destEvent,
}
allowedEvents := []Event{
{name, NonRemove},
}
// set the "allow others" flag because we might get the create of
// "oldfile" initially
testScenario(t, name, testCase, expectedEvents, allowedEvents, fakeMatcher{})
}
// TestWatchWinRoot checks that a watch at a drive letter does not panic due to
// out of root event on every event.
// https://github.com/syncthing/syncthing/issues/5695
func TestWatchWinRoot(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Windows specific test")
}
outChan := make(chan Event)
backendChan := make(chan notify.EventInfo, backendBuffer)
errChan := make(chan error)
ctx, cancel := context.WithCancel(context.Background())
// testFs is Filesystem, but we need BasicFilesystem here
root := `D:\`
fs := newBasicFilesystem(root)
watch, roots, err := fs.watchPaths(".")
if err != nil {
t.Fatal(err)
}
done := make(chan struct{})
defer func() {
cancel()
<-done
}()
go func() {
defer func() {
if r := recover(); r != nil {
t.Error(r)
}
cancel()
}()
fs.watchLoop(ctx, ".", roots, backendChan, outChan, errChan, fakeMatcher{})
close(done)
}()
// filepath.Dir as watch has a /... suffix
name := "foo"
backendChan <- fakeEventInfo(filepath.Join(filepath.Dir(watch), name))
select {
case <-time.After(10 * time.Second):
cancel()
t.Errorf("Timed out before receiving event")
case ev := <-outChan:
if ev.Name != name {
t.Errorf("Unexpected event %v, expected %v", ev.Name, name)
}
case err := <-errChan:
t.Error("Received fatal watch error:", err)
case <-ctx.Done():
}
}
// TestWatchOutside checks that no changes from outside the folder make it in
func TestWatchOutside(t *testing.T) {
expectErrorForPath(t, filepath.Join(filepath.Dir(testDirAbs), "outside"))
rootWithoutSlash := strings.TrimRight(filepath.ToSlash(testDirAbs), "/")
expectErrorForPath(t, rootWithoutSlash+"outside")
expectErrorForPath(t, rootWithoutSlash+"outside/thing")
}
func expectErrorForPath(t *testing.T, path string) {
outChan := make(chan Event)
backendChan := make(chan notify.EventInfo, backendBuffer)
errChan := make(chan error)
ctx, cancel := context.WithCancel(context.Background())
// testFs is Filesystem, but we need BasicFilesystem here
fs := newBasicFilesystem(testDirAbs)
done := make(chan struct{})
go func() {
fs.watchLoop(ctx, ".", []string{testDirAbs}, backendChan, outChan, errChan, fakeMatcher{})
close(done)
}()
defer func() {
cancel()
<-done
}()
backendChan <- fakeEventInfo(path)
select {
case <-time.After(10 * time.Second):
t.Errorf("Timed out before receiving error")
case e := <-outChan:
t.Errorf("Unexpected passed through event %v", e)
case <-errChan:
case <-ctx.Done():
}
}
func TestWatchSubpath(t *testing.T) {
outChan := make(chan Event)
backendChan := make(chan notify.EventInfo, backendBuffer)
errChan := make(chan error)
ctx, cancel := context.WithCancel(context.Background())
// testFs is Filesystem, but we need BasicFilesystem here
fs := newBasicFilesystem(testDirAbs)
abs, _ := fs.rooted("sub")
done := make(chan struct{})
go func() {
fs.watchLoop(ctx, "sub", []string{testDirAbs}, backendChan, outChan, errChan, fakeMatcher{})
close(done)
}()
defer func() {
cancel()
<-done
}()
backendChan <- fakeEventInfo(filepath.Join(abs, "file"))
timeout := time.NewTimer(2 * time.Second)
select {
case <-timeout.C:
t.Errorf("Timed out before receiving an event")
cancel()
case ev := <-outChan:
if ev.Name != filepath.Join("sub", "file") {
t.Errorf("While watching a subfolder, received an event with unexpected path %v", ev.Name)
}
case err := <-errChan:
t.Error("Received fatal watch error:", err)
}
cancel()
}
// TestWatchOverflow checks that an event at the root is sent when maxFiles is reached
func TestWatchOverflow(t *testing.T) {
if runtime.GOOS == "openbsd" {
t.Skip(failsOnOpenBSD)
}
name := "overflow"
expectedEvents := []Event{
{".", NonRemove},
}
allowedEvents := []Event{
{name, NonRemove},
}
testCase := func() {
for i := 0; i < 5*backendBuffer; i++ {
file := "file" + strconv.Itoa(i)
createTestFile(name, file)
allowedEvents = append(allowedEvents, Event{file, NonRemove})
}
}
testScenario(t, name, testCase, expectedEvents, allowedEvents, fakeMatcher{})
}
func TestWatchErrorLinuxInterpretation(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("testing of linux specific error codes")
}
var errTooManyFiles = &os.PathError{
Op: "error while traversing",
Path: "foo",
Err: syscall.Errno(24),
}
var errNoSpace = &os.PathError{
Op: "error while traversing",
Path: "bar",
Err: syscall.Errno(28),
}
if !reachedMaxUserWatches(errTooManyFiles) {
t.Error("Underlying error syscall.Errno(24) should be recognised to be about inotify limits.")
}
if !reachedMaxUserWatches(errNoSpace) {
t.Error("Underlying error syscall.Errno(28) should be recognised to be about inotify limits.")
}
err := errors.New("Another error")
if reachedMaxUserWatches(err) {
t.Errorf("This error does not concern inotify limits: %#v", err)
}
}
func TestWatchSymlinkedRoot(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Involves symlinks")
}
name := "symlinkedRoot"
if err := testFs.MkdirAll(name, 0755); err != nil {
panic(fmt.Sprintf("Failed to create directory %s: %s", name, err))
}
defer testFs.RemoveAll(name)
root := filepath.Join(name, "root")
if err := testFs.MkdirAll(root, 0777); err != nil {
panic(err)
}
link := filepath.Join(name, "link")
if err := testFs.CreateSymlink(filepath.Join(testFs.URI(), root), link); err != nil {
panic(err)
}
linkedFs := NewFilesystem(FilesystemTypeBasic, filepath.Join(testFs.URI(), link))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if _, _, err := linkedFs.Watch(".", fakeMatcher{}, ctx, false); err != nil {
panic(err)
}
if err := linkedFs.MkdirAll("foo", 0777); err != nil {
panic(err)
}
// Give the panic some time to happen
sleepMs(100)
}
func TestUnrootedChecked(t *testing.T) {
fs := newBasicFilesystem(testDirAbs)
if unrooted, err := fs.unrootedChecked("/random/other/path", []string{testDirAbs}); err == nil {
t.Error("unrootedChecked did not return an error on outside path, but returned", unrooted)
}
}
func TestWatchIssue4877(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Windows specific test")
}
name := "Issue4877"
file := "file"
testCase := func() {
createTestFile(name, file)
}
expectedEvents := []Event{
{file, NonRemove},
}
allowedEvents := []Event{
{name, NonRemove},
}
volName := filepath.VolumeName(testDirAbs)
if volName == "" {
t.Fatalf("Failed to get volume name for path %v", testDirAbs)
}
origTestFs := testFs
testFs = NewFilesystem(FilesystemTypeBasic, strings.ToLower(volName)+strings.ToUpper(testDirAbs[len(volName):]))
defer func() {
testFs = origTestFs
}()
testScenario(t, name, testCase, expectedEvents, allowedEvents, fakeMatcher{})
}
// path relative to folder root, also creates parent dirs if necessary
func createTestFile(name string, file string) string {
joined := filepath.Join(name, file)
if err := testFs.MkdirAll(filepath.Dir(joined), 0755); err != nil {
panic(fmt.Sprintf("Failed to create parent directory for %s: %s", joined, err))
}
handle, err := testFs.Create(joined)
if err != nil {
panic(fmt.Sprintf("Failed to create test file %s: %s", joined, err))
}
handle.Close()
return file
}
func renameTestFile(name string, old string, new string) {
old = filepath.Join(name, old)
new = filepath.Join(name, new)
if err := testFs.Rename(old, new); err != nil {
panic(fmt.Sprintf("Failed to rename %s to %s: %s", old, new, err))
}
}
func sleepMs(ms int) {
time.Sleep(time.Duration(ms) * time.Millisecond)
}
func testScenario(t *testing.T, name string, testCase func(), expectedEvents, allowedEvents []Event, fm fakeMatcher) {
if err := testFs.MkdirAll(name, 0755); err != nil {
panic(fmt.Sprintf("Failed to create directory %s: %s", name, err))
}
defer testFs.RemoveAll(name)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
eventChan, errChan, err := testFs.Watch(name, fm, ctx, false)
if err != nil {
panic(err)
}
go testWatchOutput(t, name, eventChan, expectedEvents, allowedEvents, ctx, cancel)
testCase()
select {
case <-time.After(10 * time.Second):
t.Error("Timed out before receiving all expected events")
case err := <-errChan:
t.Error("Received fatal watch error:", err)
case <-ctx.Done():
}
}
func testWatchOutput(t *testing.T, name string, in <-chan Event, expectedEvents, allowedEvents []Event, ctx context.Context, cancel context.CancelFunc) {
var expected = make(map[Event]struct{})
for _, ev := range expectedEvents {
ev.Name = filepath.Join(name, ev.Name)
expected[ev] = struct{}{}
}
var received Event
var last Event
for {
if len(expected) == 0 {
cancel()
return
}
select {
case <-ctx.Done():
return
case received = <-in:
}
// apparently the backend sometimes sends repeat events
if last == received {
continue
}
if _, ok := expected[received]; !ok {
if len(allowedEvents) > 0 {
sleepMs(100) // To facilitate overflow
continue
}
t.Errorf("Received unexpected event %v expected one of %v", received, expected)
cancel()
return
}
delete(expected, received)
last = received
}
}
// Matches are done via direct comparison against both ignore and include
type fakeMatcher struct {
ignore string
include string
skipIgnoredDirs bool
}
func (fm fakeMatcher) ShouldIgnore(name string) bool {
return name != fm.include && name == fm.ignore
}
func (fm fakeMatcher) SkipIgnoredDirs() bool {
return fm.skipIgnoredDirs
}
type fakeEventInfo string
func (e fakeEventInfo) Path() string {
return string(e)
}
func (e fakeEventInfo) Event() notify.Event {
return notify.Write
}
func (e fakeEventInfo) Sys() interface{} {
return nil
}