three_legged_cat_test.go 2.23 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
	core "github.com/jbenet/go-ipfs/core"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
11
	coreunix "github.com/jbenet/go-ipfs/core/coreunix"
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"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
14
	"github.com/jbenet/go-ipfs/thirdparty/unit"
15
	errors "github.com/jbenet/go-ipfs/util/debugerror"
16
	testutil "github.com/jbenet/go-ipfs/util/testutil"
17 18 19
)

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

30
func RunThreeLeggedCat(data []byte, conf testutil.LatencyConfig) error {
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
	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,
	})

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
66
	keyAdded, err := coreunix.Add(adder, bytes.NewReader(data))
67 68 69 70
	if err != nil {
		return err
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
71
	readerCatted, err := coreunix.Cat(catter, keyAdded)
72 73 74 75 76 77 78 79 80 81 82 83
	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
}