-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
grace_test.go
126 lines (108 loc) · 2.36 KB
/
grace_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
package grace_test
import (
"context"
"errors"
"fmt"
"github.com/tomwright/grace"
"reflect"
"testing"
"time"
)
func ExampleInit() {
g := grace.Init(context.Background())
fmt.Println("Starting")
g.Run(grace.RunnerFunc(func(ctx context.Context) error {
for {
select {
case <-ctx.Done():
fmt.Println("Graceful shutdown initiated")
// Fake a 3 second shutdown
for i := 3; i >= 0; i-- {
fmt.Printf("Shutting down in %d\n", i)
time.Sleep(time.Second * time.Duration(i))
}
return nil
case <-time.After(time.Second):
fmt.Println("Hello")
}
}
}))
go func() {
<-time.After(time.Millisecond * 2500)
fmt.Println("Triggering shutdown")
g.Shutdown()
}()
fmt.Println("Started")
<-g.Context().Done()
g.Wait()
fmt.Println("Shutdown")
// Output:
// Starting
// Started
// Hello
// Hello
// Triggering shutdown
// Graceful shutdown initiated
// Shutting down in 3
// Shutting down in 2
// Shutting down in 1
// Shutting down in 0
// Shutdown
}
func TestGrace_Run_Error(t *testing.T) {
errExpected := errors.New("expected error")
gotErrors := map[error]int{}
g := grace.Init(context.Background())
g.ErrHandler = func(err error) bool {
if _, ok := gotErrors[err]; !ok {
gotErrors[err] = 0
}
gotErrors[err]++
return true
}
g.Run(grace.RunnerFunc(func(ctx context.Context) error {
return errExpected
}))
select {
case <-g.Context().Done():
case <-time.After(time.Second):
t.Errorf("did not send shutdown signal after 1s")
g.Shutdown()
}
expErrors := map[error]int{
errExpected: 1,
}
if !reflect.DeepEqual(expErrors, gotErrors) {
t.Errorf("expected errors: %v, got errors: %v", expErrors, gotErrors)
return
}
}
func TestGrace_Run_Panic(t *testing.T) {
found := false
g := grace.Init(context.Background())
g.ErrHandler = func(err error) bool {
if e, ok := err.(grace.RecoveredPanicError); ok {
if fmt.Sprintf("%v", e.Err) == "whoops" {
found = true
} else {
t.Errorf("unexpected error: %T: %v", err, err)
}
} else {
t.Errorf("unexpected error type: %T: %v", err, err)
}
return true
}
g.Run(grace.RunnerFunc(func(ctx context.Context) error {
panic("whoops")
return nil
}))
select {
case <-g.Context().Done():
case <-time.After(time.Second):
t.Errorf("did not send shutdown signal after 1s")
g.Shutdown()
}
if !found {
t.Errorf("panic error not found")
}
}