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

import (
4
	"context"
5 6
	"testing"

Steven Allen's avatar
Steven Allen committed
7
	u "gx/ipfs/QmNiJuT8Ja3hMVpBHXv3Q6dwmperaQ6JjLtpMQgMCD7xvx/go-ipfs-util"
Hector Sanjuan's avatar
Hector Sanjuan committed
8 9 10
	ds "gx/ipfs/QmXRKBQA4wXP7xWbFiZsR1GP4HV6wMDQ1aWFxZZ4uBcPX9/go-datastore"
	ds_sync "gx/ipfs/QmXRKBQA4wXP7xWbFiZsR1GP4HV6wMDQ1aWFxZZ4uBcPX9/go-datastore/sync"
	blockstore "gx/ipfs/QmaG4DZ4JaqEfvPWt5nPPgoTzhc1tr1T3f4Nu9Jpdm8ymY/go-ipfs-blockstore"
Steven Allen's avatar
Steven Allen committed
11
	cid "gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid"
12
	blocks "gx/ipfs/Qmej7nf81hi2x2tvjRBF3mcp74sQyuDH4VMYDGd1YtXjb2/go-block-format"
13
	blocksutil "gx/ipfs/Qmf951DP11mCoctpyF3ZppPZdo2oAxuNi2vnkVDgHJ8Fqk/go-ipfs-blocksutil"
14 15 16
)

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

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

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

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

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

	expected := g.Blocks(2)

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

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

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

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

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

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