This repository was archived by the owner on Nov 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwatcher_test.go
123 lines (104 loc) · 2.24 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
package tail
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/fsnotify/fsnotify"
"github.com/go-faster/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap/zaptest"
"golang.org/x/sync/errgroup"
)
type wrapTracker struct {
file func(name string)
create func(name string)
t Tracker
}
func (w wrapTracker) watchFile(name string) error {
if w.file != nil {
defer w.file(name)
}
return w.t.watchFile(name)
}
func (w wrapTracker) watchCreate(name string) error {
if w.create != nil {
defer w.create(name)
}
return w.t.watchCreate(name)
}
func (w wrapTracker) removeWatchName(name string) error {
return w.t.removeWatchName(name)
}
func (w wrapTracker) removeWatchCreate(name string) error {
return w.t.removeWatchCreate(name)
}
func (w wrapTracker) listenEvents(name string) <-chan fsnotify.Event {
return w.t.listenEvents(name)
}
func TestCreateAfterWatch(t *testing.T) {
lg := zaptest.NewLogger(t)
g, ctx := errgroup.WithContext(context.Background())
name := filepath.Join(t.TempDir(), "foo.txt")
const lines = 10
started := make(chan struct{})
g.Go(func() error {
select {
case <-started:
case <-ctx.Done():
return ctx.Err()
}
f, err := os.Create(name)
if err != nil {
return err
}
for i := 0; i < lines; i++ {
if _, err := fmt.Fprintln(f, line); err != nil {
return err
}
}
return f.Close()
})
tailer := File(name, Config{
NotifyTimeout: notifyTimeout,
Follow: true,
Logger: lg,
Tracker: wrapTracker{
t: NewTracker(lg),
create: func(name string) {
close(started)
},
},
})
read := make(chan struct{})
g.Go(func() error {
var gotLines int
// Ensure that each tailer got all lines.
h := func(ctx context.Context, l *Line) error {
assert.Equal(t, line, string(l.Data))
gotLines++
if gotLines == lines {
close(read)
}
return nil
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
if err := tailer.Tail(ctx, h); !errors.Is(err, errStop) {
return err
}
return nil
})
// Read lines.
g.Go(func() error {
select {
case <-ctx.Done():
return ctx.Err()
case <-read: // ok
}
return os.Remove(name)
})
require.NoError(t, g.Wait())
}