retry_test.go 1.5 KB

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