github.com/ethersphere/bee/v2@v2.2.0/pkg/topology/lightnode/container_test.go (about) 1 // Copyright 2021 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package lightnode_test 6 7 import ( 8 "context" 9 "errors" 10 "reflect" 11 "testing" 12 13 "github.com/ethersphere/bee/v2/pkg/p2p" 14 "github.com/ethersphere/bee/v2/pkg/swarm" 15 "github.com/ethersphere/bee/v2/pkg/topology" 16 "github.com/ethersphere/bee/v2/pkg/topology/lightnode" 17 ) 18 19 func TestContainer(t *testing.T) { 20 t.Parallel() 21 22 base := swarm.RandAddress(t) 23 24 t.Run("new container is empty container", func(t *testing.T) { 25 t.Parallel() 26 27 c := lightnode.NewContainer(base) 28 29 var empty topology.BinInfo 30 31 if !reflect.DeepEqual(empty, c.PeerInfo()) { 32 t.Errorf("expected %v, got %v", empty, c.PeerInfo()) 33 } 34 }) 35 36 t.Run("can add peers to container", func(t *testing.T) { 37 t.Parallel() 38 39 c := lightnode.NewContainer(base) 40 41 p1 := swarm.NewAddress([]byte("123")) 42 p2 := swarm.NewAddress([]byte("456")) 43 c.Connected(context.Background(), p2p.Peer{Address: p1}) 44 c.Connected(context.Background(), p2p.Peer{Address: p2}) 45 46 peerCount := len(c.PeerInfo().ConnectedPeers) 47 48 if peerCount != 2 { 49 t.Errorf("expected %d connected peer, got %d", 2, peerCount) 50 } 51 52 if cc := c.Count(); cc != 2 { 53 t.Errorf("expected count 2 got %d", cc) 54 } 55 p, err := c.RandomPeer(p1) 56 if err != nil { 57 t.Fatal(err) 58 } 59 if !p.Equal(p2) { 60 t.Fatalf("expected p1 but got %s", p.String()) 61 } 62 63 p, err = c.RandomPeer(p2) 64 if err != nil { 65 t.Fatal(err) 66 } 67 if !p.Equal(p1) { 68 t.Fatalf("expected p2 but got %s", p.String()) 69 } 70 71 i := 0 72 peers := []swarm.Address{p1, p2} 73 if err = c.EachPeer(func(p swarm.Address, _ uint8) (bool, bool, error) { 74 if !p.Equal(peers[i]) { 75 return false, false, errors.New("peer not in order") 76 } 77 i++ 78 return false, false, nil 79 }); err != nil { 80 t.Fatal(err) 81 } 82 }) 83 t.Run("empty container after peer disconnect", func(t *testing.T) { 84 t.Parallel() 85 86 c := lightnode.NewContainer(base) 87 88 peer := p2p.Peer{Address: swarm.NewAddress([]byte("123"))} 89 90 c.Connected(context.Background(), peer) 91 c.Disconnected(peer) 92 93 discPeerCount := len(c.PeerInfo().DisconnectedPeers) 94 if discPeerCount != 1 { 95 t.Errorf("expected %d connected peer, got %d", 1, discPeerCount) 96 } 97 98 connPeerCount := len(c.PeerInfo().ConnectedPeers) 99 if connPeerCount != 0 { 100 t.Errorf("expected %d connected peer, got %d", 0, connPeerCount) 101 } 102 if cc := c.Count(); cc != 0 { 103 t.Errorf("expected count 0 got %d", cc) 104 } 105 }) 106 }