-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsignal_test.go
119 lines (98 loc) · 2.16 KB
/
signal_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
package signal
import (
"context"
"os"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func WaitUntil(duration time.Duration, process, timout func()) {
stop := make(chan struct{})
go func() {
process()
close(stop)
}()
select {
case <-time.After(duration):
timout()
case <-stop:
}
}
func NoSignalArrived(t *testing.T) func() {
return func() {
t.Error("no signal arrived")
}
}
func TestOnce(t *testing.T) {
t.Run("normal", func(t *testing.T) {
var wg sync.WaitGroup
wg.Add(1)
Once(SigUsr1).Notify(context.Background(), func(sig os.Signal) {
if assert.Equal(t, SigUsr1, sig) {
wg.Done()
}
})
if pid := os.Getpid(); assert.Greater(t, pid, 0) {
if err := SendSignalUser1(pid); assert.NoError(t, err) {
WaitUntil(time.Second, wg.Wait, NoSignalArrived(t))
}
assert.NoError(t, SendSignalUser1(pid))
}
})
t.Run("canceled", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
wg.Add(1)
Once(SigUsr1).Notify(ctx, func(sig os.Signal) {
assert.Equal(t, SigCtx, sig)
wg.Done()
})
cancel()
wg.Wait()
})
}
func TestWhen(t *testing.T) {
t.Run("normal", func(t *testing.T) {
var wg sync.WaitGroup
wg.Add(1)
When(SigUsr2).Notify(context.TODO(), func(sig os.Signal) {
if assert.Equal(t, SigUsr2, sig) {
wg.Done()
}
})
if pid := os.Getpid(); assert.Greater(t, pid, 0) {
if assert.NoError(t, SendSignalUser2(pid)) {
WaitUntil(time.Second, func() {
wg.Wait()
wg.Add(1)
if assert.NoError(t, SendSignalUser2(pid)) {
wg.Wait()
}
}, NoSignalArrived(t))
}
}
})
t.Run("canceled", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
When(SigUsr2).Notify(ctx, func(sig os.Signal) {
assert.Equal(t, SigCtx, sig)
})
cancel()
})
}
func TestWith(t *testing.T) {
ctx, cancel := With(context.TODO(), SigUsr1)
defer cancel()
var wg sync.WaitGroup
wg.Add(1)
go func() {
<-ctx.Done()
wg.Done()
}()
if pid := os.Getpid(); assert.Greater(t, pid, 0) {
if err := SendSignalUser1(pid); assert.NoError(t, err) {
WaitUntil(time.Second, wg.Wait, NoSignalArrived(t))
}
}
}