blockstore_test.go 5.69 KB
Newer Older
1 2 3 4
package blockstore

import (
	"bytes"
5
	"context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	"fmt"
7 8
	"testing"

9 10 11
	blocks "github.com/ipfs/go-ipfs/blocks"
	dshelp "github.com/ipfs/go-ipfs/thirdparty/ds-help"

Jeromy's avatar
Jeromy committed
12 13 14
	ds "gx/ipfs/QmRWDav6mzWseLWeYfVd5fvUKiVe9xNH29YfMF438fG364/go-datastore"
	dsq "gx/ipfs/QmRWDav6mzWseLWeYfVd5fvUKiVe9xNH29YfMF438fG364/go-datastore/query"
	ds_sync "gx/ipfs/QmRWDav6mzWseLWeYfVd5fvUKiVe9xNH29YfMF438fG364/go-datastore/sync"
15
	u "gx/ipfs/Qmb912gdngC1UWwTkhuW8knyRbcWeu5kqkxBpveLmW8bSr/go-ipfs-util"
Jeromy's avatar
Jeromy committed
16
	cid "gx/ipfs/QmcTcsTvfaeEBRFo1TkFgT8sRmgi1n1LTZpecfVP8fzpGD/go-cid"
17 18 19 20
)

func TestGetWhenKeyNotPresent(t *testing.T) {
	bs := NewBlockstore(ds_sync.MutexWrap(ds.NewMapDatastore()))
21 22
	c := cid.NewCidV0(u.Hash([]byte("stuff")))
	bl, err := bs.Get(c)
23

24 25 26 27 28
	if bl != nil {
		t.Error("nil block expected")
	}
	if err == nil {
		t.Error("error expected, got nil")
29 30 31
	}
}

32
func TestGetWhenKeyIsNil(t *testing.T) {
jbenet's avatar
jbenet committed
33
	bs := NewBlockstore(ds_sync.MutexWrap(ds.NewMapDatastore()))
34
	_, err := bs.Get(nil)
jbenet's avatar
jbenet committed
35 36 37 38 39
	if err != ErrNotFound {
		t.Fail()
	}
}

40 41 42 43 44 45 46 47 48
func TestPutThenGetBlock(t *testing.T) {
	bs := NewBlockstore(ds_sync.MutexWrap(ds.NewMapDatastore()))
	block := blocks.NewBlock([]byte("some data"))

	err := bs.Put(block)
	if err != nil {
		t.Fatal(err)
	}

49
	blockFromBlockstore, err := bs.Get(block.Cid())
50 51 52
	if err != nil {
		t.Fatal(err)
	}
Jeromy's avatar
Jeromy committed
53
	if !bytes.Equal(block.RawData(), blockFromBlockstore.RawData()) {
54 55 56 57
		t.Fail()
	}
}

58
func TestHashOnRead(t *testing.T) {
59 60 61 62 63 64
	orginalDebug := u.Debug
	defer (func() {
		u.Debug = orginalDebug
	})()
	u.Debug = false

65 66
	bs := NewBlockstore(ds_sync.MutexWrap(ds.NewMapDatastore()))
	bl := blocks.NewBlock([]byte("some data"))
67
	blBad, err := blocks.NewBlockWithCid([]byte("some other data"), bl.Cid())
68
	if err != nil {
69
		t.Fatal("debug is off, still got an error")
70
	}
71
	bl2 := blocks.NewBlock([]byte("some other data"))
72
	bs.Put(blBad)
73
	bs.Put(bl2)
74
	bs.HashOnRead(true)
75

76
	if _, err := bs.Get(bl.Cid()); err != ErrHashMismatch {
77
		t.Fatalf("expected '%v' got '%v'\n", ErrHashMismatch, err)
78
	}
79

80
	if b, err := bs.Get(bl2.Cid()); err != nil || b.String() != bl2.String() {
81 82
		t.Fatal("got wrong blocks")
	}
83 84
}

85
func newBlockStoreWithKeys(t *testing.T, d ds.Datastore, N int) (Blockstore, []*cid.Cid) {
86 87 88 89
	if d == nil {
		d = ds.NewMapDatastore()
	}
	bs := NewBlockstore(ds_sync.MutexWrap(d))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90

91
	keys := make([]*cid.Cid, N)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
92 93 94 95 96 97
	for i := 0; i < N; i++ {
		block := blocks.NewBlock([]byte(fmt.Sprintf("some data %d", i)))
		err := bs.Put(block)
		if err != nil {
			t.Fatal(err)
		}
98
		keys[i] = block.Cid()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
99
	}
100 101 102
	return bs, keys
}

