retry_test.go 1.5 KB

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