github.com/aaabigfish/gopkg@v1.1.0/stat/counter/counter_test.go (about)

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