offline_test.go 1.63 KB
Newer Older
Jeromy's avatar
Jeromy committed
1
package offline
2 3

import (
4
	"context"
5 6
	"testing"

7 8
	"github.com/ipfs/go-ipfs/blocks/blockstore"
	"github.com/ipfs/go-ipfs/blocks/blocksutil"
9
	blocks "gx/ipfs/QmbJUay5h1HtzhJb5QQk2t26yCnJksHynvhcqp18utBPqG/go-block-format"
10

11
	cid "gx/ipfs/QmNw61A6sJoXMeP37mJRtQZdNhj5e3FdjoTN3v4FyE96Gk/go-cid"
Łukasz Magiera's avatar
Łukasz Magiera committed
12 13
	ds "gx/ipfs/QmSiN66ybp5udnQnvhb6euiWiiQWdGvwMhAWa95cC1DTCV/go-datastore"
	ds_sync "gx/ipfs/QmSiN66ybp5udnQnvhb6euiWiiQWdGvwMhAWa95cC1DTCV/go-datastore/sync"
14
	u "gx/ipfs/QmWbjfz3u6HkAdPh34dgPchGbQjob6LXLhAeCGii2TX69n/go-ipfs-util"
15 16 17
)

func TestBlockReturnsErr(t *testing.T) {
18
	off := Exchange(bstore())
19 20
	c := cid.NewCidV0(u.Hash([]byte("foo")))
	_, err := off.GetBlock(context.Background(), c)
21 22 23 24 25 26 27
	if err != nil {
		return // as desired
	}
	t.Fail()
}

func TestHasBlockReturnsNil(t *testing.T) {
28 29
	store := bstore()
	ex := Exchange(store)
30
	block := blocks.NewBlock([]byte("data"))
31

32
	err := ex.HasBlock(block)
33
	if err != nil {
34 35 36
		t.Fail()
	}

37
	if _, err := store.Get(block.Cid()); err != nil {
38 39 40 41 42 43 44 45 46 47 48 49
		t.Fatal(err)
	}
}

func TestGetBlocks(t *testing.T) {
	store := bstore()
	ex := Exchange(store)
	g := blocksutil.NewBlockGenerator()

	expected := g.Blocks(2)

	for _, b := range expected {
50
		if err := ex.HasBlock(b); err != nil {
51 52
			t.Fail()
		}
53
	}
54

55 56
	request := func() []*cid.Cid {
		var ks []*cid.Cid
57 58

		for _, b := range expected {
59
			ks = append(ks, b.Cid())
60 61 62 63 64 65 66 67 68 69
		}
		return ks
	}()

	received, err := ex.GetBlocks(context.Background(), request)
	if err != nil {
		t.Fatal(err)
	}

	var count int
70
	for range received {
71 72 73 74 75 76 77 78 79
		count++
	}
	if len(expected) != count {
		t.Fail()
	}
}

func bstore() blockstore.Blockstore {
	return blockstore.NewBlockstore(ds_sync.MutexWrap(ds.NewMapDatastore()))
80
}