...
1
16
17 package testcontext
18
19 import (
20 "context"
21 "os"
22 "os/signal"
23 "testing"
24 "time"
25 )
26
27 func ForTest(t *testing.T) context.Context {
28 t.Helper()
29
30 ctx, cancel := context.WithCancel(context.Background())
31 t.Cleanup(cancel)
32
33 shuttingDown := make(chan struct{})
34 finished := make(chan struct{})
35 t.Cleanup(func() {
36 close(shuttingDown)
37 <-finished
38 })
39
40 c := make(chan os.Signal, 2)
41 signal.Notify(c, shutdownSignals...)
42 go func() {
43 defer close(finished)
44
45 select {
46 case <-c:
47 cancel()
48 case <-shuttingDown:
49 return
50 }
51
52 select {
53 case <-c:
54 os.Exit(1)
55 case <-shuttingDown:
56 return
57 }
58 }()
59
60 if deadline, ok := t.Deadline(); ok {
61 var cancel context.CancelFunc
62
63 ctx, cancel = context.WithDeadline(ctx, deadline.Add(-5*time.Second))
64 t.Cleanup(cancel)
65 }
66
67 return ctx
68 }
69
View as plain text