-
Notifications
You must be signed in to change notification settings - Fork 0
/
kvndb_test.go
75 lines (65 loc) · 1.5 KB
/
kvndb_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
package kvndb
import (
"bytes"
"encoding/hex"
"math/rand"
"os"
"testing"
"time"
)
func TestKvndbSaveLoad(t *testing.T) {
// generate test data 1 mln random bytes sequences
testData := make(map[string][]byte)
rand.Seed(time.Now().Unix())
dKey := make([]byte, 8)
dVal := make([]byte, 8)
var err error
for i := 0; i < 1_000_000; i++ {
_, err = rand.Read(dKey)
if err != nil {
t.Fatal(err)
}
_, err = rand.Read(dVal)
if err != nil {
t.Fatal(err)
}
testData[hex.EncodeToString(dKey)] = dVal
}
// make new tmp dir for data
dir, err := os.MkdirTemp(".", "temp-*")
if err != nil && err.Error() != "mkdir ./temp: file exists" {
t.Fatal(err)
}
testKvndbSave(t, dir, testData)
loadedData := testKvndbLoad(t, dir)
if len(loadedData) != len(testData) {
t.Fatalf("loaded data size mismatch; test data size [%d], but loaded [%d]", len(testData), len(loadedData))
}
for k, tv := range testData {
if v, ok := loadedData[k]; ok {
if !bytes.Equal(tv, v) {
t.Fatalf("slices are not equal. expected [%s], but got [%s]", hex.EncodeToString(tv), hex.EncodeToString(v))
}
} else {
t.Fatalf("loaded data missing key [%s]", k)
}
}
}
func testKvndbSave(t *testing.T, dir string, testData map[string][]byte) {
d := New()
for k, v := range testData {
d.Put(hexToBytes(k), v)
}
err := d.Save(dir, 1)
if err != nil {
t.Fatal(err)
}
}
func testKvndbLoad(t *testing.T, dir string) map[string][]byte {
d := newDb()
err := d.Load(dir)
if err != nil {
t.Fatal(err)
}
return d.data
}