github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/utils/timeutil/math_test.go (about)

     1  package timeutil
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  func TestAddJitter(t *testing.T) {
    11  	for _, j := range []float64{0.1, 0.2, 0.3, 0.5, 0.7} {
    12  		for i := 0; i < 100; i++ {
    13  			d := time.Second
    14  			_min := time.Duration(float64(d) * (1 - j))
    15  			_max := time.Duration(float64(d) * (1 + j))
    16  			got := AddJitter(d, j)
    17  			assert.Truef(t, got >= _min && got < _max,
    18  				"j= %v, d= %v, min= %v, max= %v, got= %v", j, d, _min, _max, got)
    19  		}
    20  	}
    21  }
    22  
    23  func TestBackoff(t *testing.T) {
    24  	got1, j1 := Backoff(10*time.Second, 0, 0.1)
    25  	assert.Equal(t, 20*time.Second, got1)
    26  	assert.True(t, j1 >= 18*time.Second && j1 < 22*time.Second)
    27  
    28  	got2, j2 := Backoff(20*time.Second, 30*time.Second, 0.1)
    29  	assert.Equal(t, 30*time.Second, got2)
    30  	assert.True(t, j2 >= 27*time.Second && j2 < 33*time.Second)
    31  }