github.com/lzy4123/fabric@v2.1.1+incompatible/gossip/util/msgs_test.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package util 8 9 import ( 10 "testing" 11 12 proto "github.com/hyperledger/fabric-protos-go/gossip" 13 "github.com/hyperledger/fabric/gossip/common" 14 "github.com/hyperledger/fabric/gossip/protoext" 15 "github.com/stretchr/testify/assert" 16 ) 17 18 func init() { 19 SetupTestLogging() 20 } 21 22 func TestMembershipStore(t *testing.T) { 23 membershipStore := NewMembershipStore() 24 25 id1 := common.PKIidType("id1") 26 id2 := common.PKIidType("id2") 27 28 msg1 := &protoext.SignedGossipMessage{} 29 msg2 := &protoext.SignedGossipMessage{Envelope: &proto.Envelope{}} 30 31 // Test initially created store is empty 32 assert.Nil(t, membershipStore.MsgByID(id1)) 33 assert.Equal(t, membershipStore.Size(), 0) 34 // Test put works as expected 35 membershipStore.Put(id1, msg1) 36 assert.NotNil(t, membershipStore.MsgByID(id1)) 37 // Test MsgByID returns the right instance stored 38 membershipStore.Put(id2, msg2) 39 assert.Equal(t, msg1, membershipStore.MsgByID(id1)) 40 assert.NotEqual(t, msg2, membershipStore.MsgByID(id1)) 41 // Test capacity grows 42 assert.Equal(t, membershipStore.Size(), 2) 43 // Test remove works 44 membershipStore.Remove(id1) 45 assert.Nil(t, membershipStore.MsgByID(id1)) 46 assert.Equal(t, membershipStore.Size(), 1) 47 // Test returned instance is not a copy 48 msg3 := &protoext.SignedGossipMessage{GossipMessage: &proto.GossipMessage{}} 49 msg3Clone := &protoext.SignedGossipMessage{GossipMessage: &proto.GossipMessage{}} 50 id3 := common.PKIidType("id3") 51 membershipStore.Put(id3, msg3) 52 assert.Equal(t, msg3Clone, msg3) 53 membershipStore.MsgByID(id3).Channel = []byte{0, 1, 2, 3} 54 assert.NotEqual(t, msg3Clone, msg3) 55 } 56 57 func TestToSlice(t *testing.T) { 58 membershipStore := NewMembershipStore() 59 id1 := common.PKIidType("id1") 60 id2 := common.PKIidType("id2") 61 id3 := common.PKIidType("id3") 62 id4 := common.PKIidType("id4") 63 64 msg1 := &protoext.SignedGossipMessage{} 65 msg2 := &protoext.SignedGossipMessage{Envelope: &proto.Envelope{}} 66 msg3 := &protoext.SignedGossipMessage{GossipMessage: &proto.GossipMessage{}} 67 msg4 := &protoext.SignedGossipMessage{GossipMessage: &proto.GossipMessage{}, Envelope: &proto.Envelope{}} 68 69 membershipStore.Put(id1, msg1) 70 membershipStore.Put(id2, msg2) 71 membershipStore.Put(id3, msg3) 72 membershipStore.Put(id4, msg4) 73 74 assert.Len(t, membershipStore.ToSlice(), 4) 75 76 existsInSlice := func(slice []*protoext.SignedGossipMessage, msg *protoext.SignedGossipMessage) bool { 77 for _, m := range slice { 78 if assert.ObjectsAreEqual(m, msg) { 79 return true 80 } 81 } 82 return false 83 } 84 85 expectedMsgs := []*protoext.SignedGossipMessage{msg1, msg2, msg3, msg4} 86 for _, msg := range membershipStore.ToSlice() { 87 assert.True(t, existsInSlice(expectedMsgs, msg)) 88 } 89 90 }