From 37576b34c82fd6c91298837b0ab0d3002bc7e1bd Mon Sep 17 00:00:00 2001 From: sincos Date: Mon, 22 Jul 2024 13:57:31 +0800 Subject: [PATCH] test(confmws/confmqtt): fix unit test --- confmws/confmqtt/broker.go | 28 +++++++++++++++++----------- confmws/confmqtt/broker_test.go | 8 ++++++++ 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/confmws/confmqtt/broker.go b/confmws/confmqtt/broker.go index 4bec591..b2a6c0f 100644 --- a/confmws/confmqtt/broker.go +++ b/confmws/confmqtt/broker.go @@ -20,6 +20,20 @@ func init() { mqtt.WARN = log.New(os.Stdout, "[MQTT WRN]", log.LstdFlags) } +func LogOnConnectionLost(c mqtt.Client, err error) { + opt := c.OptionsReader() + mqtt.WARN.Printf("connection lost: `%s` caused by %v", opt.ClientID(), err) +} + +func LogOnReconnecting(_ mqtt.Client, opt *mqtt.ClientOptions) { + mqtt.WARN.Printf("reconnecting: `%s`", opt.ClientID) +} + +func LogOnConnected(c mqtt.Client) { + opt := c.OptionsReader() + mqtt.WARN.Printf("client connected: `%s`", opt.ClientID()) +} + type Broker struct { Server datatypex.Endpoint Retry retry.Retry @@ -101,17 +115,9 @@ func (b *Broker) options(cid string) *mqtt.ClientOptions { options.SetConnectTimeout(b.Timeout) options.SetPingTimeout(b.Timeout) - options.SetConnectionLostHandler(func(c mqtt.Client, err error) { - opt := c.OptionsReader() - mqtt.WARN.Printf("connection lost: `%s` caused by %v", opt.ClientID(), err) - }) - options.SetReconnectingHandler(func(_ mqtt.Client, opt *mqtt.ClientOptions) { - mqtt.WARN.Printf("reconnecting: `%s`", opt.ClientID) - }) - options.SetOnConnectHandler(func(c mqtt.Client) { - opt := c.OptionsReader() - mqtt.WARN.Printf("client connected: `%s`", opt.ClientID()) - }) + options.SetConnectionLostHandler(LogOnConnectionLost) + options.SetReconnectingHandler(LogOnReconnecting) + options.SetOnConnectHandler(LogOnConnected) return options } diff --git a/confmws/confmqtt/broker_test.go b/confmws/confmqtt/broker_test.go index 452fc2e..3a8d473 100644 --- a/confmws/confmqtt/broker_test.go +++ b/confmws/confmqtt/broker_test.go @@ -11,6 +11,7 @@ import ( mqtt "github.com/eclipse/paho.mqtt.golang" "github.com/google/uuid" . "github.com/onsi/gomega" + "github.com/pkg/errors" "github.com/xoctopus/x/misc/must" . "github.com/xoctopus/confx/confmws/confmqtt" @@ -122,6 +123,13 @@ func TestBrokerExt(t *testing.T) { NewWithT(t).Expect(err).To(Equal(ErrInvalidTopic)) NewWithT(t).Expect(c).To(BeNil()) }) + t.Run("ClientOptionHooks", func(t *testing.T) { + opt := &mqtt.ClientOptions{ClientID: "logger_client"} + c := mqtt.NewClient(opt) + LogOnConnected(c) + LogOnReconnecting(c, opt) + LogOnConnectionLost(c, errors.New("conn lost")) + }) } func TestClientTimeout(t *testing.T) {