vitess.io/vitess@v0.16.2/go/vt/vtadmin/internal/backoff/backoff_test.go (about)

     1  /*
     2  Copyright 2022 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package backoff
    18  
    19  import (
    20  	"testing"
    21  	"time"
    22  
    23  	"github.com/stretchr/testify/assert"
    24  	grpcbackoff "google.golang.org/grpc/backoff"
    25  )
    26  
    27  func TestExponentialBackoff(t *testing.T) {
    28  	t.Parallel()
    29  
    30  	tests := []struct {
    31  		name   string
    32  		cfg    grpcbackoff.Config
    33  		delays []time.Duration
    34  	}{
    35  		{
    36  			name: "",
    37  			cfg: grpcbackoff.Config{
    38  				BaseDelay:  time.Second,
    39  				Multiplier: 2,
    40  				Jitter:     0,
    41  				MaxDelay:   time.Second * 5,
    42  			},
    43  			delays: []time.Duration{
    44  				time.Second,
    45  				time.Second * 2,
    46  				time.Second * 4,
    47  				time.Second * 5, // multiplying exceeds max
    48  
    49  			},
    50  		},
    51  	}
    52  
    53  	for _, tt := range tests {
    54  		tt := tt
    55  		t.Run(tt.name, func(t *testing.T) {
    56  			t.Parallel()
    57  
    58  			exp := Get("exponential", tt.cfg)
    59  			for retry, expectedDelay := range tt.delays {
    60  				actualDelay := exp.Backoff(retry)
    61  				assert.Equal(t, expectedDelay, actualDelay, "incorrect backoff delay for retry count %v", retry)
    62  			}
    63  		})
    64  	}
    65  
    66  	t.Run("jitter never exceeds max delay", func(t *testing.T) {
    67  		t.Parallel()
    68  
    69  		exp := Get("exponential", grpcbackoff.Config{
    70  			BaseDelay:  time.Second,
    71  			Multiplier: 1,
    72  			Jitter:     2,
    73  			MaxDelay:   time.Second,
    74  		})
    75  		delays := []time.Duration{
    76  			time.Second,
    77  			time.Second,
    78  			time.Second,
    79  			time.Second,
    80  			time.Second,
    81  			time.Second,
    82  			time.Second,
    83  			time.Second, // you get the idea ...
    84  		}
    85  
    86  		for retry, expectedDelay := range delays {
    87  			actualDelay := exp.Backoff(retry)
    88  			assert.GreaterOrEqual(t, expectedDelay, actualDelay, "incorrect backoff delay for retry count %v", retry)
    89  		}
    90  	})
    91  }