timer_test.go 1.4 KB

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