blocks_test.go 2.31 KB
Newer Older
1
package bstest
2 3 4 5

import (
	"bytes"
	"testing"
Jeromy's avatar
Jeromy committed
6 7
	"time"

8 9 10 11 12 13
	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
	dssync "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/sync"
	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	blocks "github.com/ipfs/go-ipfs/blocks"
	blockstore "github.com/ipfs/go-ipfs/blocks/blockstore"
	blocksutil "github.com/ipfs/go-ipfs/blocks/blocksutil"
14
	key "github.com/ipfs/go-ipfs/blocks/key"
15
	. "github.com/ipfs/go-ipfs/blockservice"
16 17
	offline "github.com/ipfs/go-ipfs/exchange/offline"
	u "github.com/ipfs/go-ipfs/util"
18 19 20
)

func TestBlocks(t *testing.T) {
21
	bstore := blockstore.NewBlockstore(dssync.MutexWrap(ds.NewMapDatastore()))
22
	bs := New(bstore, offline.Exchange(bstore))
23
	defer bs.Close()
24

Jeromy's avatar
Jeromy committed
25
	b := blocks.NewBlock([]byte("beep boop"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
26
	h := u.Hash([]byte("beep boop"))
27 28 29 30
	if !bytes.Equal(b.Multihash, h) {
		t.Error("Block Multihash and data multihash not equal")
	}

31
	if b.Key() != key.Key(h) {
32 33 34 35 36 37 38 39 40 41 42 43 44
		t.Error("Block key and data multihash key not equal")
	}

	k, err := bs.AddBlock(b)
	if err != nil {
		t.Error("failed to add block to BlockService", err)
		return
	}

	if k != b.Key() {
		t.Error("returned key is not equal to block key", err)
	}

Jeromy's avatar
Jeromy committed
45 46
	ctx, _ := context.WithTimeout(context.TODO(), time.Second*5)
	b2, err := bs.GetBlock(ctx, b.Key())
47 48 49 50 51 52 53 54 55 56 57 58 59
	if err != nil {
		t.Error("failed to retrieve block from BlockService", err)
		return
	}

	if b.Key() != b2.Key() {
		t.Error("Block keys not equal.")
	}

	if !bytes.Equal(b.Data, b2.Data) {
		t.Error("Block data is not equal.")
	}
}
60

61
func TestGetBlocksSequential(t *testing.T) {
62
	var servs = Mocks(4)
63 64 65
	for _, s := range servs {
		defer s.Close()
	}
66
	bg := blocksutil.NewBlockGenerator()
67 68
	blks := bg.Blocks(50)

69
	var keys []key.Key
70 71 72 73 74
	for _, blk := range blks {
		keys = append(keys, blk.Key())
		servs[0].AddBlock(blk)
	}

75
	t.Log("one instance at a time, get blocks concurrently")
Brian Tiger Chow's avatar
Brian Tiger Chow committed
76

77
	for i := 1; i < len(servs); i++ {
78
		ctx, _ := context.WithTimeout(context.TODO(), time.Second*50)
79
		out := servs[i].GetBlocks(ctx, keys)
80
		gotten := make(map[key.Key]*blocks.Block)
81 82 83 84 85 86 87 88 89 90
		for blk := range out {
			if _, ok := gotten[blk.Key()]; ok {
				t.Fatal("Got duplicate block!")
			}
			gotten[blk.Key()] = blk
		}
		if len(gotten) != len(blks) {
			t.Fatalf("Didnt get enough blocks back: %d/%d", len(gotten), len(blks))
		}
	}
91
}