bitsetratio_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package aggregator
  2. import (
  3. "math"
  4. "reflect"
  5. "testing"
  6. "time"
  7. )
  8. func TestBitSetRatioAggregator_Value(t *testing.T) {
  9. time1 := time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC)
  10. time2 := time.Date(1, 1, 1, 0, 1, 0, 0, time.UTC)
  11. time3 := time.Date(1, 1, 1, 0, 2, 0, 0, time.UTC)
  12. time4 := time.Date(1, 1, 1, 0, 3, 0, 0, time.UTC)
  13. type update struct {
  14. value float64
  15. timestamp time.Time
  16. }
  17. tests := map[string]struct {
  18. bit uint64
  19. updates []update
  20. want []MetricValue
  21. }{
  22. "no update": {
  23. bit: 0x8,
  24. updates: []update{},
  25. want: []MetricValue{{Value: 0}},
  26. },
  27. "single sample bit set": {
  28. bit: 0x8,
  29. updates: []update{{value: 8, timestamp: time1}},
  30. want: []MetricValue{{Value: 1}},
  31. },
  32. "single sample bit clear": {
  33. bit: 0x8,
  34. updates: []update{{value: 4, timestamp: time1}},
  35. want: []MetricValue{{Value: 0}},
  36. },
  37. "half of samples set": {
  38. bit: 0x4,
  39. updates: []update{
  40. {value: 0x4, timestamp: time1},
  41. {value: 0x0, timestamp: time2},
  42. {value: 0x4 | 0x8, timestamp: time3},
  43. {value: 0x8, timestamp: time4},
  44. },
  45. want: []MetricValue{{Value: 0.5}},
  46. },
  47. "other bits do not count": {
  48. bit: 0x40,
  49. updates: []update{
  50. {value: 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x80, timestamp: time1},
  51. },
  52. want: []MetricValue{{Value: 0}},
  53. },
  54. "duplicate timestamp counts once": {
  55. bit: 0x4,
  56. updates: []update{
  57. {value: 0x4, timestamp: time1},
  58. {value: 0x0, timestamp: time1},
  59. {value: 0x0, timestamp: time2},
  60. },
  61. want: []MetricValue{{Value: 0.5}},
  62. },
  63. "invalid values are treated as bit clear": {
  64. bit: 0x4,
  65. updates: []update{
  66. {value: math.NaN(), timestamp: time1},
  67. {value: -4, timestamp: time2},
  68. {value: 0x4, timestamp: time3},
  69. },
  70. want: []MetricValue{{Value: 1.0 / 3.0}},
  71. },
  72. }
  73. for name, tt := range tests {
  74. t.Run(name, func(t *testing.T) {
  75. agg := BitSetRatio(tt.bit)([]string{})
  76. for _, u := range tt.updates {
  77. agg.Update(u.value, u.timestamp, nil)
  78. }
  79. if got := agg.Value(); !reflect.DeepEqual(got, tt.want) {
  80. t.Errorf("Value() = %v, want %v", got, tt.want)
  81. }
  82. })
  83. }
  84. }