Skip to content

Commit

Permalink
fix(utils): fix bug and add test for retry method
Browse files Browse the repository at this point in the history
  • Loading branch information
wjf3121 committed Jul 27, 2024
1 parent f8aca50 commit f1042e1
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

# Output of the go coverage tool, specifically when used with LiteIDE
*.out
*.html

# Dependency directories (remove the comment below to include it)
# vendor/
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ lint-fix: check-golangci-lint ## Fix golang lint errors
./bin/golangci-lint run --config .golangci.yaml --fix

ut:
COLOR=ALWAYS go test -race -covermode=atomic -coverprofile=coverage.out -tags ut ./...
COLOR=ALWAYS go test -race -covermode=atomic -coverprofile=coverage.out ./...
go tool cover -html coverage.out -o coverage.html

check-diff:
Expand Down
2 changes: 1 addition & 1 deletion pkg/utils/wait/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
func RetryWithInterval(ctx context.Context, times int, interval time.Duration, do func(context.Context) error) error {
times = max(times, 0)
var err error
for i := 0; i < (times + 1); i++ {
for i := 0; i < times; i++ {
err = do(ctx)
if err == nil {
return nil
Expand Down
55 changes: 55 additions & 0 deletions pkg/utils/wait/retry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package wait

import (
"context"
"fmt"
"testing"
)

func doSuccessOnNth(n int) func(context.Context) error {
count := 0
return func(context.Context) error {
count = count + 1
if count == n {
return nil
}
return fmt.Errorf("failed on %vth try", count)
}
}

func TestRetryWithInterval(t *testing.T) {
tests := map[string]struct {
do func(context.Context) error
retry int
expectErr bool
}{
"success wtih no retry on first try": {
do: doSuccessOnNth(1),
expectErr: false,
},
"success on retry": {
do: doSuccessOnNth(2),
retry: 2,
expectErr: false,
},
"fail with no retry": {
do: doSuccessOnNth(2),
expectErr: true,
},
"fail with retry": {
do: doSuccessOnNth(3),
retry: 1,
expectErr: true,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
test := test
t.Parallel()
err := RetryWithInterval(context.Background(), test.retry, 0, test.do)
if (err != nil) != test.expectErr {
t.Errorf("expectErr: %v, got %v", test.expectErr, err)
}
})
}
}

0 comments on commit f1042e1

Please sign in to comment.