tiered_test.go 1.87 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
package tiered

import (
	"testing"

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

func testHas(t *testing.T, dses []ds.Datastore, k ds.Key, v interface{}) {
	// all under should have it
	for _, d := range dses {
		if v2, err := d.Get(k); err != nil {
			t.Error(err)
		} else if v2 != v {
			t.Error("value incorrect", d, k, v, v2)
		}

		if has, err := d.Has(k); err != nil {
			t.Error(err)
		} else if !has {
			t.Error("should have it", d, k, v)
		}
	}
}

func testNotHas(t *testing.T, dses []ds.Datastore, k ds.Key) {
	// all under should not have it
	for _, d := range dses {
		if _, err := d.Get(k); err == nil {
			t.Error("should not have it", d, k)
		}

		if has, err := d.Has(k); err != nil {
			t.Error(err)
		} else if has {
			t.Error("should not have it", d, k)
		}
	}
}

func TestTiered(t *testing.T) {
	d1 := ds.NewMapDatastore()
	d2 := ds.NewMapDatastore()
	d3 := ds.NewMapDatastore()
	d4 := ds.NewMapDatastore()

	td := New(d1, d2, d3, d4)
	td.Put(ds.NewKey("foo"), "bar")
	testHas(t, []ds.Datastore{td}, ds.NewKey("foo"), "bar")
Jeromy's avatar
Jeromy committed
52
	testHas(t, td, ds.NewKey("foo"), "bar") // all children
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
53 54 55 56 57

	// remove it from, say, caches.
	d1.Delete(ds.NewKey("foo"))
	d2.Delete(ds.NewKey("foo"))
	testHas(t, []ds.Datastore{td}, ds.NewKey("foo"), "bar")
Jeromy's avatar
Jeromy committed
58 59
	testHas(t, td[2:], ds.NewKey("foo"), "bar")
	testNotHas(t, td[:2], ds.NewKey("foo"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60 61 62 63

	// write it again.
	td.Put(ds.NewKey("foo"), "bar2")
	testHas(t, []ds.Datastore{td}, ds.NewKey("foo"), "bar2")
Jeromy's avatar
Jeromy committed
64
	testHas(t, td, ds.NewKey("foo"), "bar2")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
}

func TestQueryCallsLast(t *testing.T) {
	var d1n, d2n, d3n int
	d1 := dscb.Wrap(ds.NewMapDatastore(), func() { d1n++ })
	d2 := dscb.Wrap(ds.NewMapDatastore(), func() { d2n++ })
	d3 := dscb.Wrap(ds.NewMapDatastore(), func() { d3n++ })

	td := New(d1, d2, d3)

	td.Query(dsq.Query{})
	if d3n < 1 {
		t.Error("should call last")
	}
}