counter_test.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package counter
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestGaugeCounter(t *testing.T) {
  8. key := "test"
  9. g := &Group{
  10. New: func() Counter {
  11. return NewGauge()
  12. },
  13. }
  14. g.Add(key, 1)
  15. g.Add(key, 2)
  16. g.Add(key, 3)
  17. g.Add(key, -1)
  18. assert.Equal(t, g.Value(key), int64(5))
  19. g.Reset(key)
  20. assert.Equal(t, g.Value(key), int64(0))
  21. }
  22. func TestRollingCounter(t *testing.T) {
  23. key := "test"
  24. g := &Group{
  25. New: func() Counter {
  26. return NewRolling(time.Second, 10)
  27. },
  28. }
  29. t.Run("add_key_b1", func(t *testing.T) {
  30. g.Add(key, 1)
  31. assert.Equal(t, g.Value(key), int64(1))
  32. })
  33. time.Sleep(time.Millisecond * 110)
  34. t.Run("add_key_b2", func(t *testing.T) {
  35. g.Add(key, 1)
  36. assert.Equal(t, g.Value(key), int64(2))
  37. })
  38. time.Sleep(time.Millisecond * 900) // expire one bucket, 110 + 900
  39. t.Run("expire_b1", func(t *testing.T) {
  40. assert.Equal(t, g.Value(key), int64(1))
  41. g.Add(key, 1)
  42. assert.Equal(t, g.Value(key), int64(2)) // expire one bucket
  43. })
  44. time.Sleep(time.Millisecond * 1100)
  45. t.Run("expire_all", func(t *testing.T) {
  46. assert.Equal(t, g.Value(key), int64(0))
  47. })
  48. t.Run("reset", func(t *testing.T) {
  49. g.Reset(key)
  50. assert.Equal(t, g.Value(key), int64(0))
  51. })
  52. }