Skip to content

Commit a5c8296

Browse files
medyaghsethvargo
andauthored
add more unit tests (#36)
This PR improves test coverage by adding unit tests for context cancellation and edge case configuration. --------- Signed-off-by: Medya Ghazizadeh <medyagh@users.noreply.github.com> Co-authored-by: Seth Vargo <seth@sethvargo.com>
1 parent e344516 commit a5c8296

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

backoff_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,24 @@ func TestWithMaxRetries(t *testing.T) {
126126
}
127127
}
128128

129+
func TestWithMaxRetries_Zero(t *testing.T) {
130+
t.Parallel()
131+
132+
// This test verifies the behavior of WithMaxRetries when the maximum number
133+
// of retries is set to 0.
134+
b := retry.WithMaxRetries(0, retry.BackoffFunc(func() (time.Duration, bool) {
135+
return 1 * time.Second, false
136+
}))
137+
138+
val, stop := b.Next()
139+
if !stop {
140+
t.Errorf("should stop")
141+
}
142+
if val != 0 {
143+
t.Errorf("expected %v to be %v", val, 0)
144+
}
145+
}
146+
129147
func ExampleWithMaxRetries() {
130148
ctx := context.Background()
131149

retry_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,37 @@ func TestDo(t *testing.T) {
149149
t.Errorf("expected %v to be %v", err, context.DeadlineExceeded)
150150
}
151151
})
152+
153+
t.Run("deadline_exceeded", func(t *testing.T) {
154+
t.Parallel()
155+
156+
// This test verifies that the Do function immediately respects the context
157+
// deadline, even if the backoff duration is significantly longer than the
158+
// remaining context time. This is critical to ensure that the application
159+
// does not hang or wait unnecessarily when the context has already
160+
// expired.
161+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
162+
defer cancel()
163+
164+
// Backoff is longer than context timeout
165+
b := retry.NewConstant(20 * time.Millisecond)
166+
167+
start := time.Now()
168+
err := retry.Do(ctx, b, func(_ context.Context) error {
169+
return retry.RetryableError(fmt.Errorf("oops"))
170+
})
171+
if err == nil {
172+
t.Fatal("expected err")
173+
}
174+
if got, want := err, context.DeadlineExceeded; got != want {
175+
t.Errorf("expected %v to be %v", got, want)
176+
}
177+
178+
// Should have returned roughly around the timeout, not the backoff
179+
if got, want := time.Since(start), 15*time.Millisecond; got > want {
180+
t.Errorf("expected %s to be less than %s", got, want)
181+
}
182+
})
152183
}
153184

154185
func ExampleDo_simple() {

0 commit comments

Comments
 (0)