github.com/rudderlabs/rudder-go-kit@v0.30.0/stats/metric/counter_test.go (about)

     1  package metric
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  	"testing"
     7  )
     8  
     9  func TestCounterAdd(t *testing.T) {
    10  	counter := NewCounter()
    11  	counter.Inc()
    12  	if expected, got := 1.0, counter.Value(); expected != got {
    13  		t.Errorf("Expected %f, got %f.", expected, got)
    14  	}
    15  	counter.Add(42)
    16  	if expected, got := 43.0, counter.Value(); expected != got {
    17  		t.Errorf("Expected %f, got %f.", expected, got)
    18  	}
    19  
    20  	counter.Add(24.42)
    21  	if expected, got := 67.42, counter.Value(); expected != got {
    22  		t.Errorf("Expected %f, got %f.", expected, got)
    23  	}
    24  
    25  	if expected, got := "counter cannot decrease in value", decreaseCounter(counter).Error(); expected != got {
    26  		t.Errorf("Expected error %q, got %q.", expected, got)
    27  	}
    28  }
    29  
    30  func TestCounterAddConcurrently(t *testing.T) {
    31  	const concurrency = 1000
    32  	counter := NewCounter()
    33  	var wg sync.WaitGroup
    34  	wg.Add(concurrency)
    35  	for i := 0; i < concurrency; i++ {
    36  		go func() {
    37  			counter.Inc()
    38  			wg.Done()
    39  		}()
    40  	}
    41  	wg.Wait()
    42  	if expected, got := float64(concurrency), counter.Value(); expected != got {
    43  		t.Errorf("Expected %f, got %f.", expected, got)
    44  	}
    45  }
    46  
    47  func decreaseCounter(c Counter) (err error) {
    48  	defer func() {
    49  		if e := recover(); e != nil {
    50  			err = fmt.Errorf("%v", e)
    51  		}
    52  	}()
    53  	c.Add(-1)
    54  	return nil
    55  }