github.com/cenkalti/backoff/v4@v4.2.1/tries_test.go (about)

     1  package backoff
     2  
     3  import (
     4  	"errors"
     5  	"math/rand"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  func TestMaxTriesHappy(t *testing.T) {
    11  	r := rand.New(rand.NewSource(time.Now().UnixNano()))
    12  	max := 17 + r.Intn(13)
    13  	bo := WithMaxRetries(&ZeroBackOff{}, uint64(max))
    14  
    15  	// Load up the tries count, but reset should clear the record
    16  	for ix := 0; ix < max/2; ix++ {
    17  		bo.NextBackOff()
    18  	}
    19  	bo.Reset()
    20  
    21  	// Now fill the tries count all the way up
    22  	for ix := 0; ix < max; ix++ {
    23  		d := bo.NextBackOff()
    24  		if d == Stop {
    25  			t.Errorf("returned Stop on try %d", ix)
    26  		}
    27  	}
    28  
    29  	// We have now called the BackOff max number of times, we expect
    30  	// the next result to be Stop, even if we try it multiple times
    31  	for ix := 0; ix < 7; ix++ {
    32  		d := bo.NextBackOff()
    33  		if d != Stop {
    34  			t.Error("invalid next back off")
    35  		}
    36  	}
    37  
    38  	// Reset makes it all work again
    39  	bo.Reset()
    40  	d := bo.NextBackOff()
    41  	if d == Stop {
    42  		t.Error("returned Stop after reset")
    43  	}
    44  }
    45  
    46  // https://github.com/cenkalti/backoff/issues/80
    47  func TestMaxTriesZero(t *testing.T) {
    48  	var called int
    49  
    50  	b := WithMaxRetries(&ZeroBackOff{}, 0)
    51  
    52  	err := Retry(func() error {
    53  		called++
    54  		return errors.New("err")
    55  	}, b)
    56  
    57  	if err == nil {
    58  		t.Errorf("error expected, nil found")
    59  	}
    60  	if called != 1 {
    61  		t.Errorf("operation is called %d times", called)
    62  	}
    63  }