/
ctxcli_test.go
97 lines (80 loc) · 2.03 KB
/
ctxcli_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
package ctxcli
import (
"context"
"os"
"os/exec"
"os/signal"
"syscall"
"testing"
"time"
)
func TestWithSignalTrap(t *testing.T) {
testCtx := WithSignalTrap(context.Background(), syscall.SIGUSR1)
cli, ok := FromContext(testCtx)
if !ok {
t.Fatalf("failed to get cli FromContext: %v", cli)
}
defer signal.Stop(cli.sigChan)
cli.sigChan <- syscall.SIGUSR1
waitDone(t, testCtx)
if testCtx.Err() != context.Canceled {
t.Fatalf("testCtx should be cancelled: %+v", testCtx)
}
}
func TestWithInterrupt(t *testing.T) {
testCtx := WithInterrupt(context.Background())
cli, ok := FromContext(testCtx)
if !ok {
t.Fatalf("failed to get cli FromContext: %v", cli)
}
defer signal.Stop(cli.sigChan)
cli.sigChan <- syscall.SIGINT
waitDone(t, testCtx)
if testCtx.Err() != context.Canceled {
t.Fatalf("testCtx should be cancelled: %+v", testCtx)
}
}
func TestExitIfCancelled(t *testing.T) {
if os.Getenv("BE_CRASHER") == "1" {
testCtx := WithInterrupt(context.Background())
cli, ok := FromContext(testCtx)
if !ok {
t.Fatalf("failed to get cli FromContext: %v", cli)
}
defer signal.Stop(cli.sigChan)
cli.sigChan <- syscall.SIGINT
waitDone(t, testCtx)
ExitIfCancelled(testCtx, 1)
return
}
cmd := exec.Command(os.Args[0], "-test.run=TestExitIfCancelled")
cmd.Env = append(os.Environ(), "BE_CRASHER=1")
err := cmd.Run()
if e, ok := err.(*exec.ExitError); ok && !e.Success() {
return
}
t.Fatalf("process ran with err %v, want exit status 1", err)
}
func TestPanicIfCancelled(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("the code did not panic")
}
}()
testCtx := WithInterrupt(context.Background())
cli, ok := FromContext(testCtx)
if !ok {
t.Fatalf("failed to get cli FromContext: %v", cli)
}
defer signal.Stop(cli.sigChan)
cli.sigChan <- syscall.SIGINT
waitDone(t, testCtx)
PanicIfCancelled(testCtx)
}
func waitDone(t *testing.T, ctx context.Context) {
select {
case <-time.After(1 * time.Second):
t.Fatalf("timeout waiting for Done() from %v", ctx)
case <-ctx.Done():
}
}