retry_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package retry_test
  2. import (
  3. "testing"
  4. "time"
  5. "v2ray.com/core/common/errors"
  6. . "v2ray.com/core/common/retry"
  7. . "v2ray.com/ext/assert"
  8. )
  9. var (
  10. errorTestOnly = errors.New("This is a fake error.")
  11. )
  12. func TestNoRetry(t *testing.T) {
  13. assert := With(t)
  14. startTime := time.Now().Unix()
  15. err := Timed(10, 100000).On(func() error {
  16. return nil
  17. })
  18. endTime := time.Now().Unix()
  19. assert(err, IsNil)
  20. assert(endTime-startTime, AtLeast, int64(0))
  21. }
  22. func TestRetryOnce(t *testing.T) {
  23. assert := With(t)
  24. startTime := time.Now()
  25. called := 0
  26. err := Timed(10, 1000).On(func() error {
  27. if called == 0 {
  28. called++
  29. return errorTestOnly
  30. }
  31. return nil
  32. })
  33. duration := time.Since(startTime)
  34. assert(err, IsNil)
  35. assert(int64(duration/time.Millisecond), AtLeast, int64(900))
  36. }
  37. func TestRetryMultiple(t *testing.T) {
  38. assert := With(t)
  39. startTime := time.Now()
  40. called := 0
  41. err := Timed(10, 1000).On(func() error {
  42. if called < 5 {
  43. called++
  44. return errorTestOnly
  45. }
  46. return nil
  47. })
  48. duration := time.Since(startTime)
  49. assert(err, IsNil)
  50. assert(int64(duration/time.Millisecond), AtLeast, int64(4900))
  51. }
  52. func TestRetryExhausted(t *testing.T) {
  53. assert := With(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. assert(errors.Cause(err), Equals, ErrRetryFailed)
  62. assert(int64(duration/time.Millisecond), AtLeast, int64(1900))
  63. }
  64. func TestExponentialBackoff(t *testing.T) {
  65. assert := With(t)
  66. startTime := time.Now()
  67. called := 0
  68. err := ExponentialBackoff(10, 100).On(func() error {
  69. called++
  70. return errorTestOnly
  71. })
  72. duration := time.Since(startTime)
  73. assert(errors.Cause(err), Equals, ErrRetryFailed)
  74. assert(int64(duration/time.Millisecond), AtLeast, int64(4000))
  75. }