github.com/anycable/anycable-go@v1.5.1/metrics/metrics_test.go (about)

     1  package metrics
     2  
     3  import (
     4  	"log/slog"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  func TestMetricsSnapshot(t *testing.T) {
    11  	m := NewMetrics(nil, 10, slog.Default())
    12  
    13  	m.RegisterCounter("test_count", "")
    14  	m.RegisterGauge("test_gauge", "")
    15  
    16  	for i := 0; i < 1000; i++ {
    17  		m.Counter("test_count").Inc()
    18  	}
    19  
    20  	m.Gauge("test_gauge").Set(123)
    21  
    22  	m.rotate()
    23  
    24  	assert.Equal(t, uint64(1000), m.IntervalSnapshot()["test_count"])
    25  	assert.Equal(t, uint64(123), m.IntervalSnapshot()["test_gauge"])
    26  
    27  	m.Counter("test_count").Inc()
    28  
    29  	m.rotate()
    30  
    31  	assert.Equal(t, uint64(1), m.IntervalSnapshot()["test_count"])
    32  	assert.Equal(t, uint64(123), m.IntervalSnapshot()["test_gauge"])
    33  }
    34  
    35  func TestMetrics_EachGauge(t *testing.T) {
    36  	m := NewMetrics(nil, 10, slog.Default())
    37  
    38  	m.RegisterGauge("test_gauge", "First")
    39  	m.RegisterGauge("test_gauge_2", "Second")
    40  
    41  	m.Gauge("test_gauge").Set(123)
    42  	m.Gauge("test_gauge_2").Set(321)
    43  
    44  	m.EachGauge(func(gauge *Gauge) {
    45  		switch gauge.Name() {
    46  		case "test_gauge":
    47  			{
    48  				assert.Equal(t, uint64(123), gauge.Value())
    49  			}
    50  		case "test_gauge_2":
    51  			{
    52  				assert.Equal(t, uint64(321), gauge.Value())
    53  			}
    54  		default:
    55  			{
    56  				t.Errorf("Unknown gauge: %s", gauge.Name())
    57  			}
    58  		}
    59  	})
    60  }
    61  
    62  func TestMetrics_EachCounter(t *testing.T) {
    63  	m := NewMetrics(nil, 10, slog.Default())
    64  
    65  	m.RegisterCounter("test_counter", "First")
    66  	m.RegisterCounter("test_counter_2", "Second")
    67  
    68  	m.Counter("test_counter").Inc()
    69  	m.Counter("test_counter_2").Add(3)
    70  
    71  	m.EachCounter(func(counter *Counter) {
    72  		switch counter.Name() {
    73  		case "test_counter":
    74  			{
    75  				assert.Equal(t, uint64(1), counter.Value())
    76  			}
    77  		case "test_counter_2":
    78  			{
    79  				assert.Equal(t, uint64(3), counter.Value())
    80  			}
    81  		default:
    82  			{
    83  				t.Errorf("Unknown counter: %s", counter.Name())
    84  			}
    85  		}
    86  	})
    87  }