-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_test.go
121 lines (95 loc) · 2.53 KB
/
db_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// db_test.go -- test suite for dbreader/dbwriter
//
// (c) Sudhi Herle 2018
//
// Author: Sudhi Herle <[email protected]>
//
// This software does not come with any express or implied
// warranty; it is provided "as is". No claim is made to its
// suitability for any purpose.
package chd
import (
"flag"
"fmt"
"math/rand"
"os"
"testing"
"github.com/opencoff/go-fasthash"
)
var keep bool
func init() {
flag.BoolVar(&keep, "keep", false, "Keep test DB")
}
func TestDB(t *testing.T) {
assert := newAsserter(t)
fn := fmt.Sprintf("%s/mph%d.db", os.TempDir(), rand.Int())
wr, err := NewDBWriter(fn)
assert(err == nil, "can't create db: %s", err)
defer func() {
if keep {
t.Logf("DB in %s retained after test\n", fn)
} else {
os.Remove(fn)
}
}()
hseed := rand64()
kvmap := make(map[uint64]string)
for _, s := range keyw {
h := fasthash.Hash64(hseed, []byte(s))
err = wr.Add(h, []byte(s))
assert(err == nil, "can't add key %x: %s", h, err)
kvmap[h] = s
}
err = wr.Freeze(0.9)
assert(err == nil, "freeze failed: %s", err)
rd, err := NewDBReader(fn, 10)
assert(err == nil, "read failed: %s", err)
//rd.DumpMeta(os.Stdout)
for h, v := range kvmap {
s, err := rd.Find(h)
assert(err == nil, "can't find key %#x: %s", h, err)
assert(string(s) == v, "key %x: value mismatch; exp '%s', saw '%s'", h, v, string(s))
}
// now look for keys not in the DB
for i := 0; i < 10; i++ {
v, err := rd.Find(uint64(i))
assert(err != nil, "whoa: found key %d => %s", i, string(v))
}
}
func TestDBKeysOnly(t *testing.T) {
assert := newAsserter(t)
fn := fmt.Sprintf("%s/mph%d.db", os.TempDir(), rand.Int())
wr, err := NewDBWriter(fn)
assert(err == nil, "can't create db: %s", err)
defer func() {
if keep {
t.Logf("DB in %s retained after test\n", fn)
} else {
os.Remove(fn)
}
}()
hseed := rand64()
kvmap := make(map[uint64]string)
for _, s := range keyw {
h := fasthash.Hash64(hseed, []byte(s))
err = wr.Add(h, nil)
assert(err == nil, "can't add key %x: %s", h, err)
kvmap[h] = s
}
err = wr.Freeze(0.9)
assert(err == nil, "freeze failed: %s", err)
rd, err := NewDBReader(fn, 10)
assert(err == nil, "read failed: %s", err)
//rd.DumpMeta(os.Stdout)
for h := range kvmap {
s, err := rd.Find(h)
assert(err == nil, "can't find key %#x: %s", h, err)
assert(s == nil, "key %x: value mismatch; exp nil, saw '%s'", h, string(s))
}
// now look for keys not in the DB
for i := 0; i < 10; i++ {
j := rand64()
v, err := rd.Find(j)
assert(err != nil, "whoa: found key %d => %s", j, string(v))
}
}