retry_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package retry_test
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/xtls/xray-core/common"
  6. "github.com/xtls/xray-core/common/errors"
  7. . "github.com/xtls/xray-core/common/retry"
  8. )
  9. var errorTestOnly = errors.New("this is a fake error")
  10. func TestNoRetry(t *testing.T) {
  11. startTime := time.Now().Unix()
  12. err := Timed(10, 100000).On(func() error {
  13. return nil
  14. })
  15. endTime := time.Now().Unix()
  16. common.Must(err)
  17. if endTime < startTime {
  18. t.Error("endTime < startTime: ", startTime, " -> ", endTime)
  19. }
  20. }
  21. func TestRetryOnce(t *testing.T) {
  22. startTime := time.Now()
  23. called := 0
  24. err := Timed(10, 1000).On(func() error {
  25. if called == 0 {
  26. called++
  27. return errorTestOnly
  28. }
  29. return nil
  30. })
  31. duration := time.Since(startTime)
  32. common.Must(err)
  33. if v := int64(duration / time.Millisecond); v < 900 {
  34. t.Error("duration: ", v)
  35. }
  36. }
  37. func TestRetryMultiple(t *testing.T) {
  38. startTime := time.Now()
  39. called := 0
  40. err := Timed(10, 1000).On(func() error {
  41. if called < 5 {
  42. called++
  43. return errorTestOnly
  44. }
  45. return nil
  46. })
  47. duration := time.Since(startTime)
  48. common.Must(err)
  49. if v := int64(duration / time.Millisecond); v < 4900 {
  50. t.Error("duration: ", v)
  51. }
  52. }
  53. func TestRetryExhausted(t *testing.T) {
  54. startTime := time.Now()
  55. called := 0
  56. err := Timed(2, 1000).On(func() error {
  57. called++
  58. return errorTestOnly
  59. })
  60. duration := time.Since(startTime)
  61. if errors.Cause(err) != ErrRetryFailed {
  62. t.Error("cause: ", err)
  63. }
  64. if v := int64(duration / time.Millisecond); v < 1900 {
  65. t.Error("duration: ", v)
  66. }
  67. }
  68. func TestExponentialBackoff(t *testing.T) {
  69. startTime := time.Now()
  70. called := 0
  71. err := ExponentialBackoff(10, 100).On(func() error {
  72. called++
  73. return errorTestOnly
  74. })
  75. duration := time.Since(startTime)
  76. if errors.Cause(err) != ErrRetryFailed {
  77. t.Error("cause: ", err)
  78. }
  79. if v := int64(duration / time.Millisecond); v < 4000 {
  80. t.Error("duration: ", v)
  81. }
  82. }