github.com/songzhibin97/gkit@v1.2.13/internal/stat/rolling_policy_test.go (about) 1 package stat 2 3 import ( 4 "fmt" 5 "math/rand" 6 "testing" 7 "time" 8 ) 9 10 func GetRollingPolicy() *RollingPolicy { 11 w := NewWindow(10) 12 return NewRollingPolicy(w, 300*time.Millisecond) 13 } 14 15 func Handler(t *testing.T, table []map[string][]int) { 16 for _, hm := range table { 17 var totalTs, lastOffset int 18 offsetAndPoints := hm["offsetAndPoints"] 19 timeSleep := hm["timeSleep"] 20 policy := GetRollingPolicy() 21 for i, n := range timeSleep { 22 totalTs += n 23 time.Sleep(time.Duration(n) * time.Millisecond) 24 policy.Add(1) 25 offset, points := offsetAndPoints[2*i], offsetAndPoints[2*i+1] 26 27 if int(policy.window.window[offset].Points[0]) != points { 28 t.Errorf("error, time since last append: %vms, last offset: %v", totalTs, lastOffset) 29 } 30 lastOffset = offset 31 } 32 } 33 } 34 35 func TestRollingPolicy_Add(t *testing.T) { 36 rand.Seed(time.Now().Unix()) 37 38 // test add after 400ms and 601ms relative to the policy created time 39 policy := GetRollingPolicy() 40 time.Sleep(400 * time.Millisecond) 41 policy.Add(1) 42 time.Sleep(201 * time.Millisecond) 43 policy.Add(1) 44 for _, b := range policy.window.window { 45 fmt.Println(b.Points) 46 } 47 if int(policy.window.window[1].Points[0]) != 1 { 48 t.Errorf("error, time since last append: %vms, last offset: %v", 300, 0) 49 } 50 if int(policy.window.window[2].Points[0]) != 1 { 51 t.Errorf("error, time since last append: %vms, last offset: %v", 301, 0) 52 } 53 54 // test func timespan return real span 55 table := []map[string][]int{ 56 { 57 "timeSleep": []int{294, 3200}, 58 "offsetAndPoints": []int{0, 1, 0, 1}, 59 }, 60 { 61 "timeSleep": []int{305, 3200, 6400}, 62 "offsetAndPoints": []int{1, 1, 1, 1, 1, 1}, 63 }, 64 } 65 66 Handler(t, table) 67 }