github.com/andy2046/gopie@v0.7.0/pkg/countminsketch/countmin_test.go (about) 1 package countminsketch 2 3 import ( 4 "strconv" 5 "testing" 6 ) 7 8 func TestCount(t *testing.T) { 9 cms, _ := NewGuess(0.001, 0.99) 10 11 for i := 0; i < 100; i++ { 12 cms.Add([]byte(strconv.Itoa(i))) 13 } 14 15 if count := cms.Count(); count != 100 { 16 t.Errorf("expected 100, got %d", count) 17 } 18 } 19 20 func TestEstimate(t *testing.T) { 21 cms, _ := NewGuess(0.001, 0.99) 22 cms.Add([]byte(`a`)) 23 cms.Add([]byte(`b`), 1) 24 cms.Add([]byte(`c`), 1) 25 cms.Add([]byte(`b`), 1) 26 27 if count := cms.Estimate([]byte(`a`)); count != 1 { 28 t.Errorf("expected 1, got %d", count) 29 } 30 31 if count := cms.Estimate([]byte(`b`)); count != 2 { 32 t.Errorf("expected 2, got %d", count) 33 } 34 35 if count := cms.Estimate([]byte(`c`)); count != 1 { 36 t.Errorf("expected 1, got %d", count) 37 } 38 39 if count := cms.Estimate([]byte(`x`)); count != 0 { 40 t.Errorf("expected 0, got %d", count) 41 } 42 } 43 44 func TestMerge(t *testing.T) { 45 cms, _ := NewGuess(0.001, 0.99) 46 cms.Add([]byte(`a`)) 47 cms.Add([]byte(`b`), 1) 48 cms.Add([]byte(`c`), 1) 49 cms.Add([]byte(`b`), 1) 50 cms.Add([]byte(`d`), 1) 51 52 other, _ := NewGuess(0.001, 0.99) 53 other.Add([]byte(`b`), 1) 54 other.Add([]byte(`c`), 1) 55 other.Add([]byte(`b`), 1) 56 57 if err := cms.Merge(other); err != nil { 58 t.Error(err) 59 } 60 61 if count := cms.Estimate([]byte(`a`)); count != 1 { 62 t.Errorf("expected 1, got %d", count) 63 } 64 65 if count := cms.Estimate([]byte(`b`)); count != 4 { 66 t.Errorf("expected 4, got %d", count) 67 } 68 69 if count := cms.Estimate([]byte(`c`)); count != 2 { 70 t.Errorf("expected 2, got %d", count) 71 } 72 73 if count := cms.Estimate([]byte(`d`)); count != 1 { 74 t.Errorf("expected 1, got %d", count) 75 } 76 77 if count := cms.Estimate([]byte(`x`)); count != 0 { 78 t.Errorf("expected 0, got %d", count) 79 } 80 } 81 82 func TestReset(t *testing.T) { 83 cms, _ := NewGuess(0.001, 0.99) 84 cms.Add([]byte(`a`)) 85 cms.Add([]byte(`b`), 1) 86 cms.Add([]byte(`c`), 1) 87 cms.Add([]byte(`b`), 1) 88 cms.Add([]byte(`d`), 1) 89 90 cms.Reset() 91 92 for i := uint(0); i < cms.depth; i++ { 93 for j := uint(0); j < cms.width; j++ { 94 if x := cms.matrix[i][j]; x != 0 { 95 t.Errorf("expected matrix to be empty, got %d", x) 96 } 97 } 98 } 99 } 100 101 func BenchmarkAdd(b *testing.B) { 102 b.StopTimer() 103 cms, _ := NewGuess(0.001, 0.99) 104 data := make([][]byte, b.N) 105 for i := 0; i < b.N; i++ { 106 data[i] = []byte(strconv.Itoa(i)) 107 } 108 b.StartTimer() 109 110 for n := 0; n < b.N; n++ { 111 cms.Add(data[n]) 112 } 113 } 114 115 func BenchmarkCount(b *testing.B) { 116 b.StopTimer() 117 cms, _ := NewGuess(0.001, 0.99) 118 data := make([][]byte, b.N) 119 for i := 0; i < b.N; i++ { 120 data[i] = []byte(strconv.Itoa(i)) 121 cms.Add([]byte(strconv.Itoa(i))) 122 } 123 b.StartTimer() 124 125 for n := 0; n < b.N; n++ { 126 cms.Estimate(data[n]) 127 } 128 }