-
Notifications
You must be signed in to change notification settings - Fork 0
/
rungroup_test.go
81 lines (60 loc) · 1.45 KB
/
rungroup_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
package rungroup
import (
"context"
"fmt"
"testing"
"time"
)
type TestService struct {
name string
closeDuration time.Duration
chErrorTerm chan struct{}
}
func NewTestService(name string, closeDuration time.Duration) *TestService {
return &TestService{
name: name,
closeDuration: closeDuration,
chErrorTerm: make(chan struct{}),
}
}
func (svc *TestService) Run(ctx context.Context) error {
select {
case <-ctx.Done():
fmt.Printf("[%s] finishing Run\n", svc.name)
time.Sleep(svc.closeDuration)
return nil
case <-svc.chErrorTerm:
return fmt.Errorf("[%s] something went wrong", svc.name)
}
}
func (svc *TestService) Close() error {
close(svc.chErrorTerm)
fmt.Printf("[%s] is closed\n", svc.name)
return nil
}
func (svc *TestService) RaiseError() {
fmt.Printf("[%s] got raise an error\n", svc.name)
svc.chErrorTerm <- struct{}{}
}
func TestGroup_RunAndWait(t *testing.T) {
t.Parallel()
svc1 := NewTestService("svc1", 2*time.Second)
svc2 := NewTestService("svc2", 0*time.Second)
runGroup := Group{}
runGroup.AddJob(func(ctx context.Context) error {
defer func() { _ = svc1.Close() }()
return svc1.Run(ctx)
})
runGroup.AddJob(func(ctx context.Context) error {
defer func() { _ = svc2.Close() }()
return svc2.Run(ctx)
})
go func() {
time.Sleep(3 * time.Second)
svc2.RaiseError()
}()
ctx := context.Background()
if err := runGroup.RunAndWait(ctx); err != nil {
fmt.Println("error:", err)
}
}