9 "github.com/stretchr/testify/assert"
12 func TestReceivesSignal(t *testing.T) {
13 ctx := UntilSignal(context.Background(), syscall.SIGUSR2)
14 assert.NoError(t, ctx.Err())
15 syscall.Kill(syscall.Getpid(), syscall.SIGUSR2)
17 assert.Equal(t, Error{syscall.SIGUSR2}, ctx.Err())
20 func TestForwardsParent(t *testing.T) {
21 parent, _ := context.WithTimeout(
22 context.WithValue(context.Background(), t, "test"),
24 ctx := UntilSignal(parent, syscall.SIGUSR2)
25 assert.NoError(t, ctx.Err())
26 dl, ok := ctx.Deadline()
28 assert.WithinDuration(t, time.Now(), dl, time.Millisecond)
29 assert.EqualValues(t, "test", ctx.Value(t))
31 assert.Equal(t, context.DeadlineExceeded, ctx.Err())
34 func TestChildForwardsErr(t *testing.T) {
35 ctx := UntilSignal(context.Background(), syscall.SIGUSR2)
36 child, cancel := context.WithTimeout(ctx, time.Second)
37 syscall.Kill(syscall.Getpid(), syscall.SIGUSR2)
41 assert.Equal(t, Error{syscall.SIGUSR2}, ctx.Err())
42 assert.Equal(t, Error{syscall.SIGUSR2}, child.Err())
45 func TestSignalAfterCancel(t *testing.T) {
46 ctx := UntilSignal(context.Background(), syscall.SIGUSR2)
47 assert.NoError(t, ctx.Err())
50 assert.Equal(t, context.Canceled, ctx.Err())
51 syscall.Kill(syscall.Getpid(), syscall.SIGUSR2)
52 time.Sleep(5 * time.Millisecond)
53 assert.Equal(t, context.Canceled, ctx.Err())
56 func TestCancelAfterSignal(t *testing.T) {
57 ctx := UntilSignal(context.Background(), syscall.SIGUSR2)
58 assert.NoError(t, ctx.Err())
59 syscall.Kill(syscall.Getpid(), syscall.SIGUSR2)
61 assert.Equal(t, Error{syscall.SIGUSR2}, ctx.Err())
63 time.Sleep(5 * time.Millisecond)
64 assert.Equal(t, Error{syscall.SIGUSR2}, ctx.Err())
67 func TestImmediateCompletion(t *testing.T) {
68 parent, cancel := context.WithCancel(context.Background())
71 ctx := UntilSignal(parent, syscall.SIGUSR2)
72 // peek inside to be certain we never set up the signal channel.
75 case _, ok := <-ctx.Done():
76 assert.False(t, ok, "Done() should be closed")
78 assert.False(t, true, "context should be complete")
80 assert.Equal(t, context.Canceled, ctx.Err())
83 func BenchmarkReceivesSignal(b *testing.B) {
84 for i := 0; i < b.N; i++ {
85 ctx := UntilSignal(context.Background(), syscall.SIGUSR2)
86 syscall.Kill(syscall.Getpid(), syscall.SIGUSR2)
91 func BenchmarkCancelChildren(b *testing.B) {
92 children := make([]context.Context, b.N)
93 cancels := make([]context.CancelFunc, b.N)
95 ctx := UntilSignal(context.Background(), syscall.SIGUSR2)
96 for i := range children {
97 children[i], cancels[i] = context.WithTimeout(ctx, time.Hour)
99 syscall.Kill(syscall.Getpid(), syscall.SIGUSR2)
101 for i := range children {
105 for i := range cancels {
110 func BenchmarkCanceledAsChild(b *testing.B) {
111 children := make([]context.Context, b.N)
112 parent, cancel := context.WithCancel(context.Background())
114 for i := range children {
115 children[i] = UntilSignal(parent, syscall.SIGUSR2)
119 for i := range children {