retry_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. )
  9. var (
  10. errorTestOnly = errors.New("This is a fake error.")
  11. )
  12. func TestNoRetry(t *testing.T) {
  13. startTime := time.Now().Unix()
  14. err := Timed(10, 100000).On(func() error {
  15. return nil
  16. })
  17. endTime := time.Now().Unix()
  18. common.Must(err)
  19. if endTime < startTime {
  20. t.Error("endTime < startTime: ", startTime, " -> ", endTime)
  21. }
  22. }
  23. func TestRetryOnce(t *testing.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. common.Must(err)
  35. if v := int64(duration / time.Millisecond); v < 900 {
  36. t.Error("duration: ", v)
  37. }
  38. }
  39. func TestRetryMultiple(t *testing.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. if v := int64(duration / time.Millisecond); v < 4900 {
  52. t.Error("duration: ", v)
  53. }
  54. }
  55. func TestRetryExhausted(t *testing.T) {
  56. startTime := time.Now()
  57. called := 0
  58. err := Timed(2, 1000).On(func() error {
  59. called++
  60. return errorTestOnly
  61. })
  62. duration := time.Since(startTime)
  63. if errors.Cause(err) != ErrRetryFailed {
  64. t.Error("cause: ", err)
  65. }
  66. if v := int64(duration / time.Millisecond); v < 1900 {
  67. t.Error("duration: ", v)
  68. }
  69. }
  70. func TestExponentialBackoff(t *testing.T) {
  71. startTime := time.Now()
  72. called := 0
  73. err := ExponentialBackoff(10, 100).On(func() error {
  74. called++
  75. return errorTestOnly
  76. })
  77. duration := time.Since(startTime)
  78. if errors.Cause(err) != ErrRetryFailed {
  79. t.Error("cause: ", err)
  80. }
  81. if v := int64(duration / time.Millisecond); v < 4000 {
  82. t.Error("duration: ", v)
  83. }
  84. }