github.com/turingchain2020/turingchain@v1.1.21/system/p2p/dht/extension/pubsub_test.go (about) 1 package extension 2 3 import ( 4 "context" 5 "fmt" 6 "testing" 7 8 core "github.com/libp2p/go-libp2p-core" 9 "github.com/stretchr/testify/require" 10 ) 11 12 func testMsg(topic string, msg SubMsg) { 13 fmt.Println("testMsg", core.PeerID(msg.From).String(), "data", string(msg.Data)) 14 } 15 16 func Test_pubsub(t *testing.T) { 17 ctx, cancel := context.WithCancel(context.Background()) 18 defer cancel() 19 hosts := getNetHosts(ctx, 2, t) 20 connect(t, hosts[0], hosts[1]) 21 22 psub, err := NewPubSub(ctx, hosts[0]) 23 require.Nil(t, err) 24 err = psub.JoinAndSubTopic("bztest", testMsg) 25 require.Nil(t, err) 26 27 err = psub.Publish("bztest", []byte("hello,world")) 28 require.Nil(t, err) 29 err = psub.Publish("bztest2", []byte("hello,world")) 30 require.NotNil(t, err) 31 topics := psub.GetTopics() 32 require.Equal(t, 1, len(topics)) 33 require.Equal(t, "bztest", topics[0]) 34 require.False(t, psub.HasTopic("mytest")) 35 peers := psub.FetchTopicPeers("mytest") 36 t.Log(peers) 37 require.Equal(t, 0, len(peers)) 38 peers = psub.FetchTopicPeers("bztest") 39 t.Log(peers) 40 psub.RemoveTopic("bztest") 41 require.Equal(t, 0, psub.TopicNum()) 42 43 }