package playback import ( "testing" "time" ) func TestFiniteAttempts(t *testing.T) { rp := RetryPolicy{ MaxAttempts: 3, InitialDelay: 500 * time.Millisecond, MaxDelay: 10 * time.Second, } if !rp.canRetry(1) { t.Fatal("MaxAttempts=3, failed=1, but can't retry") } if !rp.canRetry(2) { t.Fatal("MaxAttempts=3, failed=2, but can't retry") } if rp.canRetry(3) { t.Fatal("MaxAttempts=3, failed=3, but can retry") } } func TestOneAllowedAttempt(t *testing.T) { rp := RetryPolicy{ MaxAttempts: 1, InitialDelay: 500 * time.Millisecond, MaxDelay: 10 * time.Second, } if rp.canRetry(1) { t.Fatal("MaxAttempts=1, failed=1, but can retry") } } func TestUnlimitedAttempts(t *testing.T) { rp := RetryPolicy{ MaxAttempts: 0, InitialDelay: 500 * time.Millisecond, MaxDelay: 10 * time.Second, } for failedAttempts := 1; failedAttempts <= 10; failedAttempts++ { if !rp.canRetry(failedAttempts) { t.Fatalf( "canRetry(%d) = false for unlimited policy", failedAttempts, ) } } } func TestBackoff(t *testing.T) { rp := RetryPolicy{ MaxAttempts: 0, InitialDelay: 500 * time.Millisecond, MaxDelay: 10 * time.Second, } want := []time.Duration{ 500 * time.Millisecond, 1 * time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 10 * time.Second, 10 * time.Second, } for i, wantDelay := range want { failedAttempts := i + 1 got := rp.retryDelay(failedAttempts) if got != wantDelay { t.Errorf( "retryDelay(%d) = %s, want %s", failedAttempts, got, wantDelay, ) } } } func TestRetryDelayLargeFailureCount(t *testing.T) { policy := RetryPolicy{ MaxAttempts: 0, InitialDelay: 500 * time.Millisecond, MaxDelay: 10 * time.Second, } if got := policy.retryDelay(1_000_000); got != policy.MaxDelay { t.Fatalf("retryDelay() = %s, want cap %s", got, policy.MaxDelay) } }