github.com/lingyao2333/mo-zero@v1.4.1/core/mathx/unstable_test.go (about) 1 package mathx 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 func TestUnstable_AroundDuration(t *testing.T) { 11 unstable := NewUnstable(0.05) 12 for i := 0; i < 1000; i++ { 13 val := unstable.AroundDuration(time.Second) 14 assert.True(t, float64(time.Second)*0.95 <= float64(val)) 15 assert.True(t, float64(val) <= float64(time.Second)*1.05) 16 } 17 } 18 19 func TestUnstable_AroundInt(t *testing.T) { 20 const target = 10000 21 unstable := NewUnstable(0.05) 22 for i := 0; i < 1000; i++ { 23 val := unstable.AroundInt(target) 24 assert.True(t, float64(target)*0.95 <= float64(val)) 25 assert.True(t, float64(val) <= float64(target)*1.05) 26 } 27 } 28 29 func TestUnstable_AroundIntLarge(t *testing.T) { 30 const target int64 = 10000 31 unstable := NewUnstable(5) 32 for i := 0; i < 1000; i++ { 33 val := unstable.AroundInt(target) 34 assert.True(t, 0 <= val) 35 assert.True(t, val <= 2*target) 36 } 37 } 38 39 func TestUnstable_AroundIntNegative(t *testing.T) { 40 const target int64 = 10000 41 unstable := NewUnstable(-0.05) 42 for i := 0; i < 1000; i++ { 43 val := unstable.AroundInt(target) 44 assert.Equal(t, target, val) 45 } 46 } 47 48 func TestUnstable_Distribution(t *testing.T) { 49 const ( 50 seconds = 10000 51 total = 10000 52 ) 53 54 m := make(map[int]int) 55 expiry := NewUnstable(0.05) 56 for i := 0; i < total; i++ { 57 val := int(expiry.AroundInt(seconds)) 58 m[val]++ 59 } 60 61 _, ok := m[0] 62 assert.False(t, ok) 63 64 mi := make(map[interface{}]int, len(m)) 65 for k, v := range m { 66 mi[k] = v 67 } 68 entropy := CalcEntropy(mi) 69 assert.True(t, len(m) > 1) 70 assert.True(t, entropy > 0.95) 71 }