test: add some missing test cases

This commit is contained in:
lilasxie 2024-05-27 13:34:27 +08:00
parent d1d9f34e51
commit 00450d862d
3 changed files with 98 additions and 2 deletions

View file

@ -25,9 +25,16 @@ func BenchmarkCounterFloat64Parallel(b *testing.B) {
} }
wg.Done() wg.Done()
}() }()
wg.Add(1)
go func() {
for i := 0; i < b.N; i++ {
c.Dec(1.0)
}
wg.Done()
}()
} }
wg.Wait() wg.Wait()
if have, want := c.Snapshot().Count(), 10.0*float64(b.N); have != want { if have, want := c.Snapshot().Count(), float64(0); have != want {
b.Fatalf("have %f want %f", have, want) b.Fatalf("have %f want %f", have, want)
} }
} }

View file

@ -1,6 +1,9 @@
package metrics package metrics
import "testing" import (
"sync"
"testing"
)
func BenchmarkCounter(b *testing.B) { func BenchmarkCounter(b *testing.B) {
c := NewCounter() c := NewCounter()
@ -10,6 +13,32 @@ func BenchmarkCounter(b *testing.B) {
} }
} }
func BenchmarkCounterParallel(b *testing.B) {
c := NewCounter()
b.ResetTimer()
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
for i := 0; i < b.N; i++ {
c.Inc(1)
}
wg.Done()
}()
wg.Add(1)
go func() {
for i := 0; i < b.N; i++ {
c.Dec(1)
}
wg.Done()
}()
}
wg.Wait()
if have, want := c.Snapshot().Count(), int64(0); have != want {
b.Fatalf("have %d want %d", have, want)
}
}
func TestCounterClear(t *testing.T) { func TestCounterClear(t *testing.T) {
c := NewCounter() c := NewCounter()
c.Inc(1) c.Inc(1)

View file

@ -1,6 +1,7 @@
package metrics package metrics
import ( import (
"sync"
"testing" "testing"
) )
@ -12,6 +13,65 @@ func BenchmarkGauge(b *testing.B) {
} }
} }
func BenchmarkGaugeIncDecParallel(b *testing.B) {
g := NewGauge()
b.ResetTimer()
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
for i := 0; i < b.N; i++ {
g.Inc(1)
}
wg.Done()
}()
wg.Add(1)
go func() {
for i := 0; i < b.N; i++ {
g.Dec(1)
}
wg.Done()
}()
}
wg.Wait()
if have, want := g.Snapshot().Value(), int64(0); have != want {
b.Fatalf("have %d want %d", have, want)
}
}
func TestGaugeUpdateIfGt(t *testing.T) {
g := NewGauge()
g.Update(int64(47))
g.UpdateIfGt(int64(0))
if v := g.Snapshot().Value(); v != 47 {
t.Errorf("g.Value(): 47 != %v\n", v)
}
g.UpdateIfGt(int64(58))
if v := g.Snapshot().Value(); v != 58 {
t.Errorf("g.Value(): 58 != %v\n", v)
}
}
func TestGaugeUpdateIfGtParallel(t *testing.T) {
g := NewGauge()
g.Update(int64(45))
if v := g.Snapshot().Value(); v != 45 {
t.Errorf("g.Value(): 45 != %v\n", v)
}
var wg sync.WaitGroup
for i := 50; i >= 40; i-- {
wg.Add(1)
go func(i int) {
g.UpdateIfGt(int64(i))
wg.Done()
}(i)
}
wg.Wait()
if v := g.Snapshot().Value(); v != 50 {
t.Errorf("g.Value(): 50 != %v\n", v)
}
}
func TestGaugeSnapshot(t *testing.T) { func TestGaugeSnapshot(t *testing.T) {
g := NewGauge() g := NewGauge()
g.Update(int64(47)) g.Update(int64(47))