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

     1  package swarm
     2  
     3  import (
     4  	"testing"
     5  
     6  	peer "github.com/ipfs/go-ipfs/p2p/peer"
     7  
     8  	ma "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
     9  	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
    10  )
    11  
    12  func TestPeers(t *testing.T) {
    13  	// t.Skip("skipping for another test")
    14  
    15  	ctx := context.Background()
    16  	swarms := makeSwarms(ctx, t, 2)
    17  	s1 := swarms[0]
    18  	s2 := swarms[1]
    19  
    20  	connect := func(s *Swarm, dst peer.ID, addr ma.Multiaddr) {
    21  		// TODO: make a DialAddr func.
    22  		s.peers.AddAddr(dst, addr, peer.PermanentAddrTTL)
    23  		// t.Logf("connections from %s", s.LocalPeer())
    24  		// for _, c := range s.ConnectionsToPeer(dst) {
    25  		// 	t.Logf("connection from %s to %s: %v", s.LocalPeer(), dst, c)
    26  		// }
    27  		// t.Logf("")
    28  		if _, err := s.Dial(ctx, dst); err != nil {
    29  			t.Fatal("error swarm dialing to peer", err)
    30  		}
    31  		// t.Log(s.swarm.Dump())
    32  	}
    33  
    34  	s1GotConn := make(chan struct{}, 0)
    35  	s2GotConn := make(chan struct{}, 0)
    36  	s1.SetConnHandler(func(c *Conn) {
    37  		s1GotConn <- struct{}{}
    38  	})
    39  	s2.SetConnHandler(func(c *Conn) {
    40  		s2GotConn <- struct{}{}
    41  	})
    42  
    43  	connect(s1, s2.LocalPeer(), s2.ListenAddresses()[0])
    44  	<-s2GotConn // have to wait here so the other side catches up.
    45  	connect(s2, s1.LocalPeer(), s1.ListenAddresses()[0])
    46  
    47  	for i := 0; i < 100; i++ {
    48  		connect(s1, s2.LocalPeer(), s2.ListenAddresses()[0])
    49  		connect(s2, s1.LocalPeer(), s1.ListenAddresses()[0])
    50  	}
    51  
    52  	for _, s := range swarms {
    53  		log.Infof("%s swarm routing table: %s", s.local, s.Peers())
    54  	}
    55  
    56  	test := func(s *Swarm) {
    57  		expect := 1
    58  		actual := len(s.Peers())
    59  		if actual != expect {
    60  			t.Errorf("%s has %d peers, not %d: %v", s.LocalPeer(), actual, expect, s.Peers())
    61  			t.Log(s.swarm.Dump())
    62  		}
    63  		actual = len(s.Connections())
    64  		if actual != expect {
    65  			t.Errorf("%s has %d conns, not %d: %v", s.LocalPeer(), actual, expect, s.Connections())
    66  			t.Log(s.swarm.Dump())
    67  		}
    68  	}
    69  
    70  	test(s1)
    71  	test(s2)
    72  }