ds_test.go 2.06 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
package leveldb

import (
	"io/ioutil"
	"os"
	"testing"

	ds "github.com/jbenet/go-datastore"
	dsq "github.com/jbenet/go-datastore/query"
)

var testcases = map[string]string{
	"/a":     "a",
	"/a/b":   "ab",
	"/a/b/c": "abc",
	"/a/b/d": "a/b/d",
	"/a/c":   "ac",
	"/a/d":   "ad",
	"/e":     "e",
	"/f":     "f",
}

23 24 25 26 27 28
// returns datastore, and a function to call on exit.
// (this garbage collects). So:
//
//  d, close := newDS(t)
//  defer close()
func newDS(t *testing.T) (Datastore, func()) {
29 30 31 32 33 34 35 36 37
	path, err := ioutil.TempDir("/tmp", "testing_leveldb_")
	if err != nil {
		t.Fatal(err)
	}

	d, err := NewDatastore(path, nil)
	if err != nil {
		t.Fatal(err)
	}
38 39 40 41 42
	return d, func() {
		os.RemoveAll(path)
		d.Close()
	}
}
43

44
func addTestCases(t *testing.T, d Datastore, testcases map[string]string) {
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
	for k, v := range testcases {
		dsk := ds.NewKey(k)
		if err := d.Put(dsk, []byte(v)); err != nil {
			t.Fatal(err)
		}
	}

	for k, v := range testcases {
		dsk := ds.NewKey(k)
		v2, err := d.Get(dsk)
		if err != nil {
			t.Fatal(err)
		}
		v2b := v2.([]byte)
		if string(v2b) != v {
			t.Errorf("%s values differ: %s != %s", k, v, v2)
		}
	}

64 65 66 67 68 69 70
}

func TestQuery(t *testing.T) {
	d, close := newDS(t)
	defer close()
	addTestCases(t, d, testcases)

71 72 73 74 75
	rs, err := d.Query(dsq.Query{Prefix: "/a/"})
	if err != nil {
		t.Fatal(err)
	}

76
	expectMatches(t, []string{
77 78 79 80 81
		"/a/b",
		"/a/b/c",
		"/a/b/d",
		"/a/c",
		"/a/d",
82
	}, rs)
83 84 85 86 87 88

	// test offset and limit

	rs, err = d.Query(dsq.Query{Prefix: "/a/", Offset: 2, Limit: 2})
	if err != nil {
		t.Fatal(err)
89 90
	}

91 92 93
	expectMatches(t, []string{
		"/a/b/d",
		"/a/c",
94 95 96
	}, rs)

}
97

98 99 100 101
func TestQueryRespectsProcess(t *testing.T) {
	d, close := newDS(t)
	defer close()
	addTestCases(t, d, testcases)
102 103
}

104 105 106 107 108 109
func expectMatches(t *testing.T, expect []string, actualR dsq.Results) {
	actual, err := actualR.Rest()
	if err != nil {
		t.Error(err)
	}

110 111
	if len(actual) != len(expect) {
		t.Error("not enough", expect, actual)
112 113 114
	}
	for _, k := range expect {
		found := false
115
		for _, e := range actual {
116 117 118 119 120 121 122 123 124
			if e.Key == k {
				found = true
			}
		}
		if !found {
			t.Error(k, "not found")
		}
	}
}