From 3fbc0c0e6169041197329f2c40cd351e87964a96 Mon Sep 17 00:00:00 2001 From: uccs <1500846601@qq.com> Date: Sat, 28 Dec 2024 21:48:55 +0800 Subject: [PATCH] fix: the Retry function throws an error when the opts parameter is passed as nil --- retry.go | 4 +++- retry_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/retry.go b/retry.go index ceda363..1bded12 100644 --- a/retry.go +++ b/retry.go @@ -75,7 +75,9 @@ func Retry[T any](ctx context.Context, operation Operation[T], opts ...RetryOpti // Apply user-provided options to the default settings. for _, opt := range opts { - opt(args) + if opt != nil { + opt(args) + } } defer args.Timer.Stop() diff --git a/retry_test.go b/retry_test.go index 28e3a31..22c7519 100644 --- a/retry_test.go +++ b/retry_test.go @@ -55,6 +55,33 @@ func TestRetry(t *testing.T) { } } +func TestRetryOptionIsNil(t *testing.T) { + const successOn = 3 + var i = 0 + + // This function is successful on "successOn" calls. + f := func() (bool, error) { + i++ + log.Printf("function is called %d. time\n", i) + + if i == successOn { + log.Println("OK") + return true, nil + } + + log.Println("error") + return false, errors.New("error") + } + + _, err := Retry(context.Background(), f, nil, nil, nil) + if err != nil { + t.Errorf("unexpected error: %s", err.Error()) + } + if i != successOn { + t.Errorf("invalid number of retries: %d", i) + } +} + func TestRetryWithData(t *testing.T) { const successOn = 3 var i = 0