| 1 |
package cuckoo |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"crypto/rand" |
| 6 |
"io" |
| 7 |
"os" |
| 8 |
"reflect" |
| 9 |
"testing" |
| 10 |
) |
| 11 |
|
| 12 |
func TestInsertion(t *testing.T) { |
| 13 |
cf := NewFilter(1000000) |
| 14 |
fd, err := os.Open("/usr/share/dict/words") |
| 15 |
if err != nil { |
| 16 |
panic(err) |
| 17 |
} |
| 18 |
scanner := bufio.NewScanner(fd) |
| 19 |
|
| 20 |
var values [][]byte |
| 21 |
var lineCount uint |
| 22 |
for scanner.Scan() { |
| 23 |
s := []byte(scanner.Text()) |
| 24 |
if cf.InsertUnique(s) { |
| 25 |
lineCount++ |
| 26 |
} |
| 27 |
values = append(values, s) |
| 28 |
} |
| 29 |
|
| 30 |
count := cf.Count() |
| 31 |
if count != lineCount { |
| 32 |
t.Errorf("Expected count = %d, instead count = %d", lineCount, count) |
| 33 |
} |
| 34 |
|
| 35 |
for _, v := range values { |
| 36 |
cf.Delete(v) |
| 37 |
} |
| 38 |
|
| 39 |
count = cf.Count() |
| 40 |
if count != 0 { |
| 41 |
t.Errorf("Expected count = 0, instead count == %d", count) |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
func TestEncodeDecode(t *testing.T) { |
| 46 |
cf := NewFilter(8) |
| 47 |
cf.buckets = []bucket{ |
| 48 |
[4]fingerprint{1, 2, 3, 4}, |
| 49 |
[4]fingerprint{5, 6, 7, 8}, |
| 50 |
} |
| 51 |
cf.count = 8 |
| 52 |
bytes := cf.Encode() |
| 53 |
ncf, err := Decode(bytes) |
| 54 |
if err != nil { |
| 55 |
t.Errorf("Expected no error, got %v", err) |
| 56 |
} |
| 57 |
if !reflect.DeepEqual(cf, ncf) { |
| 58 |
t.Errorf("Expected %v, got %v", cf, ncf) |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
func BenchmarkFilter_Reset(b *testing.B) { |
| 63 |
const cap = 10000 |
| 64 |
filter := NewFilter(cap) |
| 65 |
|
| 66 |
b.ResetTimer() |
| 67 |
|
| 68 |
for i := 0; i < b.N; i++ { |
| 69 |
filter.Reset() |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
func BenchmarkFilter_Insert(b *testing.B) { |
| 74 |
const cap = 10000 |
| 75 |
filter := NewFilter(cap) |
| 76 |
|
| 77 |
b.ResetTimer() |
| 78 |
|
| 79 |
var hash [32]byte |
| 80 |
for i := 0; i < b.N; i++ { |
| 81 |
io.ReadFull(rand.Reader, hash[:]) |
| 82 |
filter.Insert(hash[:]) |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
func BenchmarkFilter_Lookup(b *testing.B) { |
| 87 |
const cap = 10000 |
| 88 |
filter := NewFilter(cap) |
| 89 |
|
| 90 |
var hash [32]byte |
| 91 |
for i := 0; i < 10000; i++ { |
| 92 |
io.ReadFull(rand.Reader, hash[:]) |
| 93 |
filter.Insert(hash[:]) |
| 94 |
} |
| 95 |
|
| 96 |
b.ResetTimer() |
| 97 |
for i := 0; i < b.N; i++ { |
| 98 |
io.ReadFull(rand.Reader, hash[:]) |
| 99 |
filter.Lookup(hash[:]) |
| 100 |
} |
| 101 |
} |