You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
74 lines
1.3 KiB
Go
74 lines
1.3 KiB
Go
1 year ago
|
package retry
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"errors"
|
||
|
"git.noahlan.cn/noahlan/ntool/ntest/assert"
|
||
|
"testing"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
func TestRetryFailed(t *testing.T) {
|
||
|
|
||
|
var number int
|
||
|
increaseNumber := func() error {
|
||
|
number++
|
||
|
return errors.New("error occurs")
|
||
|
}
|
||
|
|
||
|
err := Retry(increaseNumber, WithDuration(time.Microsecond*50))
|
||
|
assert.NotNil(t, err)
|
||
|
assert.Equal(t, DefaultRetryTimes, number)
|
||
|
}
|
||
|
|
||
|
func TestRetrySucceeded(t *testing.T) {
|
||
|
var number int
|
||
|
increaseNumber := func() error {
|
||
|
number++
|
||
|
if number == DefaultRetryTimes {
|
||
|
return nil
|
||
|
}
|
||
|
return errors.New("error occurs")
|
||
|
}
|
||
|
|
||
|
err := Retry(increaseNumber, WithDuration(time.Microsecond*50))
|
||
|
|
||
|
assert.Nil(t, err)
|
||
|
assert.Equal(t, DefaultRetryTimes, number)
|
||
|
}
|
||
|
|
||
|
func TestSetRetryTimes(t *testing.T) {
|
||
|
|
||
|
var number int
|
||
|
increaseNumber := func() error {
|
||
|
number++
|
||
|
return errors.New("error occurs")
|
||
|
}
|
||
|
|
||
|
err := Retry(increaseNumber, WithDuration(time.Microsecond*50), WithTimes(3))
|
||
|
|
||
|
assert.NotNil(t, err)
|
||
|
assert.Equal(t, 3, number)
|
||
|
}
|
||
|
|
||
|
func TestCancelRetry(t *testing.T) {
|
||
|
ctx, cancel := context.WithCancel(context.TODO())
|
||
|
var number int
|
||
|
increaseNumber := func() error {
|
||
|
number++
|
||
|
if number > 3 {
|
||
|
cancel()
|
||
|
}
|
||
|
return errors.New("error occurs")
|
||
|
}
|
||
|
|
||
|
err := Retry(increaseNumber,
|
||
|
WithDuration(time.Microsecond*50),
|
||
|
WithContext(ctx),
|
||
|
WithTimes(100),
|
||
|
)
|
||
|
|
||
|
assert.NotNil(t, err)
|
||
|
assert.Equal(t, 4, number)
|
||
|
}
|