forked from zknill/service
-
Notifications
You must be signed in to change notification settings - Fork 1
/
group_test.go
139 lines (107 loc) · 2.08 KB
/
group_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
package service_test
import (
"context"
"sync"
"testing"
"time"
"github.com/Attest/service"
)
func TestGroup(t *testing.T) {
t.Run("success", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
g := service.NewCtx(ctx)
g.Register(block)
errs := make(chan error)
go func() {
errs <- g.Start()
}()
cancel()
if err := <-errs; err != nil {
t.Errorf("expected no error: got %+v", err)
}
})
t.Run("setup before register", func(t *testing.T) {
g := service.NewCtx(context.Background())
setupCalled := make(chan struct{})
g.Setup(func(ctx context.Context) error {
close(setupCalled)
return nil
})
g.Register(func(ctx context.Context) error {
select {
case <-setupCalled:
default:
t.Error("expected setup called before register")
}
return nil
})
if err := g.Start(); err != nil {
t.Error(err)
}
})
t.Run("double call start", func(t *testing.T) {
g := service.NewCtx(context.Background())
g.Register(block)
ch1 := make(chan struct{})
ch2 := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer close(ch1)
wg.Done()
_ = g.Start()
}()
go func() {
defer close(ch2)
wg.Wait()
_ = g.Start()
}()
select {
case <-ch1:
t.Error("expected 1 to be blocked")
case <-ch2:
}
})
t.Run("close", func(t *testing.T) {
g := service.NewCtx(context.Background())
g.Register(block)
done := make(chan struct{})
go func() {
defer close(done)
_ = g.Start()
}()
select {
case <-done:
t.Error("expected not done")
default:
}
if err := g.Close(); err != nil {
t.Error(err)
}
closed := func() bool {
select {
case <-done:
return true
default:
return false
}
}
eventually(t, 3, closed)
})
}
func block(ctx context.Context) error {
<-ctx.Done()
return nil
}
func eventually(t *testing.T, attempts int, f func() bool) {
t.Helper()
for i := 0; i < 3; i++ {
ok := f()
if ok == true {
return
}
d := 500 * time.Millisecond
<-time.After(d * time.Duration(i+1))
}
t.Fatal("expected success")
}