retry_test.go 1.8 KB

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