forked from VictoriaMetrics/metrics
-
Notifications
You must be signed in to change notification settings - Fork 1
/
counter_test.go
76 lines (69 loc) · 1.57 KB
/
counter_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
75
76
package metrics
import (
"fmt"
"testing"
)
func TestCounterSerial(t *testing.T) {
name := "CounterSerial"
c := NewCounter(name)
c.Inc()
if n := c.Get(); n != 1 {
t.Fatalf("unexpected counter value; got %d; want 1", n)
}
c.Set(123)
if n := c.Get(); n != 123 {
t.Fatalf("unexpected counter value; got %d; want 123", n)
}
c.Dec()
if n := c.Get(); n != 122 {
t.Fatalf("unexpected counter value; got %d; want 122", n)
}
c.Add(3)
if n := c.Get(); n != 125 {
t.Fatalf("unexpected counter value; got %d; want 125", n)
}
// Verify MarshalTo
testMarshalTo(t, c, "foobar", "foobar 125\n")
}
func TestCounterConcurrent(t *testing.T) {
name := "CounterConcurrent"
c := NewCounter(name)
err := testConcurrent(func() error {
nPrev := c.Get()
for i := 0; i < 10; i++ {
c.Inc()
if n := c.Get(); n <= nPrev {
return fmt.Errorf("counter value must be greater than %d; got %d", nPrev, n)
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
func TestGetOrCreateCounterSerial(t *testing.T) {
name := "GetOrCreateCounterSerial"
if err := testGetOrCreateCounter(name); err != nil {
t.Fatal(err)
}
}
func TestGetOrCreateCounterConcurrent(t *testing.T) {
name := "GetOrCreateCounterConcurrent"
err := testConcurrent(func() error {
return testGetOrCreateCounter(name)
})
if err != nil {
t.Fatal(err)
}
}
func testGetOrCreateCounter(name string) error {
c1 := GetOrCreateCounter(name)
for i := 0; i < 10; i++ {
c2 := GetOrCreateCounter(name)
if c1 != c2 {
return fmt.Errorf("unexpected counter returned; got %p; want %p", c2, c1)
}
}
return nil
}