github.com/weaviate/weaviate@v1.24.6/entities/interval/backoff_test.go (about)

     1  //                           _       _
     2  // __      _____  __ ___   ___  __ _| |_ ___
     3  // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
     4  //  \ V  V /  __/ (_| |\ V /| | (_| | ||  __/
     5  //   \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
     6  //
     7  //  Copyright © 2016 - 2024 Weaviate B.V. All rights reserved.
     8  //
     9  //  CONTACT: hello@weaviate.io
    10  //
    11  
    12  package interval
    13  
    14  import (
    15  	"sort"
    16  	"testing"
    17  	"time"
    18  
    19  	"github.com/stretchr/testify/assert"
    20  )
    21  
    22  func TestBackoffInterval(t *testing.T) {
    23  	t.Run("with default backoffs", func(t *testing.T) {
    24  		boff := NewBackoffTimer()
    25  
    26  		assert.Equal(t, boff.backoffs, defaultBackoffs)
    27  		assert.Zero(t, boff.backoffLevel)
    28  		assert.Zero(t, boff.lastInterval)
    29  		assert.Equal(t, time.Duration(0), boff.calculateInterval())
    30  		assert.True(t, boff.IntervalElapsed())
    31  
    32  		i := 1
    33  		for ; i < len(defaultBackoffs); i++ {
    34  			boff.IncreaseInterval()
    35  			assert.False(t, boff.IntervalElapsed())
    36  			assert.Equal(t, i, boff.backoffLevel)
    37  			assert.Equal(t, defaultBackoffs[i], boff.calculateInterval())
    38  		}
    39  
    40  		boff.IncreaseInterval()
    41  		assert.False(t, boff.IntervalElapsed())
    42  		assert.Equal(t, i, boff.backoffLevel)
    43  		assert.Equal(t, defaultBackoffs[len(defaultBackoffs)-1], boff.calculateInterval())
    44  	})
    45  
    46  	t.Run("with custom backoffs", func(t *testing.T) {
    47  		var (
    48  			durations = []time.Duration{time.Second, time.Nanosecond, time.Millisecond}
    49  			sorted    = make([]time.Duration, len(durations))
    50  		)
    51  
    52  		copy(sorted, durations)
    53  		sort.Slice(sorted, func(i, j int) bool {
    54  			return sorted[i] < sorted[j]
    55  		})
    56  
    57  		boff := NewBackoffTimer(durations...)
    58  		assert.Equal(t, boff.backoffs, sorted)
    59  		assert.True(t, boff.IntervalElapsed())
    60  		assert.Equal(t, sorted[0], boff.calculateInterval())
    61  
    62  		boff.IncreaseInterval()
    63  		time.Sleep(time.Millisecond)
    64  		assert.True(t, boff.IntervalElapsed())
    65  		assert.Equal(t, sorted[1], boff.calculateInterval())
    66  
    67  		boff.IncreaseInterval()
    68  		assert.False(t, boff.IntervalElapsed())
    69  		time.Sleep(time.Second)
    70  		assert.True(t, boff.IntervalElapsed())
    71  		assert.Equal(t, sorted[2], boff.calculateInterval())
    72  
    73  		boff.IncreaseInterval()
    74  		assert.False(t, boff.IntervalElapsed())
    75  		assert.False(t, boff.IntervalElapsed())
    76  		assert.Equal(t, sorted[len(sorted)-1], boff.calculateInterval())
    77  	})
    78  }