-
Notifications
You must be signed in to change notification settings - Fork 10
/
singleflight_test.go
106 lines (95 loc) · 2.25 KB
/
singleflight_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
package valkey
import (
"context"
"errors"
"runtime"
"sync/atomic"
"testing"
"time"
)
func TestSingleFlight(t *testing.T) {
defer ShouldNotLeaked(SetupLeakDetection())
var calls, done, err int64
sg := call{}
for i := 0; i < 1000; i++ {
go func() {
if ret := sg.Do(context.Background(), func() error {
atomic.AddInt64(&calls, 1)
// wait for all goroutine invoked then return
for sg.suppressing() != 1000 {
runtime.Gosched()
}
return errors.New("I should be the only ret")
}); ret != nil {
atomic.AddInt64(&err, 1)
}
atomic.AddInt64(&done, 1)
}()
}
for atomic.LoadInt64(&done) != 1000 {
runtime.Gosched()
}
if atomic.LoadInt64(&calls) == 0 {
t.Fatalf("singleflight not call at all")
}
if v := atomic.LoadInt64(&calls); v != 1 {
t.Fatalf("singleflight should suppress all concurrent calls, got: %v", v)
}
if atomic.LoadInt64(&err) != 1 {
t.Fatalf("singleflight should that one call get the return value")
}
}
func TestSingleFlightWithContext(t *testing.T) {
defer ShouldNotLeaked(SetupLeakDetection())
ch := make(chan struct{})
sg := call{}
go func() {
sg.Do(context.Background(), func() error {
<-ch
return nil
})
}()
for sg.suppressing() != 1 {
time.Sleep(time.Millisecond)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := sg.Do(ctx, func() error { return nil }); err != context.Canceled {
t.Fatalf("unexpected err %v", err)
}
go func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := sg.Do(ctx, func() error { return nil }); err != nil {
t.Errorf("unexpected err %v", err)
}
}()
for sg.suppressing() != 3 {
time.Sleep(time.Millisecond)
}
close(ch)
if err := sg.Do(context.Background(), func() error { return nil }); err != nil {
t.Fatalf("unexpected err %v", err)
}
}
func TestSingleFlightLazyDo(t *testing.T) {
defer ShouldNotLeaked(SetupLeakDetection())
ch := make(chan struct{})
sg := call{}
sg.LazyDo(time.Second, func() error {
<-ch
return nil
})
cn := 0
sg.LazyDo(time.Second, func() error {
cn++ // this should not occur
return nil
})
if cn != 0 {
t.Fatalf("unexpected cn %v", cn)
}
if sc := sg.suppressing(); sc != 1 {
t.Fatalf("unexpected suppressing %v", sc)
}
close(ch)
}