github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/test/integration/bitswap_wo_routing_test.go (about)

     1  package integrationtest
     2  
     3  import (
     4  	"bytes"
     5  	"testing"
     6  
     7  	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
     8  	"github.com/ipfs/go-ipfs/blocks"
     9  	"github.com/ipfs/go-ipfs/core"
    10  	"github.com/ipfs/go-ipfs/core/mock"
    11  	mocknet "github.com/ipfs/go-ipfs/p2p/net/mock"
    12  )
    13  
    14  func TestBitswapWithoutRouting(t *testing.T) {
    15  	ctx, cancel := context.WithCancel(context.Background())
    16  	defer cancel()
    17  	const numPeers = 4
    18  
    19  	// create network
    20  	mn := mocknet.New(ctx)
    21  
    22  	var nodes []*core.IpfsNode
    23  	for i := 0; i < numPeers; i++ {
    24  		n, err := core.NewNode(ctx, &core.BuildCfg{
    25  			Online:  true,
    26  			Host:    coremock.MockHostOption(mn),
    27  			Routing: core.NilRouterOption, // no routing
    28  		})
    29  		if err != nil {
    30  			t.Fatal(err)
    31  		}
    32  		defer n.Close()
    33  		nodes = append(nodes, n)
    34  	}
    35  
    36  	mn.LinkAll()
    37  
    38  	// connect them
    39  	for _, n1 := range nodes {
    40  		for _, n2 := range nodes {
    41  			if n1 == n2 {
    42  				continue
    43  			}
    44  
    45  			log.Debug("connecting to other hosts")
    46  			p2 := n2.PeerHost.Peerstore().PeerInfo(n2.PeerHost.ID())
    47  			if err := n1.PeerHost.Connect(ctx, p2); err != nil {
    48  				t.Fatal(err)
    49  			}
    50  		}
    51  	}
    52  
    53  	// add blocks to each before
    54  	log.Debug("adding block.")
    55  	block0 := blocks.NewBlock([]byte("block0"))
    56  	block1 := blocks.NewBlock([]byte("block1"))
    57  
    58  	// put 1 before
    59  	if err := nodes[0].Blockstore.Put(block0); err != nil {
    60  		t.Fatal(err)
    61  	}
    62  
    63  	//  get it out.
    64  	for i, n := range nodes {
    65  		// skip first because block not in its exchange. will hang.
    66  		if i == 0 {
    67  			continue
    68  		}
    69  
    70  		log.Debugf("%d %s get block.", i, n.Identity)
    71  		b, err := n.Blocks.GetBlock(ctx, block0.Key())
    72  		if err != nil {
    73  			t.Error(err)
    74  		} else if !bytes.Equal(b.Data, block0.Data) {
    75  			t.Error("byte comparison fail")
    76  		} else {
    77  			log.Debug("got block: %s", b.Key())
    78  		}
    79  	}
    80  
    81  	// put 1 after
    82  	if err := nodes[1].Blockstore.Put(block1); err != nil {
    83  		t.Fatal(err)
    84  	}
    85  
    86  	//  get it out.
    87  	for _, n := range nodes {
    88  		b, err := n.Blocks.GetBlock(ctx, block1.Key())
    89  		if err != nil {
    90  			t.Error(err)
    91  		} else if !bytes.Equal(b.Data, block1.Data) {
    92  			t.Error("byte comparison fail")
    93  		} else {
    94  			log.Debug("got block: %s", b.Key())
    95  		}
    96  	}
    97  }