github.com/xmplusdev/xmcore@v1.8.11-0.20240412132628-5518b55526af/common/signal/timer_test.go (about) 1 package signal_test 2 3 import ( 4 "context" 5 "runtime" 6 "testing" 7 "time" 8 9 . "github.com/xmplusdev/xmcore/common/signal" 10 ) 11 12 func TestActivityTimer(t *testing.T) { 13 ctx, cancel := context.WithCancel(context.Background()) 14 timer := CancelAfterInactivity(ctx, cancel, time.Second*4) 15 time.Sleep(time.Second * 6) 16 if ctx.Err() == nil { 17 t.Error("expected some error, but got nil") 18 } 19 runtime.KeepAlive(timer) 20 } 21 22 func TestActivityTimerUpdate(t *testing.T) { 23 ctx, cancel := context.WithCancel(context.Background()) 24 timer := CancelAfterInactivity(ctx, cancel, time.Second*10) 25 time.Sleep(time.Second * 3) 26 if ctx.Err() != nil { 27 t.Error("expected nil, but got ", ctx.Err().Error()) 28 } 29 timer.SetTimeout(time.Second * 1) 30 time.Sleep(time.Second * 2) 31 if ctx.Err() == nil { 32 t.Error("expcted some error, but got nil") 33 } 34 runtime.KeepAlive(timer) 35 } 36 37 func TestActivityTimerNonBlocking(t *testing.T) { 38 ctx, cancel := context.WithCancel(context.Background()) 39 timer := CancelAfterInactivity(ctx, cancel, 0) 40 time.Sleep(time.Second * 1) 41 select { 42 case <-ctx.Done(): 43 default: 44 t.Error("context not done") 45 } 46 timer.SetTimeout(0) 47 timer.SetTimeout(1) 48 timer.SetTimeout(2) 49 } 50 51 func TestActivityTimerZeroTimeout(t *testing.T) { 52 ctx, cancel := context.WithCancel(context.Background()) 53 timer := CancelAfterInactivity(ctx, cancel, 0) 54 select { 55 case <-ctx.Done(): 56 default: 57 t.Error("context not done") 58 } 59 runtime.KeepAlive(timer) 60 }