1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
package errors
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestRetryAfterWithContext(t *testing.T) {
calls := 0
ret := Retry(context.Background(), time.Second, func() error {
calls++
return nil
}, 0)
assert.NoError(t, ret)
assert.Equal(t, 1, calls)
}
func TestRetryAfterFailure(t *testing.T) {
calls := 0
ret := Retry(context.Background(), time.Second, func() error {
calls++
return errors.New("failed")
}, 0)
assert.EqualError(t, ret, "failed")
assert.Equal(t, 1, calls)
}
func TestRetryAfterSlowFailure(t *testing.T) {
calls := 0
ret := Retry(context.Background(), time.Millisecond, func() error {
time.Sleep(50 * time.Millisecond)
calls++
if calls < 2 {
return &RetriableError{Err: errors.New("failed")}
}
return nil
}, 0)
assert.NoError(t, ret)
assert.Equal(t, 2, calls)
}
func TestRetryAfterMaxAttempts(t *testing.T) {
calls := 0
ret := Retry(context.Background(), 10*time.Millisecond, func() error {
calls++
return &RetriableError{Err: errors.New("failed")}
}, 0)
assert.EqualError(t, ret, fmt.Sprintf("Temporary error: failed (x%d)", calls))
assert.Greater(t, calls, 5)
}
func TestRetryAfterSuccessAfterFailures(t *testing.T) {
calls := 0
ret := Retry(context.Background(), time.Second, func() error {
calls++
if calls < 3 {
return &RetriableError{Err: errors.New("failed")}
}
return nil
}, 0)
assert.NoError(t, ret)
assert.Equal(t, 3, calls)
}
func TestMultiErrorString(t *testing.T) {
assert.Equal(t, "Temporary Error: No Pending CSR (x4)", MultiError{
Errors: []error{
errors.New("Temporary Error: No Pending CSR"),
errors.New("Temporary Error: No Pending CSR"),
errors.New("Temporary Error: No Pending CSR"),
errors.New("Temporary Error: No Pending CSR"),
},
}.Error())
assert.Equal(t, "No Pending CSR (x2)\nConnection refused (x2)\nNo Pending CSR", MultiError{
Errors: []error{
errors.New("No Pending CSR"),
errors.New("No Pending CSR"),
errors.New("Connection refused"),
errors.New("Connection refused"),
errors.New("No Pending CSR"),
},
}.Error())
}
|