retry_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package retry_test
  2. import (
  3. "errors"
  4. "testing"
  5. "time"
  6. . "github.com/v2ray/v2ray-core/common/retry"
  7. "github.com/v2ray/v2ray-core/testing/assert"
  8. )
  9. var (
  10. errorTestOnly = errors.New("This is a fake error.")
  11. )
  12. func TestNoRetry(t *testing.T) {
  13. assert := assert.On(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.Error(err).IsNil()
  20. assert.Int64(endTime - startTime).AtLeast(0)
  21. }
  22. func TestRetryOnce(t *testing.T) {
  23. assert := assert.On(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.Error(err).IsNil()
  35. assert.Int64(int64(duration / time.Millisecond)).AtLeast(900)
  36. }
  37. func TestRetryMultiple(t *testing.T) {
  38. assert := assert.On(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.Error(err).IsNil()
  50. assert.Int64(int64(duration / time.Millisecond)).AtLeast(4900)
  51. }
  52. func TestRetryExhausted(t *testing.T) {
  53. assert := assert.On(t)
  54. startTime := time.Now()
  55. called := 0
  56. err := Timed(2, 1000).On(func() error {
  57. if called < 5 {
  58. called++
  59. return errorTestOnly
  60. }
  61. return nil
  62. })
  63. duration := time.Since(startTime)
  64. assert.Error(err).Equals(ErrRetryFailed)
  65. assert.Int64(int64(duration / time.Millisecond)).AtLeast(1900)
  66. }