github.com/EagleQL/Xray-core@v1.4.3/common/retry/retry_test.go (about) 1 package retry_test 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/xtls/xray-core/common" 8 "github.com/xtls/xray-core/common/errors" 9 . "github.com/xtls/xray-core/common/retry" 10 ) 11 12 var ( 13 errorTestOnly = errors.New("this is a fake error") 14 ) 15 16 func TestNoRetry(t *testing.T) { 17 startTime := time.Now().Unix() 18 err := Timed(10, 100000).On(func() error { 19 return nil 20 }) 21 endTime := time.Now().Unix() 22 23 common.Must(err) 24 if endTime < startTime { 25 t.Error("endTime < startTime: ", startTime, " -> ", endTime) 26 } 27 } 28 29 func TestRetryOnce(t *testing.T) { 30 startTime := time.Now() 31 called := 0 32 err := Timed(10, 1000).On(func() error { 33 if called == 0 { 34 called++ 35 return errorTestOnly 36 } 37 return nil 38 }) 39 duration := time.Since(startTime) 40 41 common.Must(err) 42 if v := int64(duration / time.Millisecond); v < 900 { 43 t.Error("duration: ", v) 44 } 45 } 46 47 func TestRetryMultiple(t *testing.T) { 48 startTime := time.Now() 49 called := 0 50 err := Timed(10, 1000).On(func() error { 51 if called < 5 { 52 called++ 53 return errorTestOnly 54 } 55 return nil 56 }) 57 duration := time.Since(startTime) 58 59 common.Must(err) 60 if v := int64(duration / time.Millisecond); v < 4900 { 61 t.Error("duration: ", v) 62 } 63 } 64 65 func TestRetryExhausted(t *testing.T) { 66 startTime := time.Now() 67 called := 0 68 err := Timed(2, 1000).On(func() error { 69 called++ 70 return errorTestOnly 71 }) 72 duration := time.Since(startTime) 73 74 if errors.Cause(err) != ErrRetryFailed { 75 t.Error("cause: ", err) 76 } 77 78 if v := int64(duration / time.Millisecond); v < 1900 { 79 t.Error("duration: ", v) 80 } 81 } 82 83 func TestExponentialBackoff(t *testing.T) { 84 startTime := time.Now() 85 called := 0 86 err := ExponentialBackoff(10, 100).On(func() error { 87 called++ 88 return errorTestOnly 89 }) 90 duration := time.Since(startTime) 91 92 if errors.Cause(err) != ErrRetryFailed { 93 t.Error("cause: ", err) 94 } 95 if v := int64(duration / time.Millisecond); v < 4000 { 96 t.Error("duration: ", v) 97 } 98 }