| 536 | } |
| 537 | |
| 538 | func TestRetryWithInterval(t *testing.T) { |
| 539 | t.Parallel() |
| 540 | |
| 541 | const interval = time.Millisecond |
| 542 | const maxAttempts = 3 |
| 543 | |
| 544 | dnsErr := &net.DNSError{Err: "no such host", Name: "example.com", IsNotFound: true} |
| 545 | logger := slogtest.Make(t, nil).Leveled(slog.LevelDebug) |
| 546 | |
| 547 | t.Run("Succeeds_FirstTry", func(t *testing.T) { |
| 548 | t.Parallel() |
| 549 | ctx := testutil.Context(t, testutil.WaitShort) |
| 550 | |
| 551 | attempts := 0 |
| 552 | err := retryWithInterval(ctx, logger, interval, maxAttempts, func() error { |
| 553 | attempts++ |
| 554 | return nil |
| 555 | }) |
| 556 | require.NoError(t, err) |
| 557 | assert.Equal(t, 1, attempts) |
| 558 | }) |
| 559 | |
| 560 | t.Run("Succeeds_AfterTransientFailures", func(t *testing.T) { |
| 561 | t.Parallel() |
| 562 | ctx := testutil.Context(t, testutil.WaitShort) |
| 563 | |
| 564 | attempts := 0 |
| 565 | err := retryWithInterval(ctx, logger, interval, maxAttempts, func() error { |
| 566 | attempts++ |
| 567 | if attempts < 3 { |
| 568 | return dnsErr |
| 569 | } |
| 570 | return nil |
| 571 | }) |
| 572 | require.NoError(t, err) |
| 573 | assert.Equal(t, 3, attempts) |
| 574 | }) |
| 575 | |
| 576 | t.Run("Stops_NonRetryableError", func(t *testing.T) { |
| 577 | t.Parallel() |
| 578 | ctx := testutil.Context(t, testutil.WaitShort) |
| 579 | |
| 580 | attempts := 0 |
| 581 | err := retryWithInterval(ctx, logger, interval, maxAttempts, func() error { |
| 582 | attempts++ |
| 583 | return xerrors.New("permanent failure") |
| 584 | }) |
| 585 | require.ErrorContains(t, err, "permanent failure") |
| 586 | assert.Equal(t, 1, attempts) |
| 587 | }) |
| 588 | |
| 589 | t.Run("Stops_MaxAttemptsExhausted", func(t *testing.T) { |
| 590 | t.Parallel() |
| 591 | ctx := testutil.Context(t, testutil.WaitShort) |
| 592 | |
| 593 | attempts := 0 |
| 594 | err := retryWithInterval(ctx, logger, interval, maxAttempts, func() error { |
| 595 | attempts++ |