1 // Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com>
2 // All rights reserved.
4 // Use of this source code is governed by a BSD-style license that can be
5 // found in the LICENSE file.
11 "github.com/syndtr/goleveldb/leveldb/util"
19 generator FilterGenerator
23 func newHarness(t *testing.T) *harness {
24 bloom := NewBloomFilter(10)
28 generator: bloom.NewGenerator(),
32 func (h *harness) add(key []byte) {
36 func (h *harness) addNum(key uint32) {
38 binary.LittleEndian.PutUint32(b[:], key)
42 func (h *harness) build() {
44 h.generator.Generate(b)
48 func (h *harness) reset() {
52 func (h *harness) filterLen() int {
56 func (h *harness) assert(key []byte, want, silent bool) bool {
57 got := h.bloom.Contains(h.filter, key)
58 if !silent && got != want {
59 h.t.Errorf("assert on '%v' failed got '%v', want '%v'", key, got, want)
64 func (h *harness) assertNum(key uint32, want, silent bool) bool {
66 binary.LittleEndian.PutUint32(b[:], key)
67 return h.assert(b[:], want, silent)
70 func TestBloomFilter_Empty(t *testing.T) {
73 h.assert([]byte("hello"), false, false)
74 h.assert([]byte("world"), false, false)
77 func TestBloomFilter_Small(t *testing.T) {
79 h.add([]byte("hello"))
80 h.add([]byte("world"))
82 h.assert([]byte("hello"), true, false)
83 h.assert([]byte("world"), true, false)
84 h.assert([]byte("x"), false, false)
85 h.assert([]byte("foo"), false, false)
88 func nextN(n int) int {
102 func TestBloomFilter_VaryingLengths(t *testing.T) {
104 var mediocre, good int
105 for n := 1; n < 10000; n = nextN(n) {
107 for i := 0; i < n; i++ {
113 want := (n * 10 / 8) + 40
115 t.Errorf("filter len test failed, '%d' > '%d'", got, want)
118 for i := 0; i < n; i++ {
119 h.assertNum(uint32(i), true, false)
123 for i := 0; i < 10000; i++ {
124 if h.assertNum(uint32(i+1000000000), true, true) {
130 t.Errorf("false positive rate is more than 2%%, got %v, at len %d", rate, n)
138 t.Logf("false positive rate: %d good, %d mediocre", good, mediocre)
139 if mediocre > good/5 {
140 t.Error("mediocre false positive rate is more than expected")