github.com/turingchain2020/turingchain@v1.1.21/system/p2p/dht/protocol/broadcast/pubsub_test.go (about) 1 // Copyright Turing Corp. 2018 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 broadcast 6 7 import ( 8 "testing" 9 10 prototypes "github.com/turingchain2020/turingchain/system/p2p/dht/protocol" 11 "github.com/turingchain2020/turingchain/types" 12 "github.com/turingchain2020/turingchain/util" 13 "github.com/turingchain2020/turingchain/util/testnode" 14 "github.com/stretchr/testify/require" 15 ) 16 17 func testRecvMsg(p *pubSub, topic string, data []byte, buf *[]byte) (types.Message, error) { 18 msg := p.newMsg(topic) 19 err := p.decodeMsg(data, buf, msg) 20 if err != nil { 21 return nil, err 22 } 23 24 return msg, nil 25 } 26 27 func newTestPubSub() *pubSub { 28 p := &pubSub{&broadcastProtocol{}} 29 p.P2PEnv = &prototypes.P2PEnv{} 30 p.ChainCfg = testnode.GetDefaultConfig() 31 32 return p 33 } 34 35 func TestPubSub(t *testing.T) { 36 37 ps := newTestPubSub() 38 addr, priv := util.Genaddress() 39 tx := util.CreateCoinsTx(ps.ChainCfg, priv, addr, 1) 40 block := util.CreateCoinsBlock(ps.ChainCfg, priv, 10000) 41 42 txHash := ps.getMsgHash(psTxTopic, tx) 43 blockHash := ps.getMsgHash(psBlockTopic, block) 44 45 sendBuf := make([]byte, 0) 46 47 txData := ps.encodeMsg(tx, &sendBuf) 48 require.Equal(t, len(txData), len(sendBuf)) 49 50 blockData := ps.encodeMsg(block, &sendBuf) 51 52 require.Equal(t, len(blockData), len(sendBuf)) 53 54 recvBuf := make([]byte, 0) 55 msg, err := testRecvMsg(ps, psTxTopic, txData, &recvBuf) 56 require.Nil(t, err) 57 require.Equal(t, len(types.Encode(tx)), len(recvBuf)) 58 require.Equal(t, txHash, ps.getMsgHash(psTxTopic, msg)) 59 msg, err = testRecvMsg(ps, psBlockTopic, blockData, &recvBuf) 60 require.Nil(t, err) 61 require.Equal(t, blockHash, ps.getMsgHash(psBlockTopic, msg)) 62 }