summary_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package summary
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestSummaryMinInterval(t *testing.T) {
  8. count := New(time.Second/2, 10)
  9. tk1 := time.NewTicker(5 * time.Millisecond)
  10. defer tk1.Stop()
  11. for i := 0; i < 100; i++ {
  12. <-tk1.C
  13. count.Add(2)
  14. }
  15. v, c := count.Value()
  16. t.Logf("count value: %d, %d\n", v, c)
  17. // 10% of error when bucket is 10
  18. if v < 190 || v > 210 {
  19. t.Errorf("expect value in [90-110] get %d", v)
  20. }
  21. // 10% of error when bucket is 10
  22. if c < 90 || c > 110 {
  23. t.Errorf("expect value in [90-110] get %d", v)
  24. }
  25. }
  26. func TestSummary(t *testing.T) {
  27. s := New(time.Second, 10)
  28. t.Run("add", func(t *testing.T) {
  29. s.Add(1)
  30. v, c := s.Value()
  31. assert.Equal(t, v, int64(1))
  32. assert.Equal(t, c, int64(1))
  33. })
  34. time.Sleep(time.Millisecond * 110)
  35. t.Run("add2", func(t *testing.T) {
  36. s.Add(1)
  37. v, c := s.Value()
  38. assert.Equal(t, v, int64(2))
  39. assert.Equal(t, c, int64(2))
  40. })
  41. time.Sleep(time.Millisecond * 900) // expire one bucket, 110 + 900
  42. t.Run("expire", func(t *testing.T) {
  43. v, c := s.Value()
  44. assert.Equal(t, v, int64(1))
  45. assert.Equal(t, c, int64(1))
  46. s.Add(1)
  47. v, c = s.Value()
  48. assert.Equal(t, v, int64(2)) // expire one bucket
  49. assert.Equal(t, c, int64(2)) // expire one bucket
  50. })
  51. time.Sleep(time.Millisecond * 1100)
  52. t.Run("expire_all", func(t *testing.T) {
  53. v, c := s.Value()
  54. assert.Equal(t, v, int64(0))
  55. assert.Equal(t, c, int64(0))
  56. })
  57. t.Run("reset", func(t *testing.T) {
  58. s.Reset()
  59. v, c := s.Value()
  60. assert.Equal(t, v, int64(0))
  61. assert.Equal(t, c, int64(0))
  62. })
  63. }