github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/p2p/net/swarm/swarm_net_test.go (about)

     1  package swarm_test
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  	"time"
     7  
     8  	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
     9  	inet "github.com/ipfs/go-ipfs/p2p/net"
    10  	testutil "github.com/ipfs/go-ipfs/p2p/test/util"
    11  )
    12  
    13  // TestConnectednessCorrect starts a few networks, connects a few
    14  // and tests Connectedness value is correct.
    15  func TestConnectednessCorrect(t *testing.T) {
    16  
    17  	ctx := context.Background()
    18  
    19  	nets := make([]inet.Network, 4)
    20  	for i := 0; i < 4; i++ {
    21  		nets[i] = testutil.GenSwarmNetwork(t, ctx)
    22  	}
    23  
    24  	// connect 0-1, 0-2, 0-3, 1-2, 2-3
    25  
    26  	dial := func(a, b inet.Network) {
    27  		testutil.DivulgeAddresses(b, a)
    28  		if _, err := a.DialPeer(ctx, b.LocalPeer()); err != nil {
    29  			t.Fatalf("Failed to dial: %s", err)
    30  		}
    31  	}
    32  
    33  	dial(nets[0], nets[1])
    34  	dial(nets[0], nets[3])
    35  	dial(nets[1], nets[2])
    36  	dial(nets[3], nets[2])
    37  
    38  	// there's something wrong with dial, i think. it's not finishing
    39  	// completely. there must be some async stuff.
    40  	<-time.After(100 * time.Millisecond)
    41  
    42  	// test those connected show up correctly
    43  
    44  	// test connected
    45  	expectConnectedness(t, nets[0], nets[1], inet.Connected)
    46  	expectConnectedness(t, nets[0], nets[3], inet.Connected)
    47  	expectConnectedness(t, nets[1], nets[2], inet.Connected)
    48  	expectConnectedness(t, nets[3], nets[2], inet.Connected)
    49  
    50  	// test not connected
    51  	expectConnectedness(t, nets[0], nets[2], inet.NotConnected)
    52  	expectConnectedness(t, nets[1], nets[3], inet.NotConnected)
    53  
    54  	for _, n := range nets {
    55  		n.Close()
    56  	}
    57  }
    58  
    59  func expectConnectedness(t *testing.T, a, b inet.Network, expected inet.Connectedness) {
    60  	es := "%s is connected to %s, but Connectedness incorrect. %s %s"
    61  	if a.Connectedness(b.LocalPeer()) != expected {
    62  		t.Errorf(es, a, b, printConns(a), printConns(b))
    63  	}
    64  
    65  	// test symmetric case
    66  	if b.Connectedness(a.LocalPeer()) != expected {
    67  		t.Errorf(es, b, a, printConns(b), printConns(a))
    68  	}
    69  }
    70  
    71  func printConns(n inet.Network) string {
    72  	s := fmt.Sprintf("Connections in %s:\n", n)
    73  	for _, c := range n.Conns() {
    74  		s = s + fmt.Sprintf("- %s\n", c)
    75  	}
    76  	return s
    77  }