34 lines
809 B
Go
34 lines
809 B
Go
package resilience
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestRetrySucceedsOnThirdAttempt(t *testing.T) {
|
|
calls := 0
|
|
err := RetryWithContext(context.Background(), 3, time.Millisecond, func(ctx context.Context) error {
|
|
calls++
|
|
if calls < 3 {
|
|
return errors.New("transient")
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil || calls != 3 {
|
|
t.Fatalf("got err=%v calls=%d, want nil and 3", err, calls)
|
|
}
|
|
}
|
|
|
|
func TestRetryStopsOnContextCancel(t *testing.T) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Millisecond)
|
|
defer cancel()
|
|
err := RetryWithContext(ctx, 10, 50*time.Millisecond, func(ctx context.Context) error {
|
|
return errors.New("always fails")
|
|
})
|
|
if !errors.Is(err, context.DeadlineExceeded) {
|
|
t.Fatalf("expected context.DeadlineExceeded, got %v", err)
|
|
}
|
|
}
|