fs_test.go 2.13 KB
Newer Older
1
package examples
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
2 3 4 5 6

import (
	"bytes"
	"testing"

Jakub Sztandera's avatar
Jakub Sztandera committed
7
	. "launchpad.net/gocheck"
8

Jeromy's avatar
Jeromy committed
9 10 11
	ds "github.com/ipfs/go-datastore"
	fs "github.com/ipfs/go-datastore/fs"
	query "github.com/ipfs/go-datastore/query"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
)

// Hook up gocheck into the "go test" runner.
func Test(t *testing.T) { TestingT(t) }

type DSSuite struct {
	dir string
	ds  ds.Datastore
}

var _ = Suite(&DSSuite{})

func (ks *DSSuite) SetUpTest(c *C) {
	ks.dir = c.MkDir()
	ks.ds, _ = fs.NewDatastore(ks.dir)
}

func (ks *DSSuite) TestOpen(c *C) {
	_, err := fs.NewDatastore("/tmp/foo/bar/baz")
	c.Assert(err, Not(Equals), nil)

	// setup ds
	_, err = fs.NewDatastore(ks.dir)
	c.Assert(err, Equals, nil)
}

func (ks *DSSuite) TestBasic(c *C) {

	keys := strsToKeys([]string{
		"foo",
		"foo/bar",
		"foo/bar/baz",
		"foo/barb",
		"foo/bar/bazb",
		"foo/bar/baz/barb",
	})

	for _, k := range keys {
		err := ks.ds.Put(k, []byte(k.String()))
		c.Check(err, Equals, nil)
	}

	for _, k := range keys {
		v, err := ks.ds.Get(k)
		c.Check(err, Equals, nil)
		c.Check(bytes.Equal(v.([]byte), []byte(k.String())), Equals, true)
	}
59 60 61 62 63 64 65 66 67 68 69

	r, err := ks.ds.Query(query.Query{Prefix: "/foo/bar/"})
	if err != nil {
		c.Check(err, Equals, nil)
	}

	expect := []string{
		"/foo/bar/baz",
		"/foo/bar/bazb",
		"/foo/bar/baz/barb",
	}
70 71 72 73
	all, err := r.Rest()
	if err != nil {
		c.Fatal(err)
	}
74 75 76 77 78 79 80 81 82 83 84 85 86 87
	c.Check(len(all), Equals, len(expect))

	for _, k := range expect {
		found := false
		for _, e := range all {
			if e.Key == k {
				found = true
			}
		}

		if !found {
			c.Error("did not find expected key: ", k)
		}
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
func (ks *DSSuite) TestDiskUsage(c *C) {
	keys := strsToKeys([]string{
		"foo",
		"foo/bar",
		"foo/bar/baz",
		"foo/barb",
		"foo/bar/bazb",
		"foo/bar/baz/barb",
	})

	for _, k := range keys {
		err := ks.ds.Put(k, []byte(k.String()))
		c.Check(err, Equals, nil)
	}

	if ps, ok := ks.ds.(ds.PersistentDatastore); ok {
		if s, err := ps.DiskUsage(); s <= 100 || err != nil {
			c.Error("unexpected size is: ", s)
		}
	} else {
		c.Error("should implement PersistentDatastore")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114 115 116 117 118 119 120
func strsToKeys(strs []string) []ds.Key {
	keys := make([]ds.Key, len(strs))
	for i, s := range strs {
		keys[i] = ds.NewKey(s)
	}
	return keys
}