github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/retry/retry_test.go (about)

     1  package retry
     2  
     3  import (
     4  	"errors"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestInvokeWithRetry(t *testing.T) {
    12  	cases := []struct {
    13  		name string
    14  		c    RetryConfig
    15  		f    RetriableFunc
    16  		err  error
    17  	}{
    18  		{
    19  			"Must fail with zero Count",
    20  			RetryConfig{
    21  				Count: 0,
    22  				Sleep: 0,
    23  			},
    24  			func(n RetryFuncArg) error { return nil },
    25  			errInvalidRetryCount,
    26  		},
    27  		{
    28  			"Must fail with zero Sleep",
    29  			RetryConfig{
    30  				Count: 1,
    31  				Sleep: 0,
    32  			},
    33  			func(n RetryFuncArg) error { return nil },
    34  			errInvalidSleepDuration,
    35  		},
    36  		{
    37  			"Retry is successful immediately",
    38  			RetryConfig{
    39  				Count: 1,
    40  				Sleep: time.Millisecond * 2,
    41  			},
    42  			func(n RetryFuncArg) error {
    43  				return nil
    44  			},
    45  			nil,
    46  		},
    47  		{
    48  			"Retry is successful after 5 attempts",
    49  			RetryConfig{
    50  				Count: 5,
    51  				Sleep: time.Millisecond * 1,
    52  			},
    53  			func(n RetryFuncArg) error {
    54  				if n.Total < 5 {
    55  					return errors.New("< 5")
    56  				}
    57  
    58  				return nil
    59  			},
    60  			nil,
    61  		},
    62  		{
    63  			"Retry is never successful",
    64  			RetryConfig{
    65  				Count: 10,
    66  				Sleep: time.Millisecond * 1,
    67  			},
    68  			func(n RetryFuncArg) error {
    69  				return errors.New("err")
    70  			},
    71  			errors.New("err"),
    72  		},
    73  	}
    74  
    75  	for _, test := range cases {
    76  		t.Run(test.name, func(t *testing.T) {
    77  			err := InvokeWithRetry(test.c, test.f)
    78  			if test.err == nil {
    79  				assert.Nil(t, err)
    80  			} else {
    81  				assert.Equal(t, test.err.Error(), err.Error())
    82  			}
    83  		})
    84  	}
    85  }