2015-11-02 18:07:15 -05:00
|
|
|
package retry
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/v2ray/v2ray-core/testing/unit"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
TestError = errors.New("This is a fake error.")
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestNoRetry(t *testing.T) {
|
|
|
|
assert := unit.Assert(t)
|
|
|
|
|
|
|
|
startTime := time.Now().Unix()
|
2015-11-02 18:12:25 -05:00
|
|
|
err := Timed(10, 100000).On(func() error {
|
2015-11-02 18:07:15 -05:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
endTime := time.Now().Unix()
|
|
|
|
|
2015-11-02 18:12:25 -05:00
|
|
|
assert.Error(err).IsNil()
|
2015-11-02 18:07:15 -05:00
|
|
|
assert.Int64(endTime - startTime).AtLeast(0)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestRetryOnce(t *testing.T) {
|
|
|
|
assert := unit.Assert(t)
|
|
|
|
|
|
|
|
startTime := time.Now()
|
|
|
|
called := 0
|
2015-11-02 18:12:25 -05:00
|
|
|
err := Timed(10, 1000).On(func() error {
|
2015-11-02 18:07:15 -05:00
|
|
|
if called == 0 {
|
|
|
|
called++
|
|
|
|
return TestError
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
duration := time.Since(startTime)
|
|
|
|
|
2015-11-02 18:12:25 -05:00
|
|
|
assert.Error(err).IsNil()
|
2015-11-02 18:07:15 -05:00
|
|
|
assert.Int64(int64(duration / time.Millisecond)).AtLeast(900)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestRetryMultiple(t *testing.T) {
|
|
|
|
assert := unit.Assert(t)
|
|
|
|
|
|
|
|
startTime := time.Now()
|
|
|
|
called := 0
|
2015-11-02 18:12:25 -05:00
|
|
|
err := Timed(10, 1000).On(func() error {
|
2015-11-02 18:07:15 -05:00
|
|
|
if called < 5 {
|
|
|
|
called++
|
|
|
|
return TestError
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
duration := time.Since(startTime)
|
|
|
|
|
2015-11-02 18:12:25 -05:00
|
|
|
assert.Error(err).IsNil()
|
2015-11-02 18:07:15 -05:00
|
|
|
assert.Int64(int64(duration / time.Millisecond)).AtLeast(4900)
|
|
|
|
}
|
2015-11-02 18:12:25 -05:00
|
|
|
|
|
|
|
func TestRetryExhausted(t *testing.T) {
|
|
|
|
assert := unit.Assert(t)
|
|
|
|
|
|
|
|
startTime := time.Now()
|
|
|
|
called := 0
|
|
|
|
err := Timed(2, 1000).On(func() error {
|
|
|
|
if called < 5 {
|
|
|
|
called++
|
|
|
|
return TestError
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
duration := time.Since(startTime)
|
|
|
|
|
|
|
|
assert.Error(err).Equals(RetryFailed)
|
|
|
|
assert.Int64(int64(duration / time.Millisecond)).AtLeast(1900)
|
|
|
|
}
|