timer_test.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package signal_test
  2. import (
  3. "context"
  4. "runtime"
  5. "testing"
  6. "time"
  7. . "v2ray.com/core/common/signal"
  8. . "v2ray.com/ext/assert"
  9. )
  10. func TestActivityTimer(t *testing.T) {
  11. assert := With(t)
  12. ctx, cancel := context.WithCancel(context.Background())
  13. timer := CancelAfterInactivity(ctx, cancel, time.Second*5)
  14. time.Sleep(time.Second * 6)
  15. assert(ctx.Err(), IsNotNil)
  16. runtime.KeepAlive(timer)
  17. }
  18. func TestActivityTimerUpdate(t *testing.T) {
  19. assert := With(t)
  20. ctx, cancel := context.WithCancel(context.Background())
  21. timer := CancelAfterInactivity(ctx, cancel, time.Second*10)
  22. time.Sleep(time.Second * 3)
  23. assert(ctx.Err(), IsNil)
  24. timer.SetTimeout(time.Second * 1)
  25. time.Sleep(time.Second * 2)
  26. assert(ctx.Err(), IsNotNil)
  27. runtime.KeepAlive(timer)
  28. }
  29. func TestActivityTimerNonBlocking(t *testing.T) {
  30. assert := With(t)
  31. ctx, cancel := context.WithCancel(context.Background())
  32. timer := CancelAfterInactivity(ctx, cancel, 0)
  33. time.Sleep(time.Second * 1)
  34. assert(ctx, HasDone)
  35. timer.SetTimeout(0)
  36. timer.SetTimeout(1)
  37. timer.SetTimeout(2)
  38. }
  39. func TestActivityTimerZeroTimeout(t *testing.T) {
  40. assert := With(t)
  41. ctx, cancel := context.WithCancel(context.Background())
  42. timer := CancelAfterInactivity(ctx, cancel, 0)
  43. assert(ctx, HasDone)
  44. runtime.KeepAlive(timer)
  45. }