-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
progress_test.go
113 lines (88 loc) · 1.91 KB
/
progress_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
package x_test
import (
"context"
"io"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gitlab.com/tozd/go/x"
)
const (
tickerInterval = 50 * time.Millisecond
)
func TestTicker(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
r, w := io.Pipe()
defer r.Close()
defer w.Close()
countingReader := x.NewCountingReader(r)
go func() {
_, _ = io.ReadAll(countingReader)
}()
ticker := x.NewTicker(ctx, countingReader, 10, tickerInterval)
require.NotNil(t, ticker)
defer ticker.Stop()
l := sync.Mutex{}
progress := []x.Progress{}
go func() {
for p := range ticker.C {
func() {
l.Lock()
defer l.Unlock()
progress = append(progress, p)
}()
}
}()
time.Sleep(2 * tickerInterval)
var p x.Progress
func() {
l.Lock()
defer l.Unlock()
require.NotEmpty(t, progress)
p = progress[len(progress)-1]
}()
assert.Equal(t, int64(10), p.Size)
assert.Equal(t, int64(0), p.Count)
assert.Equal(t, 0.0, p.Percent()) //nolint:testifylint
n, err := w.Write([]byte("abcd"))
assert.Equal(t, 4, n)
require.NoError(t, err)
time.Sleep(2 * tickerInterval)
func() {
l.Lock()
defer l.Unlock()
require.NotEmpty(t, progress)
p = progress[len(progress)-1]
}()
assert.Equal(t, int64(10), p.Size)
assert.Equal(t, int64(4), p.Count)
assert.Equal(t, 40.0, p.Percent()) //nolint:testifylint
cancel()
// We give time for cancel to propagate.
time.Sleep(2 * tickerInterval)
var progressLen int
func() {
l.Lock()
defer l.Unlock()
progressLen = len(progress)
}()
// After this there should be no new progress added.
time.Sleep(2 * tickerInterval)
func() {
l.Lock()
defer l.Unlock()
assert.Len(t, progress, progressLen)
}()
// Channel should be closed.
select {
case _, ok := <-ticker.C:
if ok {
require.Fail(t, "progress where there should be none")
}
default:
}
}