counter_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package metrics
  2. import "testing"
  3. func BenchmarkCounter(b *testing.B) {
  4. c := NewCounter()
  5. b.ResetTimer()
  6. for i := 0; i < b.N; i++ {
  7. c.Inc(1)
  8. }
  9. }
  10. func TestCounterClear(t *testing.T) {
  11. c := NewCounter()
  12. c.Inc(1)
  13. c.Clear()
  14. if count := c.Count(); 0 != count {
  15. t.Errorf("c.Count(): 0 != %v\n", count)
  16. }
  17. }
  18. func TestCounterDec1(t *testing.T) {
  19. c := NewCounter()
  20. c.Dec(1)
  21. if count := c.Count(); -1 != count {
  22. t.Errorf("c.Count(): -1 != %v\n", count)
  23. }
  24. }
  25. func TestCounterDec2(t *testing.T) {
  26. c := NewCounter()
  27. c.Dec(2)
  28. if count := c.Count(); -2 != count {
  29. t.Errorf("c.Count(): -2 != %v\n", count)
  30. }
  31. }
  32. func TestCounterInc1(t *testing.T) {
  33. c := NewCounter()
  34. c.Inc(1)
  35. if count := c.Count(); 1 != count {
  36. t.Errorf("c.Count(): 1 != %v\n", count)
  37. }
  38. }
  39. func TestCounterInc2(t *testing.T) {
  40. c := NewCounter()
  41. c.Inc(2)
  42. if count := c.Count(); 2 != count {
  43. t.Errorf("c.Count(): 2 != %v\n", count)
  44. }
  45. }
  46. func TestCounterSnapshot(t *testing.T) {
  47. c := NewCounter()
  48. c.Inc(1)
  49. snapshot := c.Snapshot()
  50. c.Inc(1)
  51. if count := snapshot.Count(); 1 != count {
  52. t.Errorf("c.Count(): 1 != %v\n", count)
  53. }
  54. }
  55. func TestCounterZero(t *testing.T) {
  56. c := NewCounter()
  57. if count := c.Count(); 0 != count {
  58. t.Errorf("c.Count(): 0 != %v\n", count)
  59. }
  60. }
  61. func TestGetOrRegisterCounter(t *testing.T) {
  62. r := NewRegistry()
  63. NewRegisteredCounter("foo", r).Inc(47)
  64. if c := GetOrRegisterCounter("foo", r); 47 != c.Count() {
  65. t.Fatal(c)
  66. }
  67. }