github.com/go-playground/pkg/v5@v5.29.1/app/context_test.go (about) 1 package appext 2 3 import ( 4 "context" 5 . "github.com/go-playground/assert/v2" 6 "os" 7 "os/signal" 8 "sync" 9 "testing" 10 "time" 11 ) 12 13 func TestForceExitWithNoTimeout(t *testing.T) { 14 var wg sync.WaitGroup 15 wg.Add(1) 16 exitFn := func(code int) { 17 defer wg.Done() 18 Equal(t, 1, code) 19 } 20 21 c := Context().Timeout(0).ExitFn(exitFn) 22 23 // copy of Build for testing 24 var sig = make(chan os.Signal, 1) 25 signal.Notify(sig, c.signals...) 26 27 ctx, cancel := context.WithCancel(context.Background()) 28 29 go listen(sig, cancel, c.exitFn, c.timeout, c.forceExit) 30 31 sig <- os.Interrupt 32 sig <- os.Interrupt 33 wg.Wait() 34 Equal(t, context.Canceled, ctx.Err()) 35 } 36 37 func TestForceExitWithTimeout(t *testing.T) { 38 var wg sync.WaitGroup 39 wg.Add(1) 40 exitFn := func(code int) { 41 defer wg.Done() 42 Equal(t, 1, code) 43 } 44 45 c := Context().Timeout(time.Hour).ExitFn(exitFn) 46 47 // copy of Build for testing 48 var sig = make(chan os.Signal, 1) 49 signal.Notify(sig, c.signals...) 50 51 ctx, cancel := context.WithCancel(context.Background()) 52 53 go listen(sig, cancel, c.exitFn, c.timeout, c.forceExit) 54 55 sig <- os.Interrupt 56 sig <- os.Interrupt 57 wg.Wait() 58 Equal(t, context.Canceled, ctx.Err()) 59 } 60 61 func TestTimeoutWithNoForceExit(t *testing.T) { 62 var wg sync.WaitGroup 63 wg.Add(1) 64 exitFn := func(code int) { 65 defer wg.Done() 66 Equal(t, 1, code) 67 } 68 69 c := Context().Timeout(time.Millisecond * 200).ForceExit(false).ExitFn(exitFn) 70 71 // copy of Build for testing 72 var sig = make(chan os.Signal, 1) 73 signal.Notify(sig, c.signals...) 74 75 ctx, cancel := context.WithCancel(context.Background()) 76 77 go listen(sig, cancel, c.exitFn, c.timeout, c.forceExit) 78 79 // only sending one, timeout must be reached for test to finish 80 sig <- os.Interrupt 81 wg.Wait() 82 Equal(t, context.Canceled, ctx.Err()) 83 }