-
Notifications
You must be signed in to change notification settings - Fork 0
/
context_test.go
79 lines (72 loc) · 1.74 KB
/
context_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
package ctxsignal
import (
"context"
"fmt"
"os"
"syscall"
"testing"
"time"
)
func ExampleWithSignals() {
ctx := WithSignals(context.Background(), syscall.SIGUSR1)
go func() {
time.Sleep(500 * time.Millisecond) // after some time SIGUSR1 is sent
// mimicking a signal from the outside
syscall.Kill(syscall.Getpid(), syscall.SIGUSR1)
}()
<-ctx.Done()
fmt.Println("finished")
// Output:
// finished
}
func Example_withUnregisteredSignals() {
dctx, cancel := context.WithTimeout(context.TODO(), time.Millisecond*100)
defer cancel()
ctx := WithSignals(dctx, syscall.SIGUSR1)
go func() {
time.Sleep(10 * time.Millisecond) // after some time SIGUSR2 is sent
// mimicking a signal from the outside, WithSignals will not handle it
syscall.Kill(syscall.Getpid(), syscall.SIGUSR2)
}()
<-ctx.Done()
fmt.Println("finished")
// Output:
// finished
}
func TestWithSignals(t *testing.T) {
tests := []struct {
name string
ctx context.Context
sigs []os.Signal
wantSignal bool
}{
{
name: "sending signal SIGUSR2 should exit context.",
ctx: context.Background(),
sigs: []os.Signal{syscall.SIGUSR2},
wantSignal: true,
},
{
name: "sending signal SIGUSR2 should NOT exit context.",
ctx: context.Background(),
sigs: []os.Signal{syscall.SIGUSR1},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := WithSignals(tt.ctx, tt.sigs...)
syscall.Kill(syscall.Getpid(), syscall.SIGUSR2)
timer := time.NewTimer(500 * time.Millisecond)
select {
case <-ctx.Done():
if !tt.wantSignal {
t.Errorf("unexpected exit with signal")
}
case <-timer.C:
if tt.wantSignal {
t.Errorf("expected to exit with signal but did not")
}
}
})
}
}