103 104
func collect(ch <-chan *cid.Cid) []*cid.Cid {
	var keys []*cid.Cid
105 106 107 108 109 110
	for k := range ch {
		keys = append(keys, k)
	}
	return keys
}

111 112
func TestAllKeysSimple(t *testing.T) {
	bs, keys := newBlockStoreWithKeys(t, nil, 100)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
113

114
	ctx := context.Background()
115
	ch, err := bs.AllKeysChan(ctx)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
116 117 118
	if err != nil {
		t.Fatal(err)
	}
119 120
	keys2 := collect(ch)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121
	// for _, k2 := range keys2 {
Michael Muré's avatar
Michael Muré committed
122
	// 	t.Log("found ", k2.B58String())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123 124 125
	// }

	expectMatches(t, keys, keys2)
126
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127

128 129 130 131 132 133 134 135 136 137 138 139
func TestAllKeysRespectsContext(t *testing.T) {
	N := 100

	d := &queryTestDS{ds: ds.NewMapDatastore()}
	bs, _ := newBlockStoreWithKeys(t, d, N)

	started := make(chan struct{}, 1)
	done := make(chan struct{}, 1)
	errors := make(chan error, 100)

	getKeys := func(ctx context.Context) {
		started <- struct{}{}
140
		ch, err := bs.AllKeysChan(ctx) // once without cancelling
141 142 143
		if err != nil {
			errors <- err
		}
144
		_ = collect(ch)
145 146 147 148
		done <- struct{}{}
		errors <- nil // a nil one to signal break
	}

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
	var results dsq.Results
	var resultsmu = make(chan struct{})
	resultChan := make(chan dsq.Result)
	d.SetFunc(func(q dsq.Query) (dsq.Results, error) {
		results = dsq.ResultsWithChan(q, resultChan)
		resultsmu <- struct{}{}
		return results, nil
	})

	go getKeys(context.Background())

	// make sure it's waiting.
	<-started
	<-resultsmu
	select {
	case <-done:
		t.Fatal("sync is wrong")
	case <-results.Process().Closing():
		t.Fatal("should not be closing")
	case <-results.Process().Closed():
		t.Fatal("should not be closed")
	default:
171 172
	}

173 174 175 176 177
	e := dsq.Entry{Key: BlockPrefix.ChildString("foo").String()}
	resultChan <- dsq.Result{Entry: e} // let it go.
	close(resultChan)
	<-done                       // should be done now.
	<-results.Process().Closed() // should be closed now
178

179 180 181 182
	// print any errors
	for err := range errors {
		if err == nil {
			break
183
		}
184
		t.Error(err)
185
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
186 187 188

}

189 190 191 192
func TestValueTypeMismatch(t *testing.T) {
	block := blocks.NewBlock([]byte("some data"))

	datastore := ds.NewMapDatastore()
193
	k := BlockPrefix.Child(dshelp.CidToDsKey(block.Cid()))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194
	datastore.Put(k, "data that isn't a block!")
195 196 197

	blockstore := NewBlockstore(ds_sync.MutexWrap(datastore))

198
	_, err := blockstore.Get(block.Cid())
199 200 201 202
	if err != ValueTypeMismatch {
		t.Fatal(err)
	}
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
203

204
func expectMatches(t *testing.T, expect, actual []*cid.Cid) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205 206 207 208 209 210 211

	if len(expect) != len(actual) {
		t.Errorf("expect and actual differ: %d != %d", len(expect), len(actual))
	}
	for _, ek := range expect {
		found := false
		for _, ak := range actual {
212
			if ek.Equals(ak) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213 214 215 216 217 218 219 220
				found = true
			}
		}
		if !found {
			t.Error("expected key not found: ", ek)
		}
	}
}
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

type queryTestDS struct {
	cb func(q dsq.Query) (dsq.Results, error)
	ds ds.Datastore
}

func (c *queryTestDS) SetFunc(f func(dsq.Query) (dsq.Results, error)) { c.cb = f }

func (c *queryTestDS) Put(key ds.Key, value interface{}) (err error) {
	return c.ds.Put(key, value)
}

func (c *queryTestDS) Get(key ds.Key) (value interface{}, err error) {
	return c.ds.Get(key)
}

func (c *queryTestDS) Has(key ds.Key) (exists bool, err error) {
	return c.ds.Has(key)
}

func (c *queryTestDS) Delete(key ds.Key) (err error) {
	return c.ds.Delete(key)
}

func (c *queryTestDS) Query(q dsq.Query) (dsq.Results, error) {
	if c.cb != nil {
		return c.cb(q)
	}
	return c.ds.Query(q)
}
251 252 253 254

func (c *queryTestDS) Batch() (ds.Batch, error) {
	return ds.NewBasicBatch(c), nil
}