PageRenderTime 70ms CodeModel.GetById 43ms app.highlight 5ms RepoModel.GetById 14ms app.codeStats 0ms

/gauge_test.go

http://github.com/rcrowley/go-metrics
Go | 87 lines | 77 code | 9 blank | 1 comment | 12 complexity | f3c18f0cca51e3609b6af18c2776d4fd MD5 | raw file
 1package metrics
 2
 3import (
 4	"fmt"
 5	"math/rand"
 6	"sync"
 7	"testing"
 8	"time"
 9)
10
11func BenchmarkGuage(b *testing.B) {
12	g := NewGauge()
13	b.ResetTimer()
14	for i := 0; i < b.N; i++ {
15		g.Update(int64(i))
16	}
17}
18
19// exercise race detector
20func TestGaugeConcurrency(t *testing.T) {
21	rand.Seed(time.Now().Unix())
22	g := NewGauge()
23	wg := &sync.WaitGroup{}
24	reps := 100
25	for i := 0; i < reps; i++ {
26		wg.Add(1)
27		go func(g Gauge, wg *sync.WaitGroup) {
28			g.Update(rand.Int63())
29			wg.Done()
30		}(g, wg)
31	}
32	wg.Wait()
33}
34
35func TestGauge(t *testing.T) {
36	g := NewGauge()
37	g.Update(int64(47))
38	if v := g.Value(); 47 != v {
39		t.Errorf("g.Value(): 47 != %v\n", v)
40	}
41}
42
43func TestGaugeSnapshot(t *testing.T) {
44	g := NewGauge()
45	g.Update(int64(47))
46	snapshot := g.Snapshot()
47	g.Update(int64(0))
48	if v := snapshot.Value(); 47 != v {
49		t.Errorf("g.Value(): 47 != %v\n", v)
50	}
51}
52
53func TestGetOrRegisterGauge(t *testing.T) {
54	r := NewRegistry()
55	NewRegisteredGauge("foo", r).Update(47)
56	if g := GetOrRegisterGauge("foo", r); 47 != g.Value() {
57		t.Fatal(g)
58	}
59}
60
61func TestFunctionalGauge(t *testing.T) {
62	var counter int64
63	fg := NewFunctionalGauge(func() int64 {
64		counter++
65		return counter
66	})
67	fg.Value()
68	fg.Value()
69	if counter != 2 {
70		t.Error("counter != 2")
71	}
72}
73
74func TestGetOrRegisterFunctionalGauge(t *testing.T) {
75	r := NewRegistry()
76	NewRegisteredFunctionalGauge("foo", r, func() int64 { return 47 })
77	if g := GetOrRegisterGauge("foo", r); 47 != g.Value() {
78		t.Fatal(g)
79	}
80}
81
82func ExampleGetOrRegisterGauge() {
83	m := "server.bytes_sent"
84	g := GetOrRegisterGauge(m, nil)
85	g.Update(47)
86	fmt.Println(g.Value()) // Output: 47
87}