Skip to content

Commit

Permalink
Merge pull request #28 from hurbcom/feat/retry-cancellation-pnr
Browse files Browse the repository at this point in the history
Feat/retry cancellation pnr
  • Loading branch information
RafaelBarbosa09 authored Jul 13, 2022
2 parents 13650ff + 4d09cfc commit 63c47d6
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 0 deletions.
25 changes: 25 additions & 0 deletions lib/retry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package lib

import (
"context"
"errors"
"time"
)

type RetryOptions struct {
RetriesCount int
RetriesInterval time.Duration
}

func WithRetries(ctx context.Context, retryFn func() error, options RetryOptions) error {
for i := 0; i < options.RetriesCount; i++ {
if err := ctx.Err(); err != nil {
return err
}
if err := retryFn(); err == nil {
return nil
}
time.Sleep(options.RetriesInterval)
}
return errors.New("maximum number of retries exceeded")
}
73 changes: 73 additions & 0 deletions lib/retry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package lib

import (
"context"
"errors"
"testing"
)

func TestWithRetries(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()

type args struct {
ctx context.Context
retryFn func() error
options RetryOptions
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "should return nil if the retry parameter function does not return an error",
args: args{
ctx: context.TODO(),
retryFn: func() error {
return nil
},
options: RetryOptions{
RetriesCount: 3,
RetriesInterval: 2,
},
},
wantErr: false,
},
{
name: "should return an error if the maximum retries is exceeded",
args: args{
ctx: context.TODO(),
retryFn: func() error {
return errors.New("error")
},
options: RetryOptions{
RetriesCount: 3,
RetriesInterval: 2,
},
},
wantErr: true,
},
{
name: "should return an error if the context is cancelled",
args: args{
ctx: ctx,
retryFn: func() error {
return nil
},
options: RetryOptions{
RetriesCount: 3,
RetriesInterval: 2,
},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := WithRetries(tt.args.ctx, tt.args.retryFn, tt.args.options); (err != nil) != tt.wantErr {
t.Errorf("WithRetries() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}

0 comments on commit 63c47d6

Please sign in to comment.