three_legged_cat_test.go 2.17 KB
Newer Older
1 2 3 4 5 6 7 8 9
package epictest

import (
	"bytes"
	"io"
	"math"
	"testing"

	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
10 11
	core "github.com/jbenet/go-ipfs/core"
	core_io "github.com/jbenet/go-ipfs/core/io"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12
	mocknet "github.com/jbenet/go-ipfs/p2p/net/mock"
13
	"github.com/jbenet/go-ipfs/p2p/peer"
14
	errors "github.com/jbenet/go-ipfs/util/debugerror"
15
	testutil "github.com/jbenet/go-ipfs/util/testutil"
16 17 18
)

func TestThreeLeggedCat(t *testing.T) {
19
	conf := testutil.LatencyConfig{
20 21 22 23 24 25 26 27 28
		NetworkLatency:    0,
		RoutingLatency:    0,
		BlockstoreLatency: 0,
	}
	if err := RunThreeLeggedCat(RandomBytes(1*KB), conf); err != nil {
		t.Fatal(err)
	}
}

29
func RunThreeLeggedCat(data []byte, conf testutil.LatencyConfig) error {
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	const numPeers = 3

	// create network
	mn, err := mocknet.FullMeshLinked(ctx, numPeers)
	if err != nil {
		return errors.Wrap(err)
	}
	mn.SetLinkDefaults(mocknet.LinkOptions{
		Latency: conf.NetworkLatency,
		// TODO add to conf. This is tricky because we want 0 values to be functional.
		Bandwidth: math.MaxInt32,
	})

45 46
	peers := mn.Peers()
	if len(peers) < numPeers {
47 48
		return errors.New("test initialization error")
	}
49
	adder, err := core.NewIPFSNode(ctx, core.ConfigOption(MocknetTestRepo(peers[0], mn.Host(peers[0]), conf)))
50 51 52
	if err != nil {
		return err
	}
53
	catter, err := core.NewIPFSNode(ctx, core.ConfigOption(MocknetTestRepo(peers[1], mn.Host(peers[1]), conf)))
54 55 56
	if err != nil {
		return err
	}
57
	bootstrap, err := core.NewIPFSNode(ctx, core.ConfigOption(MocknetTestRepo(peers[2], mn.Host(peers[2]), conf)))
58 59 60
	if err != nil {
		return err
	}
61
	boostrapInfo := bootstrap.Peerstore.PeerInfo(bootstrap.PeerHost.ID())
62 63
	adder.Bootstrap(ctx, []peer.PeerInfo{boostrapInfo})
	catter.Bootstrap(ctx, []peer.PeerInfo{boostrapInfo})
64

65
	keyAdded, err := core_io.Add(adder, bytes.NewReader(data))
66 67 68 69
	if err != nil {
		return err
	}

70
	readerCatted, err := core_io.Cat(catter, keyAdded)
71 72 73 74 75 76 77 78 79 80 81 82
	if err != nil {
		return err
	}

	// verify
	var bufout bytes.Buffer
	io.Copy(&bufout, readerCatted)
	if 0 != bytes.Compare(bufout.Bytes(), data) {
		return errors.New("catted data does not match added data")
	}
	return nil
}