-
Notifications
You must be signed in to change notification settings - Fork 0
/
cursor_test.go
116 lines (93 loc) · 1.94 KB
/
cursor_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
package tempdb
import (
"bytes"
"testing"
"github.com/btcsuite/btcwallet/walletdb"
)
var reset = func() {}
// `walletdbtest.TestInterface` doesn't cover cursors, so we test them here instead.
func TestCursor(t *testing.T) {
db, err := New("cursor.db")
if err != nil {
t.Fatal(err)
}
err = db.Update(func(tx walletdb.ReadWriteTx) error {
bkt, err := tx.CreateTopLevelBucket([]byte("alphabet"))
if err != nil {
t.Fatal(err)
}
// purposely unordered to ensure we reorder properly.
vals := [][]byte{
[]byte("c"),
[]byte("b"),
[]byte("a"),
[]byte("3"),
[]byte("2"),
[]byte("1"),
}
// populate the example values.
for _, v := range vals {
err = bkt.Put(v, nil)
if err != nil {
t.Fatal(err)
}
}
ex := [][]byte{
[]byte("1"),
[]byte("2"),
[]byte("3"),
[]byte("a"),
[]byte("b"),
[]byte("c"),
}
c := bkt.ReadCursor()
i := 0
for k, _ := c.First(); k != nil; k, _ = c.Next() {
if !bytes.Equal(ex[i], k) {
t.Fatalf("unexpected order: expected %s got %s", ex[i], k)
}
i++
}
return nil
}, reset)
if err != nil {
t.Fatal(err)
}
}
func TestCursorSeek(t *testing.T) {
db, err := New("cursor-seek.db")
if err != nil {
t.Fatal(err)
}
err = db.Update(func(tx walletdb.ReadWriteTx) error {
bkt, err := tx.CreateTopLevelBucket([]byte("alphabet"))
if err != nil {
t.Fatal(err)
}
vals := [][]byte{
[]byte("a"),
[]byte("b"),
[]byte("c"),
}
// populate the example values.
for _, v := range vals {
bkt.Put(v, nil)
}
// create a new read/write cursor.
c := bkt.ReadWriteCursor()
k, _ := c.Seek([]byte("b"))
// ensure we've seeked to the right key.
if !bytes.Equal(k, []byte("b")) {
t.Fatalf("expected an key of b not %s", k)
}
i := c.(*Cursor).index
// ensure we've seeked to the 2nd key pair.
if i != 1 {
t.Fatalf("expected an index of 1 not %d", i)
}
return nil
}, reset)
if err != nil {
t.Fatal(err)
}
}