Skip to content

Commit

Permalink
fix context behaviour
Browse files Browse the repository at this point in the history
  • Loading branch information
Jan Seidl committed Oct 9, 2020
1 parent fb576e6 commit 7b7365c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 10 deletions.
5 changes: 5 additions & 0 deletions retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,10 @@ func Do(retryableFunc RetryableFunc, opts ...Option) error {
opt(config)
}

if err := config.context.Err(); err != nil {
return err
}

var errorLog Error
if !config.lastErrorOnly {
errorLog = make(Error, config.attempts)
Expand Down Expand Up @@ -138,6 +142,7 @@ func Do(retryableFunc RetryableFunc, opts ...Option) error {
select {
case <-time.After(delayTime):
case <-config.context.Done():
return config.context.Err()
}

} else {
Expand Down
44 changes: 34 additions & 10 deletions retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,14 +262,38 @@ func TestCombineDelay(t *testing.T) {
}

func TestContext(t *testing.T) {
start := time.Now()
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := Do(
func() error { return errors.New("test") },
Context(ctx),
)
dur := time.Since(start)
assert.Error(t, err)
assert.True(t, dur < time.Millisecond, "immediately cancellation")
t.Run("cancel before", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()

retrySum := 0
start := time.Now()
err := Do(
func() error { return errors.New("test") },
OnRetry(func(n uint, err error) { retrySum += 1 }),
Context(ctx),
)
dur := time.Since(start)
assert.Error(t, err)
assert.True(t, dur < DefaultDelay, "immediately cancellation")
assert.Equal(t, 0, retrySum, "called at most once")
})

t.Run("cancel in retry progress", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())

retrySum := 0
err := Do(
func() error { return errors.New("test") },
OnRetry(func(n uint, err error) {
retrySum += 1
if retrySum > 1 {
cancel()
}
}),
Context(ctx),
)
assert.Error(t, err)
assert.Equal(t, 2, retrySum, "called at most once")
})
}

0 comments on commit 7b7365c

Please sign in to comment.