github.com/muhammadn/cortex@v1.9.1-0.20220510110439-46bb7000d03d/pkg/util/math/rate_test.go (about) 1 package math 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/stretchr/testify/require" 8 ) 9 10 func TestRate(t *testing.T) { 11 ticks := []struct { 12 events int 13 want float64 14 }{ 15 {60, 1}, 16 {30, 0.9}, 17 {0, 0.72}, 18 {60, 0.776}, 19 {0, 0.6208}, 20 {0, 0.49664}, 21 {0, 0.397312}, 22 {0, 0.3178496}, 23 {0, 0.25427968}, 24 {0, 0.203423744}, 25 {0, 0.1627389952}, 26 } 27 r := NewEWMARate(0.2, time.Minute) 28 29 for _, tick := range ticks { 30 for e := 0; e < tick.events; e++ { 31 r.Inc() 32 } 33 r.Tick() 34 // We cannot do double comparison, because double operations on different 35 // platforms may actually produce results that differ slightly. 36 // There are multiple issues about this in Go's github, eg: 18354 or 20319. 37 require.InDelta(t, tick.want, r.Rate(), 0.0000000001, "unexpected rate") 38 } 39 40 r = NewEWMARate(0.2, time.Minute) 41 42 for _, tick := range ticks { 43 r.Add(int64(tick.events)) 44 r.Tick() 45 require.InDelta(t, tick.want, r.Rate(), 0.0000000001, "unexpected rate") 46 } 47 }