gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/common/metrics/gauge_test.go (about)

     1  // Copyright 2018 The aquachain Authors
     2  // This file is part of the aquachain library.
     3  //
     4  // The aquachain library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The aquachain library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the aquachain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package metrics
    18  
    19  import (
    20  	"fmt"
    21  	"testing"
    22  )
    23  
    24  func BenchmarkGuage(b *testing.B) {
    25  	g := NewGauge()
    26  	b.ResetTimer()
    27  	for i := 0; i < b.N; i++ {
    28  		g.Update(int64(i))
    29  	}
    30  }
    31  
    32  func TestGauge(t *testing.T) {
    33  	g := NewGauge()
    34  	g.Update(int64(47))
    35  	if v := g.Value(); 47 != v {
    36  		t.Errorf("g.Value(): 47 != %v\n", v)
    37  	}
    38  }
    39  
    40  func TestGaugeSnapshot(t *testing.T) {
    41  	g := NewGauge()
    42  	g.Update(int64(47))
    43  	snapshot := g.Snapshot()
    44  	g.Update(int64(0))
    45  	if v := snapshot.Value(); 47 != v {
    46  		t.Errorf("g.Value(): 47 != %v\n", v)
    47  	}
    48  }
    49  
    50  func TestGetOrRegisterGauge(t *testing.T) {
    51  	r := NewRegistry()
    52  	NewRegisteredGauge("foo", r).Update(47)
    53  	if g := GetOrRegisterGauge("foo", r); 47 != g.Value() {
    54  		t.Fatal(g)
    55  	}
    56  }
    57  
    58  func TestFunctionalGauge(t *testing.T) {
    59  	var counter int64
    60  	fg := NewFunctionalGauge(func() int64 {
    61  		counter++
    62  		return counter
    63  	})
    64  	fg.Value()
    65  	fg.Value()
    66  	if counter != 2 {
    67  		t.Error("counter != 2")
    68  	}
    69  }
    70  
    71  func TestGetOrRegisterFunctionalGauge(t *testing.T) {
    72  	r := NewRegistry()
    73  	NewRegisteredFunctionalGauge("foo", r, func() int64 { return 47 })
    74  	if g := GetOrRegisterGauge("foo", r); 47 != g.Value() {
    75  		t.Fatal(g)
    76  	}
    77  }
    78  
    79  func ExampleGetOrRegisterGauge() {
    80  	m := "server.bytes_sent"
    81  	g := GetOrRegisterGauge(m, nil)
    82  	g.Update(47)
    83  	fmt.Println(g.Value()) // Output: 47
    84  }