-
Notifications
You must be signed in to change notification settings - Fork 0
/
gauge_test.go
74 lines (65 loc) · 1.71 KB
/
gauge_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package metric
import (
"sync"
"testing"
"time"
)
func TestGaugeAddSub(t *testing.T) {
gauge := NewGauge()
gauge.Inc()
if expected, got := 1.0, gauge.Value(); expected != got {
t.Errorf("Expected %f, got %f.", expected, got)
}
gauge.Add(42)
if expected, got := 43.0, gauge.Value(); expected != got {
t.Errorf("Expected %f, got %f.", expected, got)
}
gauge.Add(24.42)
if expected, got := 67.42, gauge.Value(); expected != got {
t.Errorf("Expected %f, got %f.", expected, got)
}
gauge.Dec()
if expected, got := 66.42, gauge.Value(); expected != got {
t.Errorf("Expected error %f, got %f.", expected, got)
}
gauge.Sub(24.42)
if expected, got := 42.0, gauge.Value(); expected != got {
t.Errorf("Expected error %f, got %f.", expected, got)
}
}
func TestGaugeSetGetTime(t *testing.T) {
gauge := NewGauge().(*gauge)
now := time.Now()
f := func() time.Time { return now }
gauge.now = f
gauge.SetToCurrentTime()
if expected, got := now.Round(1*time.Millisecond), gauge.ValueAsTime().Round(1*time.Millisecond); expected != got {
t.Errorf("Expected error %s, got %s.", expected, got)
}
}
func TestGaugeAddSubConcurrently(t *testing.T) {
const concurrency = 1000
const addAmt = 10
const subAmt = 2
gauge := NewGauge()
var wg sync.WaitGroup
wg.Add(concurrency)
for i := 0; i < concurrency/2; i++ {
go func() {
gauge.Add(addAmt)
gauge.Dec() // for every dec we do an equivalent sub below (*)
wg.Done()
}()
}
for i := 0; i < concurrency/2; i++ {
go func() {
gauge.Inc()
gauge.Sub(subAmt) // (*)
wg.Done()
}()
}
wg.Wait()
if expected, got := float64(addAmt*(concurrency/2)-subAmt*(concurrency/2)), gauge.Value(); expected != got {
t.Errorf("Expected %f, got %f.", expected, got)
}
}