-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebounce_test.go
72 lines (61 loc) · 1.24 KB
/
debounce_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
package patterns
import (
"context"
"fmt"
"sync"
"testing"
"time"
)
func getCounter() Circuit {
var mu sync.Mutex
var total int
return func(ctx context.Context) (string, error) {
mu.Lock()
defer mu.Unlock()
total++
return fmt.Sprint(total), nil
}
}
func TestDebounce(t *testing.T) {
c := Debounce(getCounter(), time.Second)
var r string
for i := 0; i < 100; i++ {
r, _ = c(context.Background())
}
if r != "1" {
t.Errorf("r == %s, want %s", r, "1")
}
time.Sleep(time.Second)
for i := 0; i < 5; i++ {
r, _ = c(context.Background())
}
if r != "2" {
t.Errorf("r == %s, want %s", r, "2")
}
}
func TestDebounceDataRace(t *testing.T) {
ctx := context.Background()
circuit := failAfter(1)
debounce := Debounce(circuit, time.Second)
var wg sync.WaitGroup
for count := 1; count <= 10; count++ {
wg.Add(1)
go func(count int) {
defer wg.Done()
time.Sleep(50 * time.Millisecond)
_, err := debounce(ctx)
t.Logf("attempt %d: err=%v", count, err)
}(count)
}
time.Sleep(time.Second * 2)
for count := 1; count <= 10; count++ {
wg.Add(1)
go func(count int) {
defer wg.Done()
time.Sleep(50 * time.Millisecond)
_, err := debounce(ctx)
t.Logf("attempt %d: err=%v", count, err)
}(count)
}
wg.Wait()
}