github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/mqtt/mqtt_test.go (about) 1 package mqtt_test 2 3 /* 4 import ( 5 "encoding/json" 6 "fmt" 7 "testing" 8 "time" 9 10 mqtt "github.com/eclipse/paho.mqtt.golang" 11 "github.com/google/uuid" 12 . "github.com/onsi/gomega" 13 14 . "github.com/machinefi/w3bstream/pkg/depends/conf/mqtt" 15 ) 16 17 type PayloadBody struct { 18 EventID string 19 PubTimestamp int64 20 Message string 21 } 22 23 func NewPayloadBody(msg string) *PayloadBody { 24 return &PayloadBody{ 25 EventID: uuid.New().String(), 26 PubTimestamp: time.Now().UnixMilli(), 27 Message: msg, 28 } 29 } 30 31 func UnsafeJsonMarshal(v interface{}) []byte { 32 data, _ := json.Marshal(v) 33 return data 34 } 35 36 var ( 37 topic = "test_demo" 38 broker = &Broker{} 39 ) 40 41 func init() { 42 err := broker.Server.UnmarshalText([]byte("mqtt://broker.emqx.io:1883")) 43 if err != nil { 44 panic(err) 45 } 46 47 broker.SetDefault() 48 err = broker.Init() 49 if err != nil { 50 panic(err) 51 } 52 } 53 54 func TestBroker(t *testing.T) { 55 cpub, err := broker.Client("pub") 56 NewWithT(t).Expect(err).To(BeNil()) 57 cpub = cpub.WithTopic(topic).WithQoS(QOS__ONCE) 58 59 csub, err := broker.Client("sub") 60 NewWithT(t).Expect(err).To(BeNil()) 61 csub = csub.WithTopic(topic).WithQoS(QOS__ONCE) 62 63 go func() { 64 err = csub.Subscribe(func(cli mqtt.Client, msg mqtt.Message) { 65 pl := &PayloadBody{} 66 ts := time.Now() 67 NewWithT(t).Expect(json.Unmarshal(msg.Payload(), pl)).To(BeNil()) 68 fmt.Printf("topic: %s cst: %dms\n", msg.Topic(), ts.UnixMilli()-pl.PubTimestamp) 69 }) 70 NewWithT(t).Expect(err).To(BeNil()) 71 }() 72 73 num := 5 74 for i := 0; i < num; i++ { 75 err = cpub.WithRetain(false).Publish(UnsafeJsonMarshal(NewPayloadBody("payload"))) 76 NewWithT(t).Expect(err).To(BeNil()) 77 time.Sleep(100 * time.Millisecond) 78 } 79 80 err = cpub.Unsubscribe() 81 NewWithT(t).Expect(err).To(BeNil()) 82 err = csub.Unsubscribe() 83 NewWithT(t).Expect(err).To(BeNil()) 84 broker.Close(cpub) 85 broker.Close(csub) 86 } 87 */