From 63a9afd028ff0efa38f72a80a3d95c25b78bf7b8 Mon Sep 17 00:00:00 2001 From: Ben Johnson Date: Mon, 9 Jun 2014 12:31:52 -0600 Subject: [PATCH] Add seek forward test. --- cursor_test.go | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/cursor_test.go b/cursor_test.go index 23b3a8e..b44bf53 100644 --- a/cursor_test.go +++ b/cursor_test.go @@ -1,6 +1,7 @@ package bolt import ( + "encoding/binary" "sort" "testing" "testing/quick" @@ -66,6 +67,57 @@ func TestCursor_Seek(t *testing.T) { }) } +// Ensure that a Tx cursor can seek to the appropriate keys when there are a +// large number of keys. This test also checks that seek will always move +// forward to the next key. +// +// Related: https://github.com/boltdb/bolt/pull/187 +func TestCursor_Seek_Large(t *testing.T) { + withOpenDB(func(db *DB, path string) { + var count = 10000 + + // Insert every other key between 0 and $count. + db.Update(func(tx *Tx) error { + b, _ := tx.CreateBucket([]byte("widgets")) + for i := 0; i < count; i += 100 { + for j := i; j < i+100; j += 2 { + k := make([]byte, 8) + binary.BigEndian.PutUint64(k, uint64(j)) + b.Put(k, make([]byte, 100)) + } + } + return nil + }) + + db.View(func(tx *Tx) error { + c := tx.Bucket([]byte("widgets")).Cursor() + for i := 0; i < count; i++ { + seek := make([]byte, 8) + binary.BigEndian.PutUint64(seek, uint64(i)) + + k, _ := c.Seek(seek) + + // The last seek is beyond the end of the the range so + // it should return nil. + if i == count-1 { + assert.Nil(t, k) + continue + } + + // Otherwise we should seek to the exact key or the next key. + num := binary.BigEndian.Uint64(k) + if i%2 == 0 { + assert.Equal(t, uint64(i), num) + } else { + assert.Equal(t, uint64(i+1), num) + } + } + + return nil + }) + }) +} + // Ensure that a cursor can iterate over an empty bucket without error. func TestCursor_EmptyBucket(t *testing.T) { withOpenDB(func(db *DB, path string) {